three.js 1.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678
  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 = '136dev';
  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 DepthFormat = 1026;
  116. const DepthStencilFormat = 1027;
  117. const RedFormat = 1028;
  118. const RedIntegerFormat = 1029;
  119. const RGFormat = 1030;
  120. const RGIntegerFormat = 1031;
  121. const RGBIntegerFormat = 1032;
  122. const RGBAIntegerFormat = 1033;
  123. const RGB_S3TC_DXT1_Format = 33776;
  124. const RGBA_S3TC_DXT1_Format = 33777;
  125. const RGBA_S3TC_DXT3_Format = 33778;
  126. const RGBA_S3TC_DXT5_Format = 33779;
  127. const RGB_PVRTC_4BPPV1_Format = 35840;
  128. const RGB_PVRTC_2BPPV1_Format = 35841;
  129. const RGBA_PVRTC_4BPPV1_Format = 35842;
  130. const RGBA_PVRTC_2BPPV1_Format = 35843;
  131. const RGB_ETC1_Format = 36196;
  132. const RGB_ETC2_Format = 37492;
  133. const RGBA_ETC2_EAC_Format = 37496;
  134. const RGBA_ASTC_4x4_Format = 37808;
  135. const RGBA_ASTC_5x4_Format = 37809;
  136. const RGBA_ASTC_5x5_Format = 37810;
  137. const RGBA_ASTC_6x5_Format = 37811;
  138. const RGBA_ASTC_6x6_Format = 37812;
  139. const RGBA_ASTC_8x5_Format = 37813;
  140. const RGBA_ASTC_8x6_Format = 37814;
  141. const RGBA_ASTC_8x8_Format = 37815;
  142. const RGBA_ASTC_10x5_Format = 37816;
  143. const RGBA_ASTC_10x6_Format = 37817;
  144. const RGBA_ASTC_10x8_Format = 37818;
  145. const RGBA_ASTC_10x10_Format = 37819;
  146. const RGBA_ASTC_12x10_Format = 37820;
  147. const RGBA_ASTC_12x12_Format = 37821;
  148. const RGBA_BPTC_Format = 36492;
  149. const SRGB8_ALPHA8_ASTC_4x4_Format = 37840;
  150. const SRGB8_ALPHA8_ASTC_5x4_Format = 37841;
  151. const SRGB8_ALPHA8_ASTC_5x5_Format = 37842;
  152. const SRGB8_ALPHA8_ASTC_6x5_Format = 37843;
  153. const SRGB8_ALPHA8_ASTC_6x6_Format = 37844;
  154. const SRGB8_ALPHA8_ASTC_8x5_Format = 37845;
  155. const SRGB8_ALPHA8_ASTC_8x6_Format = 37846;
  156. const SRGB8_ALPHA8_ASTC_8x8_Format = 37847;
  157. const SRGB8_ALPHA8_ASTC_10x5_Format = 37848;
  158. const SRGB8_ALPHA8_ASTC_10x6_Format = 37849;
  159. const SRGB8_ALPHA8_ASTC_10x8_Format = 37850;
  160. const SRGB8_ALPHA8_ASTC_10x10_Format = 37851;
  161. const SRGB8_ALPHA8_ASTC_12x10_Format = 37852;
  162. const SRGB8_ALPHA8_ASTC_12x12_Format = 37853;
  163. const LoopOnce = 2200;
  164. const LoopRepeat = 2201;
  165. const LoopPingPong = 2202;
  166. const InterpolateDiscrete = 2300;
  167. const InterpolateLinear = 2301;
  168. const InterpolateSmooth = 2302;
  169. const ZeroCurvatureEnding = 2400;
  170. const ZeroSlopeEnding = 2401;
  171. const WrapAroundEnding = 2402;
  172. const NormalAnimationBlendMode = 2500;
  173. const AdditiveAnimationBlendMode = 2501;
  174. const TrianglesDrawMode = 0;
  175. const TriangleStripDrawMode = 1;
  176. const TriangleFanDrawMode = 2;
  177. const LinearEncoding = 3000;
  178. const sRGBEncoding = 3001;
  179. const BasicDepthPacking = 3200;
  180. const RGBADepthPacking = 3201;
  181. const TangentSpaceNormalMap = 0;
  182. const ObjectSpaceNormalMap = 1;
  183. const ZeroStencilOp = 0;
  184. const KeepStencilOp = 7680;
  185. const ReplaceStencilOp = 7681;
  186. const IncrementStencilOp = 7682;
  187. const DecrementStencilOp = 7683;
  188. const IncrementWrapStencilOp = 34055;
  189. const DecrementWrapStencilOp = 34056;
  190. const InvertStencilOp = 5386;
  191. const NeverStencilFunc = 512;
  192. const LessStencilFunc = 513;
  193. const EqualStencilFunc = 514;
  194. const LessEqualStencilFunc = 515;
  195. const GreaterStencilFunc = 516;
  196. const NotEqualStencilFunc = 517;
  197. const GreaterEqualStencilFunc = 518;
  198. const AlwaysStencilFunc = 519;
  199. const StaticDrawUsage = 35044;
  200. const DynamicDrawUsage = 35048;
  201. const StreamDrawUsage = 35040;
  202. const StaticReadUsage = 35045;
  203. const DynamicReadUsage = 35049;
  204. const StreamReadUsage = 35041;
  205. const StaticCopyUsage = 35046;
  206. const DynamicCopyUsage = 35050;
  207. const StreamCopyUsage = 35042;
  208. const GLSL1 = '100';
  209. const GLSL3 = '300 es';
  210. /**
  211. * https://github.com/mrdoob/eventdispatcher.js/
  212. */
  213. class EventDispatcher {
  214. addEventListener(type, listener) {
  215. if (this._listeners === undefined) this._listeners = {};
  216. const listeners = this._listeners;
  217. if (listeners[type] === undefined) {
  218. listeners[type] = [];
  219. }
  220. if (listeners[type].indexOf(listener) === -1) {
  221. listeners[type].push(listener);
  222. }
  223. }
  224. hasEventListener(type, listener) {
  225. if (this._listeners === undefined) return false;
  226. const listeners = this._listeners;
  227. return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
  228. }
  229. removeEventListener(type, listener) {
  230. if (this._listeners === undefined) return;
  231. const listeners = this._listeners;
  232. const listenerArray = listeners[type];
  233. if (listenerArray !== undefined) {
  234. const index = listenerArray.indexOf(listener);
  235. if (index !== -1) {
  236. listenerArray.splice(index, 1);
  237. }
  238. }
  239. }
  240. dispatchEvent(event) {
  241. if (this._listeners === undefined) return;
  242. const listeners = this._listeners;
  243. const listenerArray = listeners[event.type];
  244. if (listenerArray !== undefined) {
  245. event.target = this; // Make a copy, in case listeners are removed while iterating.
  246. const array = listenerArray.slice(0);
  247. for (let i = 0, l = array.length; i < l; i++) {
  248. array[i].call(this, event);
  249. }
  250. event.target = null;
  251. }
  252. }
  253. }
  254. const _lut = [];
  255. for (let i = 0; i < 256; i++) {
  256. _lut[i] = (i < 16 ? '0' : '') + i.toString(16);
  257. }
  258. let _seed = 1234567;
  259. const DEG2RAD = Math.PI / 180;
  260. const RAD2DEG = 180 / Math.PI; // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  261. function generateUUID() {
  262. const d0 = Math.random() * 0xffffffff | 0;
  263. const d1 = Math.random() * 0xffffffff | 0;
  264. const d2 = Math.random() * 0xffffffff | 0;
  265. const d3 = Math.random() * 0xffffffff | 0;
  266. 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.
  267. return uuid.toUpperCase();
  268. }
  269. function clamp(value, min, max) {
  270. return Math.max(min, Math.min(max, value));
  271. } // compute euclidian modulo of m % n
  272. // https://en.wikipedia.org/wiki/Modulo_operation
  273. function euclideanModulo(n, m) {
  274. return (n % m + m) % m;
  275. } // Linear mapping from range <a1, a2> to range <b1, b2>
  276. function mapLinear(x, a1, a2, b1, b2) {
  277. return b1 + (x - a1) * (b2 - b1) / (a2 - a1);
  278. } // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  279. function inverseLerp(x, y, value) {
  280. if (x !== y) {
  281. return (value - x) / (y - x);
  282. } else {
  283. return 0;
  284. }
  285. } // https://en.wikipedia.org/wiki/Linear_interpolation
  286. function lerp(x, y, t) {
  287. return (1 - t) * x + t * y;
  288. } // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  289. function damp(x, y, lambda, dt) {
  290. return lerp(x, y, 1 - Math.exp(-lambda * dt));
  291. } // https://www.desmos.com/calculator/vcsjnyz7x4
  292. function pingpong(x, length = 1) {
  293. return length - Math.abs(euclideanModulo(x, length * 2) - length);
  294. } // http://en.wikipedia.org/wiki/Smoothstep
  295. function smoothstep(x, min, max) {
  296. if (x <= min) return 0;
  297. if (x >= max) return 1;
  298. x = (x - min) / (max - min);
  299. return x * x * (3 - 2 * x);
  300. }
  301. function smootherstep(x, min, max) {
  302. if (x <= min) return 0;
  303. if (x >= max) return 1;
  304. x = (x - min) / (max - min);
  305. return x * x * x * (x * (x * 6 - 15) + 10);
  306. } // Random integer from <low, high> interval
  307. function randInt(low, high) {
  308. return low + Math.floor(Math.random() * (high - low + 1));
  309. } // Random float from <low, high> interval
  310. function randFloat(low, high) {
  311. return low + Math.random() * (high - low);
  312. } // Random float from <-range/2, range/2> interval
  313. function randFloatSpread(range) {
  314. return range * (0.5 - Math.random());
  315. } // Deterministic pseudo-random float in the interval [ 0, 1 ]
  316. function seededRandom(s) {
  317. if (s !== undefined) _seed = s % 2147483647; // Park-Miller algorithm
  318. _seed = _seed * 16807 % 2147483647;
  319. return (_seed - 1) / 2147483646;
  320. }
  321. function degToRad(degrees) {
  322. return degrees * DEG2RAD;
  323. }
  324. function radToDeg(radians) {
  325. return radians * RAD2DEG;
  326. }
  327. function isPowerOfTwo(value) {
  328. return (value & value - 1) === 0 && value !== 0;
  329. }
  330. function ceilPowerOfTwo(value) {
  331. return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
  332. }
  333. function floorPowerOfTwo(value) {
  334. return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
  335. }
  336. function setQuaternionFromProperEuler(q, a, b, c, order) {
  337. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  338. // rotations are applied to the axes in the order specified by 'order'
  339. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  340. // angles are in radians
  341. const cos = Math.cos;
  342. const sin = Math.sin;
  343. const c2 = cos(b / 2);
  344. const s2 = sin(b / 2);
  345. const c13 = cos((a + c) / 2);
  346. const s13 = sin((a + c) / 2);
  347. const c1_3 = cos((a - c) / 2);
  348. const s1_3 = sin((a - c) / 2);
  349. const c3_1 = cos((c - a) / 2);
  350. const s3_1 = sin((c - a) / 2);
  351. switch (order) {
  352. case 'XYX':
  353. q.set(c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13);
  354. break;
  355. case 'YZY':
  356. q.set(s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13);
  357. break;
  358. case 'ZXZ':
  359. q.set(s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13);
  360. break;
  361. case 'XZX':
  362. q.set(c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13);
  363. break;
  364. case 'YXY':
  365. q.set(s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13);
  366. break;
  367. case 'ZYZ':
  368. q.set(s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13);
  369. break;
  370. default:
  371. console.warn('THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order);
  372. }
  373. }
  374. var MathUtils = /*#__PURE__*/Object.freeze({
  375. __proto__: null,
  376. DEG2RAD: DEG2RAD,
  377. RAD2DEG: RAD2DEG,
  378. generateUUID: generateUUID,
  379. clamp: clamp,
  380. euclideanModulo: euclideanModulo,
  381. mapLinear: mapLinear,
  382. inverseLerp: inverseLerp,
  383. lerp: lerp,
  384. damp: damp,
  385. pingpong: pingpong,
  386. smoothstep: smoothstep,
  387. smootherstep: smootherstep,
  388. randInt: randInt,
  389. randFloat: randFloat,
  390. randFloatSpread: randFloatSpread,
  391. seededRandom: seededRandom,
  392. degToRad: degToRad,
  393. radToDeg: radToDeg,
  394. isPowerOfTwo: isPowerOfTwo,
  395. ceilPowerOfTwo: ceilPowerOfTwo,
  396. floorPowerOfTwo: floorPowerOfTwo,
  397. setQuaternionFromProperEuler: setQuaternionFromProperEuler
  398. });
  399. class Vector2 {
  400. constructor(x = 0, y = 0) {
  401. this.x = x;
  402. this.y = y;
  403. }
  404. get width() {
  405. return this.x;
  406. }
  407. set width(value) {
  408. this.x = value;
  409. }
  410. get height() {
  411. return this.y;
  412. }
  413. set height(value) {
  414. this.y = value;
  415. }
  416. set(x, y) {
  417. this.x = x;
  418. this.y = y;
  419. return this;
  420. }
  421. setScalar(scalar) {
  422. this.x = scalar;
  423. this.y = scalar;
  424. return this;
  425. }
  426. setX(x) {
  427. this.x = x;
  428. return this;
  429. }
  430. setY(y) {
  431. this.y = y;
  432. return this;
  433. }
  434. setComponent(index, value) {
  435. switch (index) {
  436. case 0:
  437. this.x = value;
  438. break;
  439. case 1:
  440. this.y = value;
  441. break;
  442. default:
  443. throw new Error('index is out of range: ' + index);
  444. }
  445. return this;
  446. }
  447. getComponent(index) {
  448. switch (index) {
  449. case 0:
  450. return this.x;
  451. case 1:
  452. return this.y;
  453. default:
  454. throw new Error('index is out of range: ' + index);
  455. }
  456. }
  457. clone() {
  458. return new this.constructor(this.x, this.y);
  459. }
  460. copy(v) {
  461. this.x = v.x;
  462. this.y = v.y;
  463. return this;
  464. }
  465. add(v, w) {
  466. if (w !== undefined) {
  467. console.warn('THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  468. return this.addVectors(v, w);
  469. }
  470. this.x += v.x;
  471. this.y += v.y;
  472. return this;
  473. }
  474. addScalar(s) {
  475. this.x += s;
  476. this.y += s;
  477. return this;
  478. }
  479. addVectors(a, b) {
  480. this.x = a.x + b.x;
  481. this.y = a.y + b.y;
  482. return this;
  483. }
  484. addScaledVector(v, s) {
  485. this.x += v.x * s;
  486. this.y += v.y * s;
  487. return this;
  488. }
  489. sub(v, w) {
  490. if (w !== undefined) {
  491. console.warn('THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  492. return this.subVectors(v, w);
  493. }
  494. this.x -= v.x;
  495. this.y -= v.y;
  496. return this;
  497. }
  498. subScalar(s) {
  499. this.x -= s;
  500. this.y -= s;
  501. return this;
  502. }
  503. subVectors(a, b) {
  504. this.x = a.x - b.x;
  505. this.y = a.y - b.y;
  506. return this;
  507. }
  508. multiply(v) {
  509. this.x *= v.x;
  510. this.y *= v.y;
  511. return this;
  512. }
  513. multiplyScalar(scalar) {
  514. this.x *= scalar;
  515. this.y *= scalar;
  516. return this;
  517. }
  518. divide(v) {
  519. this.x /= v.x;
  520. this.y /= v.y;
  521. return this;
  522. }
  523. divideScalar(scalar) {
  524. return this.multiplyScalar(1 / scalar);
  525. }
  526. applyMatrix3(m) {
  527. const x = this.x,
  528. y = this.y;
  529. const e = m.elements;
  530. this.x = e[0] * x + e[3] * y + e[6];
  531. this.y = e[1] * x + e[4] * y + e[7];
  532. return this;
  533. }
  534. min(v) {
  535. this.x = Math.min(this.x, v.x);
  536. this.y = Math.min(this.y, v.y);
  537. return this;
  538. }
  539. max(v) {
  540. this.x = Math.max(this.x, v.x);
  541. this.y = Math.max(this.y, v.y);
  542. return this;
  543. }
  544. clamp(min, max) {
  545. // assumes min < max, componentwise
  546. this.x = Math.max(min.x, Math.min(max.x, this.x));
  547. this.y = Math.max(min.y, Math.min(max.y, this.y));
  548. return this;
  549. }
  550. clampScalar(minVal, maxVal) {
  551. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  552. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  553. return this;
  554. }
  555. clampLength(min, max) {
  556. const length = this.length();
  557. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  558. }
  559. floor() {
  560. this.x = Math.floor(this.x);
  561. this.y = Math.floor(this.y);
  562. return this;
  563. }
  564. ceil() {
  565. this.x = Math.ceil(this.x);
  566. this.y = Math.ceil(this.y);
  567. return this;
  568. }
  569. round() {
  570. this.x = Math.round(this.x);
  571. this.y = Math.round(this.y);
  572. return this;
  573. }
  574. roundToZero() {
  575. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  576. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  577. return this;
  578. }
  579. negate() {
  580. this.x = -this.x;
  581. this.y = -this.y;
  582. return this;
  583. }
  584. dot(v) {
  585. return this.x * v.x + this.y * v.y;
  586. }
  587. cross(v) {
  588. return this.x * v.y - this.y * v.x;
  589. }
  590. lengthSq() {
  591. return this.x * this.x + this.y * this.y;
  592. }
  593. length() {
  594. return Math.sqrt(this.x * this.x + this.y * this.y);
  595. }
  596. manhattanLength() {
  597. return Math.abs(this.x) + Math.abs(this.y);
  598. }
  599. normalize() {
  600. return this.divideScalar(this.length() || 1);
  601. }
  602. angle() {
  603. // computes the angle in radians with respect to the positive x-axis
  604. const angle = Math.atan2(-this.y, -this.x) + Math.PI;
  605. return angle;
  606. }
  607. distanceTo(v) {
  608. return Math.sqrt(this.distanceToSquared(v));
  609. }
  610. distanceToSquared(v) {
  611. const dx = this.x - v.x,
  612. dy = this.y - v.y;
  613. return dx * dx + dy * dy;
  614. }
  615. manhattanDistanceTo(v) {
  616. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);
  617. }
  618. setLength(length) {
  619. return this.normalize().multiplyScalar(length);
  620. }
  621. lerp(v, alpha) {
  622. this.x += (v.x - this.x) * alpha;
  623. this.y += (v.y - this.y) * alpha;
  624. return this;
  625. }
  626. lerpVectors(v1, v2, alpha) {
  627. this.x = v1.x + (v2.x - v1.x) * alpha;
  628. this.y = v1.y + (v2.y - v1.y) * alpha;
  629. return this;
  630. }
  631. equals(v) {
  632. return v.x === this.x && v.y === this.y;
  633. }
  634. fromArray(array, offset = 0) {
  635. this.x = array[offset];
  636. this.y = array[offset + 1];
  637. return this;
  638. }
  639. toArray(array = [], offset = 0) {
  640. array[offset] = this.x;
  641. array[offset + 1] = this.y;
  642. return array;
  643. }
  644. fromBufferAttribute(attribute, index, offset) {
  645. if (offset !== undefined) {
  646. console.warn('THREE.Vector2: offset has been removed from .fromBufferAttribute().');
  647. }
  648. this.x = attribute.getX(index);
  649. this.y = attribute.getY(index);
  650. return this;
  651. }
  652. rotateAround(center, angle) {
  653. const c = Math.cos(angle),
  654. s = Math.sin(angle);
  655. const x = this.x - center.x;
  656. const y = this.y - center.y;
  657. this.x = x * c - y * s + center.x;
  658. this.y = x * s + y * c + center.y;
  659. return this;
  660. }
  661. random() {
  662. this.x = Math.random();
  663. this.y = Math.random();
  664. return this;
  665. }
  666. *[Symbol.iterator]() {
  667. yield this.x;
  668. yield this.y;
  669. }
  670. }
  671. Vector2.prototype.isVector2 = true;
  672. class Matrix3 {
  673. constructor() {
  674. this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  675. if (arguments.length > 0) {
  676. console.error('THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.');
  677. }
  678. }
  679. set(n11, n12, n13, n21, n22, n23, n31, n32, n33) {
  680. const te = this.elements;
  681. te[0] = n11;
  682. te[1] = n21;
  683. te[2] = n31;
  684. te[3] = n12;
  685. te[4] = n22;
  686. te[5] = n32;
  687. te[6] = n13;
  688. te[7] = n23;
  689. te[8] = n33;
  690. return this;
  691. }
  692. identity() {
  693. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  694. return this;
  695. }
  696. copy(m) {
  697. const te = this.elements;
  698. const me = m.elements;
  699. te[0] = me[0];
  700. te[1] = me[1];
  701. te[2] = me[2];
  702. te[3] = me[3];
  703. te[4] = me[4];
  704. te[5] = me[5];
  705. te[6] = me[6];
  706. te[7] = me[7];
  707. te[8] = me[8];
  708. return this;
  709. }
  710. extractBasis(xAxis, yAxis, zAxis) {
  711. xAxis.setFromMatrix3Column(this, 0);
  712. yAxis.setFromMatrix3Column(this, 1);
  713. zAxis.setFromMatrix3Column(this, 2);
  714. return this;
  715. }
  716. setFromMatrix4(m) {
  717. const me = m.elements;
  718. this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]);
  719. return this;
  720. }
  721. multiply(m) {
  722. return this.multiplyMatrices(this, m);
  723. }
  724. premultiply(m) {
  725. return this.multiplyMatrices(m, this);
  726. }
  727. multiplyMatrices(a, b) {
  728. const ae = a.elements;
  729. const be = b.elements;
  730. const te = this.elements;
  731. const a11 = ae[0],
  732. a12 = ae[3],
  733. a13 = ae[6];
  734. const a21 = ae[1],
  735. a22 = ae[4],
  736. a23 = ae[7];
  737. const a31 = ae[2],
  738. a32 = ae[5],
  739. a33 = ae[8];
  740. const b11 = be[0],
  741. b12 = be[3],
  742. b13 = be[6];
  743. const b21 = be[1],
  744. b22 = be[4],
  745. b23 = be[7];
  746. const b31 = be[2],
  747. b32 = be[5],
  748. b33 = be[8];
  749. te[0] = a11 * b11 + a12 * b21 + a13 * b31;
  750. te[3] = a11 * b12 + a12 * b22 + a13 * b32;
  751. te[6] = a11 * b13 + a12 * b23 + a13 * b33;
  752. te[1] = a21 * b11 + a22 * b21 + a23 * b31;
  753. te[4] = a21 * b12 + a22 * b22 + a23 * b32;
  754. te[7] = a21 * b13 + a22 * b23 + a23 * b33;
  755. te[2] = a31 * b11 + a32 * b21 + a33 * b31;
  756. te[5] = a31 * b12 + a32 * b22 + a33 * b32;
  757. te[8] = a31 * b13 + a32 * b23 + a33 * b33;
  758. return this;
  759. }
  760. multiplyScalar(s) {
  761. const te = this.elements;
  762. te[0] *= s;
  763. te[3] *= s;
  764. te[6] *= s;
  765. te[1] *= s;
  766. te[4] *= s;
  767. te[7] *= s;
  768. te[2] *= s;
  769. te[5] *= s;
  770. te[8] *= s;
  771. return this;
  772. }
  773. determinant() {
  774. const te = this.elements;
  775. const a = te[0],
  776. b = te[1],
  777. c = te[2],
  778. d = te[3],
  779. e = te[4],
  780. f = te[5],
  781. g = te[6],
  782. h = te[7],
  783. i = te[8];
  784. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  785. }
  786. invert() {
  787. const te = this.elements,
  788. n11 = te[0],
  789. n21 = te[1],
  790. n31 = te[2],
  791. n12 = te[3],
  792. n22 = te[4],
  793. n32 = te[5],
  794. n13 = te[6],
  795. n23 = te[7],
  796. n33 = te[8],
  797. t11 = n33 * n22 - n32 * n23,
  798. t12 = n32 * n13 - n33 * n12,
  799. t13 = n23 * n12 - n22 * n13,
  800. det = n11 * t11 + n21 * t12 + n31 * t13;
  801. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  802. const detInv = 1 / det;
  803. te[0] = t11 * detInv;
  804. te[1] = (n31 * n23 - n33 * n21) * detInv;
  805. te[2] = (n32 * n21 - n31 * n22) * detInv;
  806. te[3] = t12 * detInv;
  807. te[4] = (n33 * n11 - n31 * n13) * detInv;
  808. te[5] = (n31 * n12 - n32 * n11) * detInv;
  809. te[6] = t13 * detInv;
  810. te[7] = (n21 * n13 - n23 * n11) * detInv;
  811. te[8] = (n22 * n11 - n21 * n12) * detInv;
  812. return this;
  813. }
  814. transpose() {
  815. let tmp;
  816. const m = this.elements;
  817. tmp = m[1];
  818. m[1] = m[3];
  819. m[3] = tmp;
  820. tmp = m[2];
  821. m[2] = m[6];
  822. m[6] = tmp;
  823. tmp = m[5];
  824. m[5] = m[7];
  825. m[7] = tmp;
  826. return this;
  827. }
  828. getNormalMatrix(matrix4) {
  829. return this.setFromMatrix4(matrix4).invert().transpose();
  830. }
  831. transposeIntoArray(r) {
  832. const m = this.elements;
  833. r[0] = m[0];
  834. r[1] = m[3];
  835. r[2] = m[6];
  836. r[3] = m[1];
  837. r[4] = m[4];
  838. r[5] = m[7];
  839. r[6] = m[2];
  840. r[7] = m[5];
  841. r[8] = m[8];
  842. return this;
  843. }
  844. setUvTransform(tx, ty, sx, sy, rotation, cx, cy) {
  845. const c = Math.cos(rotation);
  846. const s = Math.sin(rotation);
  847. 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);
  848. return this;
  849. }
  850. scale(sx, sy) {
  851. const te = this.elements;
  852. te[0] *= sx;
  853. te[3] *= sx;
  854. te[6] *= sx;
  855. te[1] *= sy;
  856. te[4] *= sy;
  857. te[7] *= sy;
  858. return this;
  859. }
  860. rotate(theta) {
  861. const c = Math.cos(theta);
  862. const s = Math.sin(theta);
  863. const te = this.elements;
  864. const a11 = te[0],
  865. a12 = te[3],
  866. a13 = te[6];
  867. const a21 = te[1],
  868. a22 = te[4],
  869. a23 = te[7];
  870. te[0] = c * a11 + s * a21;
  871. te[3] = c * a12 + s * a22;
  872. te[6] = c * a13 + s * a23;
  873. te[1] = -s * a11 + c * a21;
  874. te[4] = -s * a12 + c * a22;
  875. te[7] = -s * a13 + c * a23;
  876. return this;
  877. }
  878. translate(tx, ty) {
  879. const te = this.elements;
  880. te[0] += tx * te[2];
  881. te[3] += tx * te[5];
  882. te[6] += tx * te[8];
  883. te[1] += ty * te[2];
  884. te[4] += ty * te[5];
  885. te[7] += ty * te[8];
  886. return this;
  887. }
  888. equals(matrix) {
  889. const te = this.elements;
  890. const me = matrix.elements;
  891. for (let i = 0; i < 9; i++) {
  892. if (te[i] !== me[i]) return false;
  893. }
  894. return true;
  895. }
  896. fromArray(array, offset = 0) {
  897. for (let i = 0; i < 9; i++) {
  898. this.elements[i] = array[i + offset];
  899. }
  900. return this;
  901. }
  902. toArray(array = [], offset = 0) {
  903. const te = this.elements;
  904. array[offset] = te[0];
  905. array[offset + 1] = te[1];
  906. array[offset + 2] = te[2];
  907. array[offset + 3] = te[3];
  908. array[offset + 4] = te[4];
  909. array[offset + 5] = te[5];
  910. array[offset + 6] = te[6];
  911. array[offset + 7] = te[7];
  912. array[offset + 8] = te[8];
  913. return array;
  914. }
  915. clone() {
  916. return new this.constructor().fromArray(this.elements);
  917. }
  918. }
  919. Matrix3.prototype.isMatrix3 = true;
  920. function arrayMax(array) {
  921. if (array.length === 0) return -Infinity;
  922. let max = array[0];
  923. for (let i = 1, l = array.length; i < l; ++i) {
  924. if (array[i] > max) max = array[i];
  925. }
  926. return max;
  927. }
  928. const TYPED_ARRAYS = {
  929. Int8Array: Int8Array,
  930. Uint8Array: Uint8Array,
  931. Uint8ClampedArray: Uint8ClampedArray,
  932. Int16Array: Int16Array,
  933. Uint16Array: Uint16Array,
  934. Int32Array: Int32Array,
  935. Uint32Array: Uint32Array,
  936. Float32Array: Float32Array,
  937. Float64Array: Float64Array
  938. };
  939. function getTypedArray(type, buffer) {
  940. return new TYPED_ARRAYS[type](buffer);
  941. }
  942. function createElementNS(name) {
  943. return document.createElementNS('http://www.w3.org/1999/xhtml', name);
  944. }
  945. let _canvas;
  946. class ImageUtils {
  947. static getDataURL(image) {
  948. if (/^data:/i.test(image.src)) {
  949. return image.src;
  950. }
  951. if (typeof HTMLCanvasElement == 'undefined') {
  952. return image.src;
  953. }
  954. let canvas;
  955. if (image instanceof HTMLCanvasElement) {
  956. canvas = image;
  957. } else {
  958. if (_canvas === undefined) _canvas = createElementNS('canvas');
  959. _canvas.width = image.width;
  960. _canvas.height = image.height;
  961. const context = _canvas.getContext('2d');
  962. if (image instanceof ImageData) {
  963. context.putImageData(image, 0, 0);
  964. } else {
  965. context.drawImage(image, 0, 0, image.width, image.height);
  966. }
  967. canvas = _canvas;
  968. }
  969. if (canvas.width > 2048 || canvas.height > 2048) {
  970. console.warn('THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image);
  971. return canvas.toDataURL('image/jpeg', 0.6);
  972. } else {
  973. return canvas.toDataURL('image/png');
  974. }
  975. }
  976. }
  977. let textureId = 0;
  978. class Texture extends EventDispatcher {
  979. 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) {
  980. super();
  981. Object.defineProperty(this, 'id', {
  982. value: textureId++
  983. });
  984. this.uuid = generateUUID();
  985. this.name = '';
  986. this.image = image;
  987. this.mipmaps = [];
  988. this.mapping = mapping;
  989. this.wrapS = wrapS;
  990. this.wrapT = wrapT;
  991. this.magFilter = magFilter;
  992. this.minFilter = minFilter;
  993. this.anisotropy = anisotropy;
  994. this.format = format;
  995. this.internalFormat = null;
  996. this.type = type;
  997. this.offset = new Vector2(0, 0);
  998. this.repeat = new Vector2(1, 1);
  999. this.center = new Vector2(0, 0);
  1000. this.rotation = 0;
  1001. this.matrixAutoUpdate = true;
  1002. this.matrix = new Matrix3();
  1003. this.generateMipmaps = true;
  1004. this.premultiplyAlpha = false;
  1005. this.flipY = true;
  1006. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1007. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  1008. //
  1009. // Also changing the encoding after already used by a Material will not automatically make the Material
  1010. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  1011. this.encoding = encoding;
  1012. this.userData = {};
  1013. this.version = 0;
  1014. this.onUpdate = null;
  1015. this.isRenderTargetTexture = false;
  1016. }
  1017. updateMatrix() {
  1018. this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  1019. }
  1020. clone() {
  1021. return new this.constructor().copy(this);
  1022. }
  1023. copy(source) {
  1024. this.name = source.name;
  1025. this.image = source.image;
  1026. this.mipmaps = source.mipmaps.slice(0);
  1027. this.mapping = source.mapping;
  1028. this.wrapS = source.wrapS;
  1029. this.wrapT = source.wrapT;
  1030. this.magFilter = source.magFilter;
  1031. this.minFilter = source.minFilter;
  1032. this.anisotropy = source.anisotropy;
  1033. this.format = source.format;
  1034. this.internalFormat = source.internalFormat;
  1035. this.type = source.type;
  1036. this.offset.copy(source.offset);
  1037. this.repeat.copy(source.repeat);
  1038. this.center.copy(source.center);
  1039. this.rotation = source.rotation;
  1040. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1041. this.matrix.copy(source.matrix);
  1042. this.generateMipmaps = source.generateMipmaps;
  1043. this.premultiplyAlpha = source.premultiplyAlpha;
  1044. this.flipY = source.flipY;
  1045. this.unpackAlignment = source.unpackAlignment;
  1046. this.encoding = source.encoding;
  1047. this.userData = JSON.parse(JSON.stringify(source.userData));
  1048. return this;
  1049. }
  1050. toJSON(meta) {
  1051. const isRootObject = meta === undefined || typeof meta === 'string';
  1052. if (!isRootObject && meta.textures[this.uuid] !== undefined) {
  1053. return meta.textures[this.uuid];
  1054. }
  1055. const output = {
  1056. metadata: {
  1057. version: 4.5,
  1058. type: 'Texture',
  1059. generator: 'Texture.toJSON'
  1060. },
  1061. uuid: this.uuid,
  1062. name: this.name,
  1063. mapping: this.mapping,
  1064. repeat: [this.repeat.x, this.repeat.y],
  1065. offset: [this.offset.x, this.offset.y],
  1066. center: [this.center.x, this.center.y],
  1067. rotation: this.rotation,
  1068. wrap: [this.wrapS, this.wrapT],
  1069. format: this.format,
  1070. type: this.type,
  1071. encoding: this.encoding,
  1072. minFilter: this.minFilter,
  1073. magFilter: this.magFilter,
  1074. anisotropy: this.anisotropy,
  1075. flipY: this.flipY,
  1076. premultiplyAlpha: this.premultiplyAlpha,
  1077. unpackAlignment: this.unpackAlignment
  1078. };
  1079. if (this.image !== undefined) {
  1080. // TODO: Move to THREE.Image
  1081. const image = this.image;
  1082. if (image.uuid === undefined) {
  1083. image.uuid = generateUUID(); // UGH
  1084. }
  1085. if (!isRootObject && meta.images[image.uuid] === undefined) {
  1086. let url;
  1087. if (Array.isArray(image)) {
  1088. // process array of images e.g. CubeTexture
  1089. url = [];
  1090. for (let i = 0, l = image.length; i < l; i++) {
  1091. // check cube texture with data textures
  1092. if (image[i].isDataTexture) {
  1093. url.push(serializeImage(image[i].image));
  1094. } else {
  1095. url.push(serializeImage(image[i]));
  1096. }
  1097. }
  1098. } else {
  1099. // process single image
  1100. url = serializeImage(image);
  1101. }
  1102. meta.images[image.uuid] = {
  1103. uuid: image.uuid,
  1104. url: url
  1105. };
  1106. }
  1107. output.image = image.uuid;
  1108. }
  1109. if (JSON.stringify(this.userData) !== '{}') output.userData = this.userData;
  1110. if (!isRootObject) {
  1111. meta.textures[this.uuid] = output;
  1112. }
  1113. return output;
  1114. }
  1115. dispose() {
  1116. this.dispatchEvent({
  1117. type: 'dispose'
  1118. });
  1119. }
  1120. transformUv(uv) {
  1121. if (this.mapping !== UVMapping) return uv;
  1122. uv.applyMatrix3(this.matrix);
  1123. if (uv.x < 0 || uv.x > 1) {
  1124. switch (this.wrapS) {
  1125. case RepeatWrapping:
  1126. uv.x = uv.x - Math.floor(uv.x);
  1127. break;
  1128. case ClampToEdgeWrapping:
  1129. uv.x = uv.x < 0 ? 0 : 1;
  1130. break;
  1131. case MirroredRepeatWrapping:
  1132. if (Math.abs(Math.floor(uv.x) % 2) === 1) {
  1133. uv.x = Math.ceil(uv.x) - uv.x;
  1134. } else {
  1135. uv.x = uv.x - Math.floor(uv.x);
  1136. }
  1137. break;
  1138. }
  1139. }
  1140. if (uv.y < 0 || uv.y > 1) {
  1141. switch (this.wrapT) {
  1142. case RepeatWrapping:
  1143. uv.y = uv.y - Math.floor(uv.y);
  1144. break;
  1145. case ClampToEdgeWrapping:
  1146. uv.y = uv.y < 0 ? 0 : 1;
  1147. break;
  1148. case MirroredRepeatWrapping:
  1149. if (Math.abs(Math.floor(uv.y) % 2) === 1) {
  1150. uv.y = Math.ceil(uv.y) - uv.y;
  1151. } else {
  1152. uv.y = uv.y - Math.floor(uv.y);
  1153. }
  1154. break;
  1155. }
  1156. }
  1157. if (this.flipY) {
  1158. uv.y = 1 - uv.y;
  1159. }
  1160. return uv;
  1161. }
  1162. set needsUpdate(value) {
  1163. if (value === true) this.version++;
  1164. }
  1165. }
  1166. Texture.DEFAULT_IMAGE = undefined;
  1167. Texture.DEFAULT_MAPPING = UVMapping;
  1168. Texture.prototype.isTexture = true;
  1169. function serializeImage(image) {
  1170. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  1171. // default images
  1172. return ImageUtils.getDataURL(image);
  1173. } else {
  1174. if (image.data) {
  1175. // images of DataTexture
  1176. return {
  1177. data: Array.prototype.slice.call(image.data),
  1178. width: image.width,
  1179. height: image.height,
  1180. type: image.data.constructor.name
  1181. };
  1182. } else {
  1183. console.warn('THREE.Texture: Unable to serialize Texture.');
  1184. return {};
  1185. }
  1186. }
  1187. }
  1188. class Vector4 {
  1189. constructor(x = 0, y = 0, z = 0, w = 1) {
  1190. this.x = x;
  1191. this.y = y;
  1192. this.z = z;
  1193. this.w = w;
  1194. }
  1195. get width() {
  1196. return this.z;
  1197. }
  1198. set width(value) {
  1199. this.z = value;
  1200. }
  1201. get height() {
  1202. return this.w;
  1203. }
  1204. set height(value) {
  1205. this.w = value;
  1206. }
  1207. set(x, y, z, w) {
  1208. this.x = x;
  1209. this.y = y;
  1210. this.z = z;
  1211. this.w = w;
  1212. return this;
  1213. }
  1214. setScalar(scalar) {
  1215. this.x = scalar;
  1216. this.y = scalar;
  1217. this.z = scalar;
  1218. this.w = scalar;
  1219. return this;
  1220. }
  1221. setX(x) {
  1222. this.x = x;
  1223. return this;
  1224. }
  1225. setY(y) {
  1226. this.y = y;
  1227. return this;
  1228. }
  1229. setZ(z) {
  1230. this.z = z;
  1231. return this;
  1232. }
  1233. setW(w) {
  1234. this.w = w;
  1235. return this;
  1236. }
  1237. setComponent(index, value) {
  1238. switch (index) {
  1239. case 0:
  1240. this.x = value;
  1241. break;
  1242. case 1:
  1243. this.y = value;
  1244. break;
  1245. case 2:
  1246. this.z = value;
  1247. break;
  1248. case 3:
  1249. this.w = value;
  1250. break;
  1251. default:
  1252. throw new Error('index is out of range: ' + index);
  1253. }
  1254. return this;
  1255. }
  1256. getComponent(index) {
  1257. switch (index) {
  1258. case 0:
  1259. return this.x;
  1260. case 1:
  1261. return this.y;
  1262. case 2:
  1263. return this.z;
  1264. case 3:
  1265. return this.w;
  1266. default:
  1267. throw new Error('index is out of range: ' + index);
  1268. }
  1269. }
  1270. clone() {
  1271. return new this.constructor(this.x, this.y, this.z, this.w);
  1272. }
  1273. copy(v) {
  1274. this.x = v.x;
  1275. this.y = v.y;
  1276. this.z = v.z;
  1277. this.w = v.w !== undefined ? v.w : 1;
  1278. return this;
  1279. }
  1280. add(v, w) {
  1281. if (w !== undefined) {
  1282. console.warn('THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  1283. return this.addVectors(v, w);
  1284. }
  1285. this.x += v.x;
  1286. this.y += v.y;
  1287. this.z += v.z;
  1288. this.w += v.w;
  1289. return this;
  1290. }
  1291. addScalar(s) {
  1292. this.x += s;
  1293. this.y += s;
  1294. this.z += s;
  1295. this.w += s;
  1296. return this;
  1297. }
  1298. addVectors(a, b) {
  1299. this.x = a.x + b.x;
  1300. this.y = a.y + b.y;
  1301. this.z = a.z + b.z;
  1302. this.w = a.w + b.w;
  1303. return this;
  1304. }
  1305. addScaledVector(v, s) {
  1306. this.x += v.x * s;
  1307. this.y += v.y * s;
  1308. this.z += v.z * s;
  1309. this.w += v.w * s;
  1310. return this;
  1311. }
  1312. sub(v, w) {
  1313. if (w !== undefined) {
  1314. console.warn('THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  1315. return this.subVectors(v, w);
  1316. }
  1317. this.x -= v.x;
  1318. this.y -= v.y;
  1319. this.z -= v.z;
  1320. this.w -= v.w;
  1321. return this;
  1322. }
  1323. subScalar(s) {
  1324. this.x -= s;
  1325. this.y -= s;
  1326. this.z -= s;
  1327. this.w -= s;
  1328. return this;
  1329. }
  1330. subVectors(a, b) {
  1331. this.x = a.x - b.x;
  1332. this.y = a.y - b.y;
  1333. this.z = a.z - b.z;
  1334. this.w = a.w - b.w;
  1335. return this;
  1336. }
  1337. multiply(v) {
  1338. this.x *= v.x;
  1339. this.y *= v.y;
  1340. this.z *= v.z;
  1341. this.w *= v.w;
  1342. return this;
  1343. }
  1344. multiplyScalar(scalar) {
  1345. this.x *= scalar;
  1346. this.y *= scalar;
  1347. this.z *= scalar;
  1348. this.w *= scalar;
  1349. return this;
  1350. }
  1351. applyMatrix4(m) {
  1352. const x = this.x,
  1353. y = this.y,
  1354. z = this.z,
  1355. w = this.w;
  1356. const e = m.elements;
  1357. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1358. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1359. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1360. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1361. return this;
  1362. }
  1363. divideScalar(scalar) {
  1364. return this.multiplyScalar(1 / scalar);
  1365. }
  1366. setAxisAngleFromQuaternion(q) {
  1367. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1368. // q is assumed to be normalized
  1369. this.w = 2 * Math.acos(q.w);
  1370. const s = Math.sqrt(1 - q.w * q.w);
  1371. if (s < 0.0001) {
  1372. this.x = 1;
  1373. this.y = 0;
  1374. this.z = 0;
  1375. } else {
  1376. this.x = q.x / s;
  1377. this.y = q.y / s;
  1378. this.z = q.z / s;
  1379. }
  1380. return this;
  1381. }
  1382. setAxisAngleFromRotationMatrix(m) {
  1383. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1384. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1385. let angle, x, y, z; // variables for result
  1386. const epsilon = 0.01,
  1387. // margin to allow for rounding errors
  1388. epsilon2 = 0.1,
  1389. // margin to distinguish between 0 and 180 degrees
  1390. te = m.elements,
  1391. m11 = te[0],
  1392. m12 = te[4],
  1393. m13 = te[8],
  1394. m21 = te[1],
  1395. m22 = te[5],
  1396. m23 = te[9],
  1397. m31 = te[2],
  1398. m32 = te[6],
  1399. m33 = te[10];
  1400. if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) {
  1401. // singularity found
  1402. // first check for identity matrix which must have +1 for all terms
  1403. // in leading diagonal and zero in other terms
  1404. if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) {
  1405. // this singularity is identity matrix so angle = 0
  1406. this.set(1, 0, 0, 0);
  1407. return this; // zero angle, arbitrary axis
  1408. } // otherwise this singularity is angle = 180
  1409. angle = Math.PI;
  1410. const xx = (m11 + 1) / 2;
  1411. const yy = (m22 + 1) / 2;
  1412. const zz = (m33 + 1) / 2;
  1413. const xy = (m12 + m21) / 4;
  1414. const xz = (m13 + m31) / 4;
  1415. const yz = (m23 + m32) / 4;
  1416. if (xx > yy && xx > zz) {
  1417. // m11 is the largest diagonal term
  1418. if (xx < epsilon) {
  1419. x = 0;
  1420. y = 0.707106781;
  1421. z = 0.707106781;
  1422. } else {
  1423. x = Math.sqrt(xx);
  1424. y = xy / x;
  1425. z = xz / x;
  1426. }
  1427. } else if (yy > zz) {
  1428. // m22 is the largest diagonal term
  1429. if (yy < epsilon) {
  1430. x = 0.707106781;
  1431. y = 0;
  1432. z = 0.707106781;
  1433. } else {
  1434. y = Math.sqrt(yy);
  1435. x = xy / y;
  1436. z = yz / y;
  1437. }
  1438. } else {
  1439. // m33 is the largest diagonal term so base result on this
  1440. if (zz < epsilon) {
  1441. x = 0.707106781;
  1442. y = 0.707106781;
  1443. z = 0;
  1444. } else {
  1445. z = Math.sqrt(zz);
  1446. x = xz / z;
  1447. y = yz / z;
  1448. }
  1449. }
  1450. this.set(x, y, z, angle);
  1451. return this; // return 180 deg rotation
  1452. } // as we have reached here there are no singularities so we can handle normally
  1453. let s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); // used to normalize
  1454. if (Math.abs(s) < 0.001) s = 1; // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1455. // caught by singularity test above, but I've left it in just in case
  1456. this.x = (m32 - m23) / s;
  1457. this.y = (m13 - m31) / s;
  1458. this.z = (m21 - m12) / s;
  1459. this.w = Math.acos((m11 + m22 + m33 - 1) / 2);
  1460. return this;
  1461. }
  1462. min(v) {
  1463. this.x = Math.min(this.x, v.x);
  1464. this.y = Math.min(this.y, v.y);
  1465. this.z = Math.min(this.z, v.z);
  1466. this.w = Math.min(this.w, v.w);
  1467. return this;
  1468. }
  1469. max(v) {
  1470. this.x = Math.max(this.x, v.x);
  1471. this.y = Math.max(this.y, v.y);
  1472. this.z = Math.max(this.z, v.z);
  1473. this.w = Math.max(this.w, v.w);
  1474. return this;
  1475. }
  1476. clamp(min, max) {
  1477. // assumes min < max, componentwise
  1478. this.x = Math.max(min.x, Math.min(max.x, this.x));
  1479. this.y = Math.max(min.y, Math.min(max.y, this.y));
  1480. this.z = Math.max(min.z, Math.min(max.z, this.z));
  1481. this.w = Math.max(min.w, Math.min(max.w, this.w));
  1482. return this;
  1483. }
  1484. clampScalar(minVal, maxVal) {
  1485. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  1486. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  1487. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  1488. this.w = Math.max(minVal, Math.min(maxVal, this.w));
  1489. return this;
  1490. }
  1491. clampLength(min, max) {
  1492. const length = this.length();
  1493. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  1494. }
  1495. floor() {
  1496. this.x = Math.floor(this.x);
  1497. this.y = Math.floor(this.y);
  1498. this.z = Math.floor(this.z);
  1499. this.w = Math.floor(this.w);
  1500. return this;
  1501. }
  1502. ceil() {
  1503. this.x = Math.ceil(this.x);
  1504. this.y = Math.ceil(this.y);
  1505. this.z = Math.ceil(this.z);
  1506. this.w = Math.ceil(this.w);
  1507. return this;
  1508. }
  1509. round() {
  1510. this.x = Math.round(this.x);
  1511. this.y = Math.round(this.y);
  1512. this.z = Math.round(this.z);
  1513. this.w = Math.round(this.w);
  1514. return this;
  1515. }
  1516. roundToZero() {
  1517. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  1518. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  1519. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  1520. this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w);
  1521. return this;
  1522. }
  1523. negate() {
  1524. this.x = -this.x;
  1525. this.y = -this.y;
  1526. this.z = -this.z;
  1527. this.w = -this.w;
  1528. return this;
  1529. }
  1530. dot(v) {
  1531. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1532. }
  1533. lengthSq() {
  1534. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1535. }
  1536. length() {
  1537. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1538. }
  1539. manhattanLength() {
  1540. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  1541. }
  1542. normalize() {
  1543. return this.divideScalar(this.length() || 1);
  1544. }
  1545. setLength(length) {
  1546. return this.normalize().multiplyScalar(length);
  1547. }
  1548. lerp(v, alpha) {
  1549. this.x += (v.x - this.x) * alpha;
  1550. this.y += (v.y - this.y) * alpha;
  1551. this.z += (v.z - this.z) * alpha;
  1552. this.w += (v.w - this.w) * alpha;
  1553. return this;
  1554. }
  1555. lerpVectors(v1, v2, alpha) {
  1556. this.x = v1.x + (v2.x - v1.x) * alpha;
  1557. this.y = v1.y + (v2.y - v1.y) * alpha;
  1558. this.z = v1.z + (v2.z - v1.z) * alpha;
  1559. this.w = v1.w + (v2.w - v1.w) * alpha;
  1560. return this;
  1561. }
  1562. equals(v) {
  1563. return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;
  1564. }
  1565. fromArray(array, offset = 0) {
  1566. this.x = array[offset];
  1567. this.y = array[offset + 1];
  1568. this.z = array[offset + 2];
  1569. this.w = array[offset + 3];
  1570. return this;
  1571. }
  1572. toArray(array = [], offset = 0) {
  1573. array[offset] = this.x;
  1574. array[offset + 1] = this.y;
  1575. array[offset + 2] = this.z;
  1576. array[offset + 3] = this.w;
  1577. return array;
  1578. }
  1579. fromBufferAttribute(attribute, index, offset) {
  1580. if (offset !== undefined) {
  1581. console.warn('THREE.Vector4: offset has been removed from .fromBufferAttribute().');
  1582. }
  1583. this.x = attribute.getX(index);
  1584. this.y = attribute.getY(index);
  1585. this.z = attribute.getZ(index);
  1586. this.w = attribute.getW(index);
  1587. return this;
  1588. }
  1589. random() {
  1590. this.x = Math.random();
  1591. this.y = Math.random();
  1592. this.z = Math.random();
  1593. this.w = Math.random();
  1594. return this;
  1595. }
  1596. *[Symbol.iterator]() {
  1597. yield this.x;
  1598. yield this.y;
  1599. yield this.z;
  1600. yield this.w;
  1601. }
  1602. }
  1603. Vector4.prototype.isVector4 = true;
  1604. /*
  1605. In options, we can specify:
  1606. * Texture parameters for an auto-generated target texture
  1607. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1608. */
  1609. class WebGLRenderTarget extends EventDispatcher {
  1610. constructor(width, height, options = {}) {
  1611. super();
  1612. this.width = width;
  1613. this.height = height;
  1614. this.depth = 1;
  1615. this.scissor = new Vector4(0, 0, width, height);
  1616. this.scissorTest = false;
  1617. this.viewport = new Vector4(0, 0, width, height);
  1618. this.texture = new Texture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  1619. this.texture.isRenderTargetTexture = true;
  1620. this.texture.image = {
  1621. width: width,
  1622. height: height,
  1623. depth: 1
  1624. };
  1625. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  1626. this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null;
  1627. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  1628. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  1629. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  1630. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  1631. }
  1632. setTexture(texture) {
  1633. texture.image = {
  1634. width: this.width,
  1635. height: this.height,
  1636. depth: this.depth
  1637. };
  1638. this.texture = texture;
  1639. }
  1640. setSize(width, height, depth = 1) {
  1641. if (this.width !== width || this.height !== height || this.depth !== depth) {
  1642. this.width = width;
  1643. this.height = height;
  1644. this.depth = depth;
  1645. this.texture.image.width = width;
  1646. this.texture.image.height = height;
  1647. this.texture.image.depth = depth;
  1648. this.dispose();
  1649. }
  1650. this.viewport.set(0, 0, width, height);
  1651. this.scissor.set(0, 0, width, height);
  1652. }
  1653. clone() {
  1654. return new this.constructor().copy(this);
  1655. }
  1656. copy(source) {
  1657. this.width = source.width;
  1658. this.height = source.height;
  1659. this.depth = source.depth;
  1660. this.viewport.copy(source.viewport);
  1661. this.texture = source.texture.clone();
  1662. this.texture.image = { ...this.texture.image
  1663. }; // See #20328.
  1664. this.depthBuffer = source.depthBuffer;
  1665. this.stencilBuffer = source.stencilBuffer;
  1666. this.depthTexture = source.depthTexture;
  1667. return this;
  1668. }
  1669. dispose() {
  1670. this.dispatchEvent({
  1671. type: 'dispose'
  1672. });
  1673. }
  1674. }
  1675. WebGLRenderTarget.prototype.isWebGLRenderTarget = true;
  1676. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  1677. constructor(width, height, count) {
  1678. super(width, height);
  1679. const texture = this.texture;
  1680. this.texture = [];
  1681. for (let i = 0; i < count; i++) {
  1682. this.texture[i] = texture.clone();
  1683. }
  1684. }
  1685. setSize(width, height, depth = 1) {
  1686. if (this.width !== width || this.height !== height || this.depth !== depth) {
  1687. this.width = width;
  1688. this.height = height;
  1689. this.depth = depth;
  1690. for (let i = 0, il = this.texture.length; i < il; i++) {
  1691. this.texture[i].image.width = width;
  1692. this.texture[i].image.height = height;
  1693. this.texture[i].image.depth = depth;
  1694. }
  1695. this.dispose();
  1696. }
  1697. this.viewport.set(0, 0, width, height);
  1698. this.scissor.set(0, 0, width, height);
  1699. return this;
  1700. }
  1701. copy(source) {
  1702. this.dispose();
  1703. this.width = source.width;
  1704. this.height = source.height;
  1705. this.depth = source.depth;
  1706. this.viewport.set(0, 0, this.width, this.height);
  1707. this.scissor.set(0, 0, this.width, this.height);
  1708. this.depthBuffer = source.depthBuffer;
  1709. this.stencilBuffer = source.stencilBuffer;
  1710. this.depthTexture = source.depthTexture;
  1711. this.texture.length = 0;
  1712. for (let i = 0, il = source.texture.length; i < il; i++) {
  1713. this.texture[i] = source.texture[i].clone();
  1714. }
  1715. return this;
  1716. }
  1717. }
  1718. WebGLMultipleRenderTargets.prototype.isWebGLMultipleRenderTargets = true;
  1719. class WebGLMultisampleRenderTarget extends WebGLRenderTarget {
  1720. constructor(width, height, options = {}) {
  1721. super(width, height, options);
  1722. this.samples = 4;
  1723. this.ignoreDepthForMultisampleCopy = options.ignoreDepth !== undefined ? options.ignoreDepth : true;
  1724. this.useRenderToTexture = options.useRenderToTexture !== undefined ? options.useRenderToTexture : false;
  1725. this.useRenderbuffer = this.useRenderToTexture === false;
  1726. }
  1727. copy(source) {
  1728. super.copy.call(this, source);
  1729. this.samples = source.samples;
  1730. this.useRenderToTexture = source.useRenderToTexture;
  1731. this.useRenderbuffer = source.useRenderbuffer;
  1732. return this;
  1733. }
  1734. }
  1735. WebGLMultisampleRenderTarget.prototype.isWebGLMultisampleRenderTarget = true;
  1736. class Quaternion {
  1737. constructor(x = 0, y = 0, z = 0, w = 1) {
  1738. this._x = x;
  1739. this._y = y;
  1740. this._z = z;
  1741. this._w = w;
  1742. }
  1743. static slerp(qa, qb, qm, t) {
  1744. console.warn('THREE.Quaternion: Static .slerp() has been deprecated. Use qm.slerpQuaternions( qa, qb, t ) instead.');
  1745. return qm.slerpQuaternions(qa, qb, t);
  1746. }
  1747. static slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
  1748. // fuzz-free, array-based Quaternion SLERP operation
  1749. let x0 = src0[srcOffset0 + 0],
  1750. y0 = src0[srcOffset0 + 1],
  1751. z0 = src0[srcOffset0 + 2],
  1752. w0 = src0[srcOffset0 + 3];
  1753. const x1 = src1[srcOffset1 + 0],
  1754. y1 = src1[srcOffset1 + 1],
  1755. z1 = src1[srcOffset1 + 2],
  1756. w1 = src1[srcOffset1 + 3];
  1757. if (t === 0) {
  1758. dst[dstOffset + 0] = x0;
  1759. dst[dstOffset + 1] = y0;
  1760. dst[dstOffset + 2] = z0;
  1761. dst[dstOffset + 3] = w0;
  1762. return;
  1763. }
  1764. if (t === 1) {
  1765. dst[dstOffset + 0] = x1;
  1766. dst[dstOffset + 1] = y1;
  1767. dst[dstOffset + 2] = z1;
  1768. dst[dstOffset + 3] = w1;
  1769. return;
  1770. }
  1771. if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
  1772. let s = 1 - t;
  1773. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1774. dir = cos >= 0 ? 1 : -1,
  1775. sqrSin = 1 - cos * cos; // Skip the Slerp for tiny steps to avoid numeric problems:
  1776. if (sqrSin > Number.EPSILON) {
  1777. const sin = Math.sqrt(sqrSin),
  1778. len = Math.atan2(sin, cos * dir);
  1779. s = Math.sin(s * len) / sin;
  1780. t = Math.sin(t * len) / sin;
  1781. }
  1782. const tDir = t * dir;
  1783. x0 = x0 * s + x1 * tDir;
  1784. y0 = y0 * s + y1 * tDir;
  1785. z0 = z0 * s + z1 * tDir;
  1786. w0 = w0 * s + w1 * tDir; // Normalize in case we just did a lerp:
  1787. if (s === 1 - t) {
  1788. const f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
  1789. x0 *= f;
  1790. y0 *= f;
  1791. z0 *= f;
  1792. w0 *= f;
  1793. }
  1794. }
  1795. dst[dstOffset] = x0;
  1796. dst[dstOffset + 1] = y0;
  1797. dst[dstOffset + 2] = z0;
  1798. dst[dstOffset + 3] = w0;
  1799. }
  1800. static multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) {
  1801. const x0 = src0[srcOffset0];
  1802. const y0 = src0[srcOffset0 + 1];
  1803. const z0 = src0[srcOffset0 + 2];
  1804. const w0 = src0[srcOffset0 + 3];
  1805. const x1 = src1[srcOffset1];
  1806. const y1 = src1[srcOffset1 + 1];
  1807. const z1 = src1[srcOffset1 + 2];
  1808. const w1 = src1[srcOffset1 + 3];
  1809. dst[dstOffset] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  1810. dst[dstOffset + 1] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  1811. dst[dstOffset + 2] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  1812. dst[dstOffset + 3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  1813. return dst;
  1814. }
  1815. get x() {
  1816. return this._x;
  1817. }
  1818. set x(value) {
  1819. this._x = value;
  1820. this._onChangeCallback();
  1821. }
  1822. get y() {
  1823. return this._y;
  1824. }
  1825. set y(value) {
  1826. this._y = value;
  1827. this._onChangeCallback();
  1828. }
  1829. get z() {
  1830. return this._z;
  1831. }
  1832. set z(value) {
  1833. this._z = value;
  1834. this._onChangeCallback();
  1835. }
  1836. get w() {
  1837. return this._w;
  1838. }
  1839. set w(value) {
  1840. this._w = value;
  1841. this._onChangeCallback();
  1842. }
  1843. set(x, y, z, w) {
  1844. this._x = x;
  1845. this._y = y;
  1846. this._z = z;
  1847. this._w = w;
  1848. this._onChangeCallback();
  1849. return this;
  1850. }
  1851. clone() {
  1852. return new this.constructor(this._x, this._y, this._z, this._w);
  1853. }
  1854. copy(quaternion) {
  1855. this._x = quaternion.x;
  1856. this._y = quaternion.y;
  1857. this._z = quaternion.z;
  1858. this._w = quaternion.w;
  1859. this._onChangeCallback();
  1860. return this;
  1861. }
  1862. setFromEuler(euler, update) {
  1863. if (!(euler && euler.isEuler)) {
  1864. throw new Error('THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.');
  1865. }
  1866. const x = euler._x,
  1867. y = euler._y,
  1868. z = euler._z,
  1869. order = euler._order; // http://www.mathworks.com/matlabcentral/fileexchange/
  1870. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1871. // content/SpinCalc.m
  1872. const cos = Math.cos;
  1873. const sin = Math.sin;
  1874. const c1 = cos(x / 2);
  1875. const c2 = cos(y / 2);
  1876. const c3 = cos(z / 2);
  1877. const s1 = sin(x / 2);
  1878. const s2 = sin(y / 2);
  1879. const s3 = sin(z / 2);
  1880. switch (order) {
  1881. case 'XYZ':
  1882. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1883. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1884. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1885. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1886. break;
  1887. case 'YXZ':
  1888. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1889. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1890. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1891. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1892. break;
  1893. case 'ZXY':
  1894. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1895. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1896. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1897. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1898. break;
  1899. case 'ZYX':
  1900. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1901. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1902. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1903. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1904. break;
  1905. case 'YZX':
  1906. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1907. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1908. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1909. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1910. break;
  1911. case 'XZY':
  1912. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1913. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1914. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1915. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1916. break;
  1917. default:
  1918. console.warn('THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order);
  1919. }
  1920. if (update !== false) this._onChangeCallback();
  1921. return this;
  1922. }
  1923. setFromAxisAngle(axis, angle) {
  1924. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  1925. // assumes axis is normalized
  1926. const halfAngle = angle / 2,
  1927. s = Math.sin(halfAngle);
  1928. this._x = axis.x * s;
  1929. this._y = axis.y * s;
  1930. this._z = axis.z * s;
  1931. this._w = Math.cos(halfAngle);
  1932. this._onChangeCallback();
  1933. return this;
  1934. }
  1935. setFromRotationMatrix(m) {
  1936. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  1937. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1938. const te = m.elements,
  1939. m11 = te[0],
  1940. m12 = te[4],
  1941. m13 = te[8],
  1942. m21 = te[1],
  1943. m22 = te[5],
  1944. m23 = te[9],
  1945. m31 = te[2],
  1946. m32 = te[6],
  1947. m33 = te[10],
  1948. trace = m11 + m22 + m33;
  1949. if (trace > 0) {
  1950. const s = 0.5 / Math.sqrt(trace + 1.0);
  1951. this._w = 0.25 / s;
  1952. this._x = (m32 - m23) * s;
  1953. this._y = (m13 - m31) * s;
  1954. this._z = (m21 - m12) * s;
  1955. } else if (m11 > m22 && m11 > m33) {
  1956. const s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1957. this._w = (m32 - m23) / s;
  1958. this._x = 0.25 * s;
  1959. this._y = (m12 + m21) / s;
  1960. this._z = (m13 + m31) / s;
  1961. } else if (m22 > m33) {
  1962. const s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1963. this._w = (m13 - m31) / s;
  1964. this._x = (m12 + m21) / s;
  1965. this._y = 0.25 * s;
  1966. this._z = (m23 + m32) / s;
  1967. } else {
  1968. const s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1969. this._w = (m21 - m12) / s;
  1970. this._x = (m13 + m31) / s;
  1971. this._y = (m23 + m32) / s;
  1972. this._z = 0.25 * s;
  1973. }
  1974. this._onChangeCallback();
  1975. return this;
  1976. }
  1977. setFromUnitVectors(vFrom, vTo) {
  1978. // assumes direction vectors vFrom and vTo are normalized
  1979. let r = vFrom.dot(vTo) + 1;
  1980. if (r < Number.EPSILON) {
  1981. // vFrom and vTo point in opposite directions
  1982. r = 0;
  1983. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  1984. this._x = -vFrom.y;
  1985. this._y = vFrom.x;
  1986. this._z = 0;
  1987. this._w = r;
  1988. } else {
  1989. this._x = 0;
  1990. this._y = -vFrom.z;
  1991. this._z = vFrom.y;
  1992. this._w = r;
  1993. }
  1994. } else {
  1995. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  1996. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  1997. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  1998. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  1999. this._w = r;
  2000. }
  2001. return this.normalize();
  2002. }
  2003. angleTo(q) {
  2004. return 2 * Math.acos(Math.abs(clamp(this.dot(q), -1, 1)));
  2005. }
  2006. rotateTowards(q, step) {
  2007. const angle = this.angleTo(q);
  2008. if (angle === 0) return this;
  2009. const t = Math.min(1, step / angle);
  2010. this.slerp(q, t);
  2011. return this;
  2012. }
  2013. identity() {
  2014. return this.set(0, 0, 0, 1);
  2015. }
  2016. invert() {
  2017. // quaternion is assumed to have unit length
  2018. return this.conjugate();
  2019. }
  2020. conjugate() {
  2021. this._x *= -1;
  2022. this._y *= -1;
  2023. this._z *= -1;
  2024. this._onChangeCallback();
  2025. return this;
  2026. }
  2027. dot(v) {
  2028. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2029. }
  2030. lengthSq() {
  2031. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2032. }
  2033. length() {
  2034. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  2035. }
  2036. normalize() {
  2037. let l = this.length();
  2038. if (l === 0) {
  2039. this._x = 0;
  2040. this._y = 0;
  2041. this._z = 0;
  2042. this._w = 1;
  2043. } else {
  2044. l = 1 / l;
  2045. this._x = this._x * l;
  2046. this._y = this._y * l;
  2047. this._z = this._z * l;
  2048. this._w = this._w * l;
  2049. }
  2050. this._onChangeCallback();
  2051. return this;
  2052. }
  2053. multiply(q, p) {
  2054. if (p !== undefined) {
  2055. console.warn('THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.');
  2056. return this.multiplyQuaternions(q, p);
  2057. }
  2058. return this.multiplyQuaternions(this, q);
  2059. }
  2060. premultiply(q) {
  2061. return this.multiplyQuaternions(q, this);
  2062. }
  2063. multiplyQuaternions(a, b) {
  2064. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2065. const qax = a._x,
  2066. qay = a._y,
  2067. qaz = a._z,
  2068. qaw = a._w;
  2069. const qbx = b._x,
  2070. qby = b._y,
  2071. qbz = b._z,
  2072. qbw = b._w;
  2073. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2074. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2075. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2076. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2077. this._onChangeCallback();
  2078. return this;
  2079. }
  2080. slerp(qb, t) {
  2081. if (t === 0) return this;
  2082. if (t === 1) return this.copy(qb);
  2083. const x = this._x,
  2084. y = this._y,
  2085. z = this._z,
  2086. w = this._w; // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2087. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2088. if (cosHalfTheta < 0) {
  2089. this._w = -qb._w;
  2090. this._x = -qb._x;
  2091. this._y = -qb._y;
  2092. this._z = -qb._z;
  2093. cosHalfTheta = -cosHalfTheta;
  2094. } else {
  2095. this.copy(qb);
  2096. }
  2097. if (cosHalfTheta >= 1.0) {
  2098. this._w = w;
  2099. this._x = x;
  2100. this._y = y;
  2101. this._z = z;
  2102. return this;
  2103. }
  2104. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2105. if (sqrSinHalfTheta <= Number.EPSILON) {
  2106. const s = 1 - t;
  2107. this._w = s * w + t * this._w;
  2108. this._x = s * x + t * this._x;
  2109. this._y = s * y + t * this._y;
  2110. this._z = s * z + t * this._z;
  2111. this.normalize();
  2112. this._onChangeCallback();
  2113. return this;
  2114. }
  2115. const sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
  2116. const halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
  2117. const ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  2118. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  2119. this._w = w * ratioA + this._w * ratioB;
  2120. this._x = x * ratioA + this._x * ratioB;
  2121. this._y = y * ratioA + this._y * ratioB;
  2122. this._z = z * ratioA + this._z * ratioB;
  2123. this._onChangeCallback();
  2124. return this;
  2125. }
  2126. slerpQuaternions(qa, qb, t) {
  2127. this.copy(qa).slerp(qb, t);
  2128. }
  2129. random() {
  2130. // Derived from http://planning.cs.uiuc.edu/node198.html
  2131. // Note, this source uses w, x, y, z ordering,
  2132. // so we swap the order below.
  2133. const u1 = Math.random();
  2134. const sqrt1u1 = Math.sqrt(1 - u1);
  2135. const sqrtu1 = Math.sqrt(u1);
  2136. const u2 = 2 * Math.PI * Math.random();
  2137. const u3 = 2 * Math.PI * Math.random();
  2138. return this.set(sqrt1u1 * Math.cos(u2), sqrtu1 * Math.sin(u3), sqrtu1 * Math.cos(u3), sqrt1u1 * Math.sin(u2));
  2139. }
  2140. equals(quaternion) {
  2141. return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
  2142. }
  2143. fromArray(array, offset = 0) {
  2144. this._x = array[offset];
  2145. this._y = array[offset + 1];
  2146. this._z = array[offset + 2];
  2147. this._w = array[offset + 3];
  2148. this._onChangeCallback();
  2149. return this;
  2150. }
  2151. toArray(array = [], offset = 0) {
  2152. array[offset] = this._x;
  2153. array[offset + 1] = this._y;
  2154. array[offset + 2] = this._z;
  2155. array[offset + 3] = this._w;
  2156. return array;
  2157. }
  2158. fromBufferAttribute(attribute, index) {
  2159. this._x = attribute.getX(index);
  2160. this._y = attribute.getY(index);
  2161. this._z = attribute.getZ(index);
  2162. this._w = attribute.getW(index);
  2163. return this;
  2164. }
  2165. _onChange(callback) {
  2166. this._onChangeCallback = callback;
  2167. return this;
  2168. }
  2169. _onChangeCallback() {}
  2170. }
  2171. Quaternion.prototype.isQuaternion = true;
  2172. class Vector3 {
  2173. constructor(x = 0, y = 0, z = 0) {
  2174. this.x = x;
  2175. this.y = y;
  2176. this.z = z;
  2177. }
  2178. set(x, y, z) {
  2179. if (z === undefined) z = this.z; // sprite.scale.set(x,y)
  2180. this.x = x;
  2181. this.y = y;
  2182. this.z = z;
  2183. return this;
  2184. }
  2185. setScalar(scalar) {
  2186. this.x = scalar;
  2187. this.y = scalar;
  2188. this.z = scalar;
  2189. return this;
  2190. }
  2191. setX(x) {
  2192. this.x = x;
  2193. return this;
  2194. }
  2195. setY(y) {
  2196. this.y = y;
  2197. return this;
  2198. }
  2199. setZ(z) {
  2200. this.z = z;
  2201. return this;
  2202. }
  2203. setComponent(index, value) {
  2204. switch (index) {
  2205. case 0:
  2206. this.x = value;
  2207. break;
  2208. case 1:
  2209. this.y = value;
  2210. break;
  2211. case 2:
  2212. this.z = value;
  2213. break;
  2214. default:
  2215. throw new Error('index is out of range: ' + index);
  2216. }
  2217. return this;
  2218. }
  2219. getComponent(index) {
  2220. switch (index) {
  2221. case 0:
  2222. return this.x;
  2223. case 1:
  2224. return this.y;
  2225. case 2:
  2226. return this.z;
  2227. default:
  2228. throw new Error('index is out of range: ' + index);
  2229. }
  2230. }
  2231. clone() {
  2232. return new this.constructor(this.x, this.y, this.z);
  2233. }
  2234. copy(v) {
  2235. this.x = v.x;
  2236. this.y = v.y;
  2237. this.z = v.z;
  2238. return this;
  2239. }
  2240. add(v, w) {
  2241. if (w !== undefined) {
  2242. console.warn('THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  2243. return this.addVectors(v, w);
  2244. }
  2245. this.x += v.x;
  2246. this.y += v.y;
  2247. this.z += v.z;
  2248. return this;
  2249. }
  2250. addScalar(s) {
  2251. this.x += s;
  2252. this.y += s;
  2253. this.z += s;
  2254. return this;
  2255. }
  2256. addVectors(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. addScaledVector(v, s) {
  2263. this.x += v.x * s;
  2264. this.y += v.y * s;
  2265. this.z += v.z * s;
  2266. return this;
  2267. }
  2268. sub(v, w) {
  2269. if (w !== undefined) {
  2270. console.warn('THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  2271. return this.subVectors(v, w);
  2272. }
  2273. this.x -= v.x;
  2274. this.y -= v.y;
  2275. this.z -= v.z;
  2276. return this;
  2277. }
  2278. subScalar(s) {
  2279. this.x -= s;
  2280. this.y -= s;
  2281. this.z -= s;
  2282. return this;
  2283. }
  2284. subVectors(a, b) {
  2285. this.x = a.x - b.x;
  2286. this.y = a.y - b.y;
  2287. this.z = a.z - b.z;
  2288. return this;
  2289. }
  2290. multiply(v, w) {
  2291. if (w !== undefined) {
  2292. console.warn('THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.');
  2293. return this.multiplyVectors(v, w);
  2294. }
  2295. this.x *= v.x;
  2296. this.y *= v.y;
  2297. this.z *= v.z;
  2298. return this;
  2299. }
  2300. multiplyScalar(scalar) {
  2301. this.x *= scalar;
  2302. this.y *= scalar;
  2303. this.z *= scalar;
  2304. return this;
  2305. }
  2306. multiplyVectors(a, b) {
  2307. this.x = a.x * b.x;
  2308. this.y = a.y * b.y;
  2309. this.z = a.z * b.z;
  2310. return this;
  2311. }
  2312. applyEuler(euler) {
  2313. if (!(euler && euler.isEuler)) {
  2314. console.error('THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.');
  2315. }
  2316. return this.applyQuaternion(_quaternion$4.setFromEuler(euler));
  2317. }
  2318. applyAxisAngle(axis, angle) {
  2319. return this.applyQuaternion(_quaternion$4.setFromAxisAngle(axis, angle));
  2320. }
  2321. applyMatrix3(m) {
  2322. const x = this.x,
  2323. y = this.y,
  2324. z = this.z;
  2325. const e = m.elements;
  2326. this.x = e[0] * x + e[3] * y + e[6] * z;
  2327. this.y = e[1] * x + e[4] * y + e[7] * z;
  2328. this.z = e[2] * x + e[5] * y + e[8] * z;
  2329. return this;
  2330. }
  2331. applyNormalMatrix(m) {
  2332. return this.applyMatrix3(m).normalize();
  2333. }
  2334. applyMatrix4(m) {
  2335. const x = this.x,
  2336. y = this.y,
  2337. z = this.z;
  2338. const e = m.elements;
  2339. const w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
  2340. this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
  2341. this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
  2342. this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
  2343. return this;
  2344. }
  2345. applyQuaternion(q) {
  2346. const x = this.x,
  2347. y = this.y,
  2348. z = this.z;
  2349. const qx = q.x,
  2350. qy = q.y,
  2351. qz = q.z,
  2352. qw = q.w; // calculate quat * vector
  2353. const ix = qw * x + qy * z - qz * y;
  2354. const iy = qw * y + qz * x - qx * z;
  2355. const iz = qw * z + qx * y - qy * x;
  2356. const iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  2357. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2358. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2359. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2360. return this;
  2361. }
  2362. project(camera) {
  2363. return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
  2364. }
  2365. unproject(camera) {
  2366. return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
  2367. }
  2368. transformDirection(m) {
  2369. // input: THREE.Matrix4 affine matrix
  2370. // vector interpreted as a direction
  2371. const x = this.x,
  2372. y = this.y,
  2373. z = this.z;
  2374. const e = m.elements;
  2375. this.x = e[0] * x + e[4] * y + e[8] * z;
  2376. this.y = e[1] * x + e[5] * y + e[9] * z;
  2377. this.z = e[2] * x + e[6] * y + e[10] * z;
  2378. return this.normalize();
  2379. }
  2380. divide(v) {
  2381. this.x /= v.x;
  2382. this.y /= v.y;
  2383. this.z /= v.z;
  2384. return this;
  2385. }
  2386. divideScalar(scalar) {
  2387. return this.multiplyScalar(1 / scalar);
  2388. }
  2389. min(v) {
  2390. this.x = Math.min(this.x, v.x);
  2391. this.y = Math.min(this.y, v.y);
  2392. this.z = Math.min(this.z, v.z);
  2393. return this;
  2394. }
  2395. max(v) {
  2396. this.x = Math.max(this.x, v.x);
  2397. this.y = Math.max(this.y, v.y);
  2398. this.z = Math.max(this.z, v.z);
  2399. return this;
  2400. }
  2401. clamp(min, max) {
  2402. // assumes min < max, componentwise
  2403. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2404. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2405. this.z = Math.max(min.z, Math.min(max.z, this.z));
  2406. return this;
  2407. }
  2408. clampScalar(minVal, maxVal) {
  2409. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2410. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2411. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  2412. return this;
  2413. }
  2414. clampLength(min, max) {
  2415. const length = this.length();
  2416. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2417. }
  2418. floor() {
  2419. this.x = Math.floor(this.x);
  2420. this.y = Math.floor(this.y);
  2421. this.z = Math.floor(this.z);
  2422. return this;
  2423. }
  2424. ceil() {
  2425. this.x = Math.ceil(this.x);
  2426. this.y = Math.ceil(this.y);
  2427. this.z = Math.ceil(this.z);
  2428. return this;
  2429. }
  2430. round() {
  2431. this.x = Math.round(this.x);
  2432. this.y = Math.round(this.y);
  2433. this.z = Math.round(this.z);
  2434. return this;
  2435. }
  2436. roundToZero() {
  2437. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2438. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2439. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  2440. return this;
  2441. }
  2442. negate() {
  2443. this.x = -this.x;
  2444. this.y = -this.y;
  2445. this.z = -this.z;
  2446. return this;
  2447. }
  2448. dot(v) {
  2449. return this.x * v.x + this.y * v.y + this.z * v.z;
  2450. } // TODO lengthSquared?
  2451. lengthSq() {
  2452. return this.x * this.x + this.y * this.y + this.z * this.z;
  2453. }
  2454. length() {
  2455. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2456. }
  2457. manhattanLength() {
  2458. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  2459. }
  2460. normalize() {
  2461. return this.divideScalar(this.length() || 1);
  2462. }
  2463. setLength(length) {
  2464. return this.normalize().multiplyScalar(length);
  2465. }
  2466. lerp(v, alpha) {
  2467. this.x += (v.x - this.x) * alpha;
  2468. this.y += (v.y - this.y) * alpha;
  2469. this.z += (v.z - this.z) * alpha;
  2470. return this;
  2471. }
  2472. lerpVectors(v1, v2, alpha) {
  2473. this.x = v1.x + (v2.x - v1.x) * alpha;
  2474. this.y = v1.y + (v2.y - v1.y) * alpha;
  2475. this.z = v1.z + (v2.z - v1.z) * alpha;
  2476. return this;
  2477. }
  2478. cross(v, w) {
  2479. if (w !== undefined) {
  2480. console.warn('THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.');
  2481. return this.crossVectors(v, w);
  2482. }
  2483. return this.crossVectors(this, v);
  2484. }
  2485. crossVectors(a, b) {
  2486. const ax = a.x,
  2487. ay = a.y,
  2488. az = a.z;
  2489. const bx = b.x,
  2490. by = b.y,
  2491. bz = b.z;
  2492. this.x = ay * bz - az * by;
  2493. this.y = az * bx - ax * bz;
  2494. this.z = ax * by - ay * bx;
  2495. return this;
  2496. }
  2497. projectOnVector(v) {
  2498. const denominator = v.lengthSq();
  2499. if (denominator === 0) return this.set(0, 0, 0);
  2500. const scalar = v.dot(this) / denominator;
  2501. return this.copy(v).multiplyScalar(scalar);
  2502. }
  2503. projectOnPlane(planeNormal) {
  2504. _vector$c.copy(this).projectOnVector(planeNormal);
  2505. return this.sub(_vector$c);
  2506. }
  2507. reflect(normal) {
  2508. // reflect incident vector off plane orthogonal to normal
  2509. // normal is assumed to have unit length
  2510. return this.sub(_vector$c.copy(normal).multiplyScalar(2 * this.dot(normal)));
  2511. }
  2512. angleTo(v) {
  2513. const denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
  2514. if (denominator === 0) return Math.PI / 2;
  2515. const theta = this.dot(v) / denominator; // clamp, to handle numerical problems
  2516. return Math.acos(clamp(theta, -1, 1));
  2517. }
  2518. distanceTo(v) {
  2519. return Math.sqrt(this.distanceToSquared(v));
  2520. }
  2521. distanceToSquared(v) {
  2522. const dx = this.x - v.x,
  2523. dy = this.y - v.y,
  2524. dz = this.z - v.z;
  2525. return dx * dx + dy * dy + dz * dz;
  2526. }
  2527. manhattanDistanceTo(v) {
  2528. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
  2529. }
  2530. setFromSpherical(s) {
  2531. return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
  2532. }
  2533. setFromSphericalCoords(radius, phi, theta) {
  2534. const sinPhiRadius = Math.sin(phi) * radius;
  2535. this.x = sinPhiRadius * Math.sin(theta);
  2536. this.y = Math.cos(phi) * radius;
  2537. this.z = sinPhiRadius * Math.cos(theta);
  2538. return this;
  2539. }
  2540. setFromCylindrical(c) {
  2541. return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
  2542. }
  2543. setFromCylindricalCoords(radius, theta, y) {
  2544. this.x = radius * Math.sin(theta);
  2545. this.y = y;
  2546. this.z = radius * Math.cos(theta);
  2547. return this;
  2548. }
  2549. setFromMatrixPosition(m) {
  2550. const e = m.elements;
  2551. this.x = e[12];
  2552. this.y = e[13];
  2553. this.z = e[14];
  2554. return this;
  2555. }
  2556. setFromMatrixScale(m) {
  2557. const sx = this.setFromMatrixColumn(m, 0).length();
  2558. const sy = this.setFromMatrixColumn(m, 1).length();
  2559. const sz = this.setFromMatrixColumn(m, 2).length();
  2560. this.x = sx;
  2561. this.y = sy;
  2562. this.z = sz;
  2563. return this;
  2564. }
  2565. setFromMatrixColumn(m, index) {
  2566. return this.fromArray(m.elements, index * 4);
  2567. }
  2568. setFromMatrix3Column(m, index) {
  2569. return this.fromArray(m.elements, index * 3);
  2570. }
  2571. equals(v) {
  2572. return v.x === this.x && v.y === this.y && v.z === this.z;
  2573. }
  2574. fromArray(array, offset = 0) {
  2575. this.x = array[offset];
  2576. this.y = array[offset + 1];
  2577. this.z = array[offset + 2];
  2578. return this;
  2579. }
  2580. toArray(array = [], offset = 0) {
  2581. array[offset] = this.x;
  2582. array[offset + 1] = this.y;
  2583. array[offset + 2] = this.z;
  2584. return array;
  2585. }
  2586. fromBufferAttribute(attribute, index, offset) {
  2587. if (offset !== undefined) {
  2588. console.warn('THREE.Vector3: offset has been removed from .fromBufferAttribute().');
  2589. }
  2590. this.x = attribute.getX(index);
  2591. this.y = attribute.getY(index);
  2592. this.z = attribute.getZ(index);
  2593. return this;
  2594. }
  2595. random() {
  2596. this.x = Math.random();
  2597. this.y = Math.random();
  2598. this.z = Math.random();
  2599. return this;
  2600. }
  2601. randomDirection() {
  2602. // Derived from https://mathworld.wolfram.com/SpherePointPicking.html
  2603. const u = (Math.random() - 0.5) * 2;
  2604. const t = Math.random() * Math.PI * 2;
  2605. const f = Math.sqrt(1 - u ** 2);
  2606. this.x = f * Math.cos(t);
  2607. this.y = f * Math.sin(t);
  2608. this.z = u;
  2609. return this;
  2610. }
  2611. *[Symbol.iterator]() {
  2612. yield this.x;
  2613. yield this.y;
  2614. yield this.z;
  2615. }
  2616. }
  2617. Vector3.prototype.isVector3 = true;
  2618. const _vector$c = /*@__PURE__*/new Vector3();
  2619. const _quaternion$4 = /*@__PURE__*/new Quaternion();
  2620. class Box3 {
  2621. constructor(min = new Vector3(+Infinity, +Infinity, +Infinity), max = new Vector3(-Infinity, -Infinity, -Infinity)) {
  2622. this.min = min;
  2623. this.max = max;
  2624. }
  2625. set(min, max) {
  2626. this.min.copy(min);
  2627. this.max.copy(max);
  2628. return this;
  2629. }
  2630. setFromArray(array) {
  2631. let minX = +Infinity;
  2632. let minY = +Infinity;
  2633. let minZ = +Infinity;
  2634. let maxX = -Infinity;
  2635. let maxY = -Infinity;
  2636. let maxZ = -Infinity;
  2637. for (let i = 0, l = array.length; i < l; i += 3) {
  2638. const x = array[i];
  2639. const y = array[i + 1];
  2640. const z = array[i + 2];
  2641. if (x < minX) minX = x;
  2642. if (y < minY) minY = y;
  2643. if (z < minZ) minZ = z;
  2644. if (x > maxX) maxX = x;
  2645. if (y > maxY) maxY = y;
  2646. if (z > maxZ) maxZ = z;
  2647. }
  2648. this.min.set(minX, minY, minZ);
  2649. this.max.set(maxX, maxY, maxZ);
  2650. return this;
  2651. }
  2652. setFromBufferAttribute(attribute) {
  2653. let minX = +Infinity;
  2654. let minY = +Infinity;
  2655. let minZ = +Infinity;
  2656. let maxX = -Infinity;
  2657. let maxY = -Infinity;
  2658. let maxZ = -Infinity;
  2659. for (let i = 0, l = attribute.count; i < l; i++) {
  2660. const x = attribute.getX(i);
  2661. const y = attribute.getY(i);
  2662. const z = attribute.getZ(i);
  2663. if (x < minX) minX = x;
  2664. if (y < minY) minY = y;
  2665. if (z < minZ) minZ = z;
  2666. if (x > maxX) maxX = x;
  2667. if (y > maxY) maxY = y;
  2668. if (z > maxZ) maxZ = z;
  2669. }
  2670. this.min.set(minX, minY, minZ);
  2671. this.max.set(maxX, maxY, maxZ);
  2672. return this;
  2673. }
  2674. setFromPoints(points) {
  2675. this.makeEmpty();
  2676. for (let i = 0, il = points.length; i < il; i++) {
  2677. this.expandByPoint(points[i]);
  2678. }
  2679. return this;
  2680. }
  2681. setFromCenterAndSize(center, size) {
  2682. const halfSize = _vector$b.copy(size).multiplyScalar(0.5);
  2683. this.min.copy(center).sub(halfSize);
  2684. this.max.copy(center).add(halfSize);
  2685. return this;
  2686. }
  2687. setFromObject(object) {
  2688. this.makeEmpty();
  2689. return this.expandByObject(object);
  2690. }
  2691. clone() {
  2692. return new this.constructor().copy(this);
  2693. }
  2694. copy(box) {
  2695. this.min.copy(box.min);
  2696. this.max.copy(box.max);
  2697. return this;
  2698. }
  2699. makeEmpty() {
  2700. this.min.x = this.min.y = this.min.z = +Infinity;
  2701. this.max.x = this.max.y = this.max.z = -Infinity;
  2702. return this;
  2703. }
  2704. isEmpty() {
  2705. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2706. return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  2707. }
  2708. getCenter(target) {
  2709. return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  2710. }
  2711. getSize(target) {
  2712. return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
  2713. }
  2714. expandByPoint(point) {
  2715. this.min.min(point);
  2716. this.max.max(point);
  2717. return this;
  2718. }
  2719. expandByVector(vector) {
  2720. this.min.sub(vector);
  2721. this.max.add(vector);
  2722. return this;
  2723. }
  2724. expandByScalar(scalar) {
  2725. this.min.addScalar(-scalar);
  2726. this.max.addScalar(scalar);
  2727. return this;
  2728. }
  2729. expandByObject(object) {
  2730. // Computes the world-axis-aligned bounding box of an object (including its children),
  2731. // accounting for both the object's, and children's, world transforms
  2732. object.updateWorldMatrix(false, false);
  2733. const geometry = object.geometry;
  2734. if (geometry !== undefined) {
  2735. if (geometry.boundingBox === null) {
  2736. geometry.computeBoundingBox();
  2737. }
  2738. _box$3.copy(geometry.boundingBox);
  2739. _box$3.applyMatrix4(object.matrixWorld);
  2740. this.union(_box$3);
  2741. }
  2742. const children = object.children;
  2743. for (let i = 0, l = children.length; i < l; i++) {
  2744. this.expandByObject(children[i]);
  2745. }
  2746. return this;
  2747. }
  2748. containsPoint(point) {
  2749. 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;
  2750. }
  2751. containsBox(box) {
  2752. 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;
  2753. }
  2754. getParameter(point, target) {
  2755. // This can potentially have a divide by zero if the box
  2756. // has a size dimension of 0.
  2757. 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));
  2758. }
  2759. intersectsBox(box) {
  2760. // using 6 splitting planes to rule out intersections.
  2761. 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;
  2762. }
  2763. intersectsSphere(sphere) {
  2764. // Find the point on the AABB closest to the sphere center.
  2765. this.clampPoint(sphere.center, _vector$b); // If that point is inside the sphere, the AABB and sphere intersect.
  2766. return _vector$b.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  2767. }
  2768. intersectsPlane(plane) {
  2769. // We compute the minimum and maximum dot product values. If those values
  2770. // are on the same side (back or front) of the plane, then there is no intersection.
  2771. let min, max;
  2772. if (plane.normal.x > 0) {
  2773. min = plane.normal.x * this.min.x;
  2774. max = plane.normal.x * this.max.x;
  2775. } else {
  2776. min = plane.normal.x * this.max.x;
  2777. max = plane.normal.x * this.min.x;
  2778. }
  2779. if (plane.normal.y > 0) {
  2780. min += plane.normal.y * this.min.y;
  2781. max += plane.normal.y * this.max.y;
  2782. } else {
  2783. min += plane.normal.y * this.max.y;
  2784. max += plane.normal.y * this.min.y;
  2785. }
  2786. if (plane.normal.z > 0) {
  2787. min += plane.normal.z * this.min.z;
  2788. max += plane.normal.z * this.max.z;
  2789. } else {
  2790. min += plane.normal.z * this.max.z;
  2791. max += plane.normal.z * this.min.z;
  2792. }
  2793. return min <= -plane.constant && max >= -plane.constant;
  2794. }
  2795. intersectsTriangle(triangle) {
  2796. if (this.isEmpty()) {
  2797. return false;
  2798. } // compute box center and extents
  2799. this.getCenter(_center);
  2800. _extents.subVectors(this.max, _center); // translate triangle to aabb origin
  2801. _v0$2.subVectors(triangle.a, _center);
  2802. _v1$7.subVectors(triangle.b, _center);
  2803. _v2$3.subVectors(triangle.c, _center); // compute edge vectors for triangle
  2804. _f0.subVectors(_v1$7, _v0$2);
  2805. _f1.subVectors(_v2$3, _v1$7);
  2806. _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
  2807. // 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
  2808. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2809. 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];
  2810. if (!satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents)) {
  2811. return false;
  2812. } // test 3 face normals from the aabb
  2813. axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  2814. if (!satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents)) {
  2815. return false;
  2816. } // finally testing the face normal of the triangle
  2817. // use already existing triangle edge vectors here
  2818. _triangleNormal.crossVectors(_f0, _f1);
  2819. axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
  2820. return satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents);
  2821. }
  2822. clampPoint(point, target) {
  2823. return target.copy(point).clamp(this.min, this.max);
  2824. }
  2825. distanceToPoint(point) {
  2826. const clampedPoint = _vector$b.copy(point).clamp(this.min, this.max);
  2827. return clampedPoint.sub(point).length();
  2828. }
  2829. getBoundingSphere(target) {
  2830. this.getCenter(target.center);
  2831. target.radius = this.getSize(_vector$b).length() * 0.5;
  2832. return target;
  2833. }
  2834. intersect(box) {
  2835. this.min.max(box.min);
  2836. 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.
  2837. if (this.isEmpty()) this.makeEmpty();
  2838. return this;
  2839. }
  2840. union(box) {
  2841. this.min.min(box.min);
  2842. this.max.max(box.max);
  2843. return this;
  2844. }
  2845. applyMatrix4(matrix) {
  2846. // transform of empty box is an empty box.
  2847. if (this.isEmpty()) return this; // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2848. _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000
  2849. _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001
  2850. _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010
  2851. _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011
  2852. _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100
  2853. _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101
  2854. _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110
  2855. _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111
  2856. this.setFromPoints(_points);
  2857. return this;
  2858. }
  2859. translate(offset) {
  2860. this.min.add(offset);
  2861. this.max.add(offset);
  2862. return this;
  2863. }
  2864. equals(box) {
  2865. return box.min.equals(this.min) && box.max.equals(this.max);
  2866. }
  2867. }
  2868. Box3.prototype.isBox3 = true;
  2869. 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()];
  2870. const _vector$b = /*@__PURE__*/new Vector3();
  2871. const _box$3 = /*@__PURE__*/new Box3(); // triangle centered vertices
  2872. const _v0$2 = /*@__PURE__*/new Vector3();
  2873. const _v1$7 = /*@__PURE__*/new Vector3();
  2874. const _v2$3 = /*@__PURE__*/new Vector3(); // triangle edge vectors
  2875. const _f0 = /*@__PURE__*/new Vector3();
  2876. const _f1 = /*@__PURE__*/new Vector3();
  2877. const _f2 = /*@__PURE__*/new Vector3();
  2878. const _center = /*@__PURE__*/new Vector3();
  2879. const _extents = /*@__PURE__*/new Vector3();
  2880. const _triangleNormal = /*@__PURE__*/new Vector3();
  2881. const _testAxis = /*@__PURE__*/new Vector3();
  2882. function satForAxes(axes, v0, v1, v2, extents) {
  2883. for (let i = 0, j = axes.length - 3; i <= j; i += 3) {
  2884. _testAxis.fromArray(axes, i); // project the aabb onto the seperating axis
  2885. 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
  2886. const p0 = v0.dot(_testAxis);
  2887. const p1 = v1.dot(_testAxis);
  2888. const p2 = v2.dot(_testAxis); // actual test, basically see if either of the most extreme of the triangle points intersects r
  2889. if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
  2890. // points of the projected triangle are outside the projected half-length of the aabb
  2891. // the axis is seperating and we can exit
  2892. return false;
  2893. }
  2894. }
  2895. return true;
  2896. }
  2897. const _box$2 = /*@__PURE__*/new Box3();
  2898. const _v1$6 = /*@__PURE__*/new Vector3();
  2899. const _toFarthestPoint = /*@__PURE__*/new Vector3();
  2900. const _toPoint = /*@__PURE__*/new Vector3();
  2901. class Sphere {
  2902. constructor(center = new Vector3(), radius = -1) {
  2903. this.center = center;
  2904. this.radius = radius;
  2905. }
  2906. set(center, radius) {
  2907. this.center.copy(center);
  2908. this.radius = radius;
  2909. return this;
  2910. }
  2911. setFromPoints(points, optionalCenter) {
  2912. const center = this.center;
  2913. if (optionalCenter !== undefined) {
  2914. center.copy(optionalCenter);
  2915. } else {
  2916. _box$2.setFromPoints(points).getCenter(center);
  2917. }
  2918. let maxRadiusSq = 0;
  2919. for (let i = 0, il = points.length; i < il; i++) {
  2920. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
  2921. }
  2922. this.radius = Math.sqrt(maxRadiusSq);
  2923. return this;
  2924. }
  2925. copy(sphere) {
  2926. this.center.copy(sphere.center);
  2927. this.radius = sphere.radius;
  2928. return this;
  2929. }
  2930. isEmpty() {
  2931. return this.radius < 0;
  2932. }
  2933. makeEmpty() {
  2934. this.center.set(0, 0, 0);
  2935. this.radius = -1;
  2936. return this;
  2937. }
  2938. containsPoint(point) {
  2939. return point.distanceToSquared(this.center) <= this.radius * this.radius;
  2940. }
  2941. distanceToPoint(point) {
  2942. return point.distanceTo(this.center) - this.radius;
  2943. }
  2944. intersectsSphere(sphere) {
  2945. const radiusSum = this.radius + sphere.radius;
  2946. return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
  2947. }
  2948. intersectsBox(box) {
  2949. return box.intersectsSphere(this);
  2950. }
  2951. intersectsPlane(plane) {
  2952. return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
  2953. }
  2954. clampPoint(point, target) {
  2955. const deltaLengthSq = this.center.distanceToSquared(point);
  2956. target.copy(point);
  2957. if (deltaLengthSq > this.radius * this.radius) {
  2958. target.sub(this.center).normalize();
  2959. target.multiplyScalar(this.radius).add(this.center);
  2960. }
  2961. return target;
  2962. }
  2963. getBoundingBox(target) {
  2964. if (this.isEmpty()) {
  2965. // Empty sphere produces empty bounding box
  2966. target.makeEmpty();
  2967. return target;
  2968. }
  2969. target.set(this.center, this.center);
  2970. target.expandByScalar(this.radius);
  2971. return target;
  2972. }
  2973. applyMatrix4(matrix) {
  2974. this.center.applyMatrix4(matrix);
  2975. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  2976. return this;
  2977. }
  2978. translate(offset) {
  2979. this.center.add(offset);
  2980. return this;
  2981. }
  2982. expandByPoint(point) {
  2983. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L649-L671
  2984. _toPoint.subVectors(point, this.center);
  2985. const lengthSq = _toPoint.lengthSq();
  2986. if (lengthSq > this.radius * this.radius) {
  2987. const length = Math.sqrt(lengthSq);
  2988. const missingRadiusHalf = (length - this.radius) * 0.5; // Nudge this sphere towards the target point. Add half the missing distance to radius,
  2989. // and the other half to position. This gives a tighter enclosure, instead of if
  2990. // the whole missing distance were just added to radius.
  2991. this.center.add(_toPoint.multiplyScalar(missingRadiusHalf / length));
  2992. this.radius += missingRadiusHalf;
  2993. }
  2994. return this;
  2995. }
  2996. union(sphere) {
  2997. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L759-L769
  2998. // To enclose another sphere into this sphere, we only need to enclose two points:
  2999. // 1) Enclose the farthest point on the other sphere into this sphere.
  3000. // 2) Enclose the opposite point of the farthest point into this sphere.
  3001. if (this.center.equals(sphere.center) === true) {
  3002. _toFarthestPoint.set(0, 0, 1).multiplyScalar(sphere.radius);
  3003. } else {
  3004. _toFarthestPoint.subVectors(sphere.center, this.center).normalize().multiplyScalar(sphere.radius);
  3005. }
  3006. this.expandByPoint(_v1$6.copy(sphere.center).add(_toFarthestPoint));
  3007. this.expandByPoint(_v1$6.copy(sphere.center).sub(_toFarthestPoint));
  3008. return this;
  3009. }
  3010. equals(sphere) {
  3011. return sphere.center.equals(this.center) && sphere.radius === this.radius;
  3012. }
  3013. clone() {
  3014. return new this.constructor().copy(this);
  3015. }
  3016. }
  3017. const _vector$a = /*@__PURE__*/new Vector3();
  3018. const _segCenter = /*@__PURE__*/new Vector3();
  3019. const _segDir = /*@__PURE__*/new Vector3();
  3020. const _diff = /*@__PURE__*/new Vector3();
  3021. const _edge1 = /*@__PURE__*/new Vector3();
  3022. const _edge2 = /*@__PURE__*/new Vector3();
  3023. const _normal$1 = /*@__PURE__*/new Vector3();
  3024. class Ray {
  3025. constructor(origin = new Vector3(), direction = new Vector3(0, 0, -1)) {
  3026. this.origin = origin;
  3027. this.direction = direction;
  3028. }
  3029. set(origin, direction) {
  3030. this.origin.copy(origin);
  3031. this.direction.copy(direction);
  3032. return this;
  3033. }
  3034. copy(ray) {
  3035. this.origin.copy(ray.origin);
  3036. this.direction.copy(ray.direction);
  3037. return this;
  3038. }
  3039. at(t, target) {
  3040. return target.copy(this.direction).multiplyScalar(t).add(this.origin);
  3041. }
  3042. lookAt(v) {
  3043. this.direction.copy(v).sub(this.origin).normalize();
  3044. return this;
  3045. }
  3046. recast(t) {
  3047. this.origin.copy(this.at(t, _vector$a));
  3048. return this;
  3049. }
  3050. closestPointToPoint(point, target) {
  3051. target.subVectors(point, this.origin);
  3052. const directionDistance = target.dot(this.direction);
  3053. if (directionDistance < 0) {
  3054. return target.copy(this.origin);
  3055. }
  3056. return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  3057. }
  3058. distanceToPoint(point) {
  3059. return Math.sqrt(this.distanceSqToPoint(point));
  3060. }
  3061. distanceSqToPoint(point) {
  3062. const directionDistance = _vector$a.subVectors(point, this.origin).dot(this.direction); // point behind the ray
  3063. if (directionDistance < 0) {
  3064. return this.origin.distanceToSquared(point);
  3065. }
  3066. _vector$a.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  3067. return _vector$a.distanceToSquared(point);
  3068. }
  3069. distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) {
  3070. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3071. // It returns the min distance between the ray and the segment
  3072. // defined by v0 and v1
  3073. // It can also set two optional targets :
  3074. // - The closest point on the ray
  3075. // - The closest point on the segment
  3076. _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
  3077. _segDir.copy(v1).sub(v0).normalize();
  3078. _diff.copy(this.origin).sub(_segCenter);
  3079. const segExtent = v0.distanceTo(v1) * 0.5;
  3080. const a01 = -this.direction.dot(_segDir);
  3081. const b0 = _diff.dot(this.direction);
  3082. const b1 = -_diff.dot(_segDir);
  3083. const c = _diff.lengthSq();
  3084. const det = Math.abs(1 - a01 * a01);
  3085. let s0, s1, sqrDist, extDet;
  3086. if (det > 0) {
  3087. // The ray and segment are not parallel.
  3088. s0 = a01 * b1 - b0;
  3089. s1 = a01 * b0 - b1;
  3090. extDet = segExtent * det;
  3091. if (s0 >= 0) {
  3092. if (s1 >= -extDet) {
  3093. if (s1 <= extDet) {
  3094. // region 0
  3095. // Minimum at interior points of ray and segment.
  3096. const invDet = 1 / det;
  3097. s0 *= invDet;
  3098. s1 *= invDet;
  3099. sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
  3100. } else {
  3101. // region 1
  3102. s1 = segExtent;
  3103. s0 = Math.max(0, -(a01 * s1 + b0));
  3104. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3105. }
  3106. } else {
  3107. // region 5
  3108. s1 = -segExtent;
  3109. s0 = Math.max(0, -(a01 * s1 + b0));
  3110. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3111. }
  3112. } else {
  3113. if (s1 <= -extDet) {
  3114. // region 4
  3115. s0 = Math.max(0, -(-a01 * segExtent + b0));
  3116. s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3117. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3118. } else if (s1 <= extDet) {
  3119. // region 3
  3120. s0 = 0;
  3121. s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
  3122. sqrDist = s1 * (s1 + 2 * b1) + c;
  3123. } else {
  3124. // region 2
  3125. s0 = Math.max(0, -(a01 * segExtent + b0));
  3126. s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3127. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3128. }
  3129. }
  3130. } else {
  3131. // Ray and segment are parallel.
  3132. s1 = a01 > 0 ? -segExtent : segExtent;
  3133. s0 = Math.max(0, -(a01 * s1 + b0));
  3134. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3135. }
  3136. if (optionalPointOnRay) {
  3137. optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);
  3138. }
  3139. if (optionalPointOnSegment) {
  3140. optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
  3141. }
  3142. return sqrDist;
  3143. }
  3144. intersectSphere(sphere, target) {
  3145. _vector$a.subVectors(sphere.center, this.origin);
  3146. const tca = _vector$a.dot(this.direction);
  3147. const d2 = _vector$a.dot(_vector$a) - tca * tca;
  3148. const radius2 = sphere.radius * sphere.radius;
  3149. if (d2 > radius2) return null;
  3150. const thc = Math.sqrt(radius2 - d2); // t0 = first intersect point - entrance on front of sphere
  3151. const t0 = tca - thc; // t1 = second intersect point - exit point on back of sphere
  3152. const t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return null
  3153. if (t0 < 0 && t1 < 0) return null; // test to see if t0 is behind the ray:
  3154. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3155. // in order to always return an intersect point that is in front of the ray.
  3156. 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
  3157. return this.at(t0, target);
  3158. }
  3159. intersectsSphere(sphere) {
  3160. return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
  3161. }
  3162. distanceToPlane(plane) {
  3163. const denominator = plane.normal.dot(this.direction);
  3164. if (denominator === 0) {
  3165. // line is coplanar, return origin
  3166. if (plane.distanceToPoint(this.origin) === 0) {
  3167. return 0;
  3168. } // Null is preferable to undefined since undefined means.... it is undefined
  3169. return null;
  3170. }
  3171. const t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; // Return if the ray never intersects the plane
  3172. return t >= 0 ? t : null;
  3173. }
  3174. intersectPlane(plane, target) {
  3175. const t = this.distanceToPlane(plane);
  3176. if (t === null) {
  3177. return null;
  3178. }
  3179. return this.at(t, target);
  3180. }
  3181. intersectsPlane(plane) {
  3182. // check if the ray lies on the plane first
  3183. const distToPoint = plane.distanceToPoint(this.origin);
  3184. if (distToPoint === 0) {
  3185. return true;
  3186. }
  3187. const denominator = plane.normal.dot(this.direction);
  3188. if (denominator * distToPoint < 0) {
  3189. return true;
  3190. } // ray origin is behind the plane (and is pointing behind it)
  3191. return false;
  3192. }
  3193. intersectBox(box, target) {
  3194. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3195. const invdirx = 1 / this.direction.x,
  3196. invdiry = 1 / this.direction.y,
  3197. invdirz = 1 / this.direction.z;
  3198. const origin = this.origin;
  3199. if (invdirx >= 0) {
  3200. tmin = (box.min.x - origin.x) * invdirx;
  3201. tmax = (box.max.x - origin.x) * invdirx;
  3202. } else {
  3203. tmin = (box.max.x - origin.x) * invdirx;
  3204. tmax = (box.min.x - origin.x) * invdirx;
  3205. }
  3206. if (invdiry >= 0) {
  3207. tymin = (box.min.y - origin.y) * invdiry;
  3208. tymax = (box.max.y - origin.y) * invdiry;
  3209. } else {
  3210. tymin = (box.max.y - origin.y) * invdiry;
  3211. tymax = (box.min.y - origin.y) * invdiry;
  3212. }
  3213. if (tmin > tymax || tymin > tmax) return null; // These lines also handle the case where tmin or tmax is NaN
  3214. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3215. if (tymin > tmin || tmin !== tmin) tmin = tymin;
  3216. if (tymax < tmax || tmax !== tmax) tmax = tymax;
  3217. if (invdirz >= 0) {
  3218. tzmin = (box.min.z - origin.z) * invdirz;
  3219. tzmax = (box.max.z - origin.z) * invdirz;
  3220. } else {
  3221. tzmin = (box.max.z - origin.z) * invdirz;
  3222. tzmax = (box.min.z - origin.z) * invdirz;
  3223. }
  3224. if (tmin > tzmax || tzmin > tmax) return null;
  3225. if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
  3226. if (tzmax < tmax || tmax !== tmax) tmax = tzmax; //return point closest to the ray (positive side)
  3227. if (tmax < 0) return null;
  3228. return this.at(tmin >= 0 ? tmin : tmax, target);
  3229. }
  3230. intersectsBox(box) {
  3231. return this.intersectBox(box, _vector$a) !== null;
  3232. }
  3233. intersectTriangle(a, b, c, backfaceCulling, target) {
  3234. // Compute the offset origin, edges, and normal.
  3235. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3236. _edge1.subVectors(b, a);
  3237. _edge2.subVectors(c, a);
  3238. _normal$1.crossVectors(_edge1, _edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3239. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3240. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3241. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3242. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3243. let DdN = this.direction.dot(_normal$1);
  3244. let sign;
  3245. if (DdN > 0) {
  3246. if (backfaceCulling) return null;
  3247. sign = 1;
  3248. } else if (DdN < 0) {
  3249. sign = -1;
  3250. DdN = -DdN;
  3251. } else {
  3252. return null;
  3253. }
  3254. _diff.subVectors(this.origin, a);
  3255. const DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); // b1 < 0, no intersection
  3256. if (DdQxE2 < 0) {
  3257. return null;
  3258. }
  3259. const DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); // b2 < 0, no intersection
  3260. if (DdE1xQ < 0) {
  3261. return null;
  3262. } // b1+b2 > 1, no intersection
  3263. if (DdQxE2 + DdE1xQ > DdN) {
  3264. return null;
  3265. } // Line intersects triangle, check if ray does.
  3266. const QdN = -sign * _diff.dot(_normal$1); // t < 0, no intersection
  3267. if (QdN < 0) {
  3268. return null;
  3269. } // Ray intersects triangle.
  3270. return this.at(QdN / DdN, target);
  3271. }
  3272. applyMatrix4(matrix4) {
  3273. this.origin.applyMatrix4(matrix4);
  3274. this.direction.transformDirection(matrix4);
  3275. return this;
  3276. }
  3277. equals(ray) {
  3278. return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
  3279. }
  3280. clone() {
  3281. return new this.constructor().copy(this);
  3282. }
  3283. }
  3284. class Matrix4 {
  3285. constructor() {
  3286. this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  3287. if (arguments.length > 0) {
  3288. console.error('THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.');
  3289. }
  3290. }
  3291. set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  3292. const te = this.elements;
  3293. te[0] = n11;
  3294. te[4] = n12;
  3295. te[8] = n13;
  3296. te[12] = n14;
  3297. te[1] = n21;
  3298. te[5] = n22;
  3299. te[9] = n23;
  3300. te[13] = n24;
  3301. te[2] = n31;
  3302. te[6] = n32;
  3303. te[10] = n33;
  3304. te[14] = n34;
  3305. te[3] = n41;
  3306. te[7] = n42;
  3307. te[11] = n43;
  3308. te[15] = n44;
  3309. return this;
  3310. }
  3311. identity() {
  3312. this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3313. return this;
  3314. }
  3315. clone() {
  3316. return new Matrix4().fromArray(this.elements);
  3317. }
  3318. copy(m) {
  3319. const te = this.elements;
  3320. const me = m.elements;
  3321. te[0] = me[0];
  3322. te[1] = me[1];
  3323. te[2] = me[2];
  3324. te[3] = me[3];
  3325. te[4] = me[4];
  3326. te[5] = me[5];
  3327. te[6] = me[6];
  3328. te[7] = me[7];
  3329. te[8] = me[8];
  3330. te[9] = me[9];
  3331. te[10] = me[10];
  3332. te[11] = me[11];
  3333. te[12] = me[12];
  3334. te[13] = me[13];
  3335. te[14] = me[14];
  3336. te[15] = me[15];
  3337. return this;
  3338. }
  3339. copyPosition(m) {
  3340. const te = this.elements,
  3341. me = m.elements;
  3342. te[12] = me[12];
  3343. te[13] = me[13];
  3344. te[14] = me[14];
  3345. return this;
  3346. }
  3347. setFromMatrix3(m) {
  3348. const me = m.elements;
  3349. 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);
  3350. return this;
  3351. }
  3352. extractBasis(xAxis, yAxis, zAxis) {
  3353. xAxis.setFromMatrixColumn(this, 0);
  3354. yAxis.setFromMatrixColumn(this, 1);
  3355. zAxis.setFromMatrixColumn(this, 2);
  3356. return this;
  3357. }
  3358. makeBasis(xAxis, yAxis, zAxis) {
  3359. 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);
  3360. return this;
  3361. }
  3362. extractRotation(m) {
  3363. // this method does not support reflection matrices
  3364. const te = this.elements;
  3365. const me = m.elements;
  3366. const scaleX = 1 / _v1$5.setFromMatrixColumn(m, 0).length();
  3367. const scaleY = 1 / _v1$5.setFromMatrixColumn(m, 1).length();
  3368. const scaleZ = 1 / _v1$5.setFromMatrixColumn(m, 2).length();
  3369. te[0] = me[0] * scaleX;
  3370. te[1] = me[1] * scaleX;
  3371. te[2] = me[2] * scaleX;
  3372. te[3] = 0;
  3373. te[4] = me[4] * scaleY;
  3374. te[5] = me[5] * scaleY;
  3375. te[6] = me[6] * scaleY;
  3376. te[7] = 0;
  3377. te[8] = me[8] * scaleZ;
  3378. te[9] = me[9] * scaleZ;
  3379. te[10] = me[10] * scaleZ;
  3380. te[11] = 0;
  3381. te[12] = 0;
  3382. te[13] = 0;
  3383. te[14] = 0;
  3384. te[15] = 1;
  3385. return this;
  3386. }
  3387. makeRotationFromEuler(euler) {
  3388. if (!(euler && euler.isEuler)) {
  3389. console.error('THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.');
  3390. }
  3391. const te = this.elements;
  3392. const x = euler.x,
  3393. y = euler.y,
  3394. z = euler.z;
  3395. const a = Math.cos(x),
  3396. b = Math.sin(x);
  3397. const c = Math.cos(y),
  3398. d = Math.sin(y);
  3399. const e = Math.cos(z),
  3400. f = Math.sin(z);
  3401. if (euler.order === 'XYZ') {
  3402. const ae = a * e,
  3403. af = a * f,
  3404. be = b * e,
  3405. bf = b * f;
  3406. te[0] = c * e;
  3407. te[4] = -c * f;
  3408. te[8] = d;
  3409. te[1] = af + be * d;
  3410. te[5] = ae - bf * d;
  3411. te[9] = -b * c;
  3412. te[2] = bf - ae * d;
  3413. te[6] = be + af * d;
  3414. te[10] = a * c;
  3415. } else if (euler.order === 'YXZ') {
  3416. const ce = c * e,
  3417. cf = c * f,
  3418. de = d * e,
  3419. df = d * f;
  3420. te[0] = ce + df * b;
  3421. te[4] = de * b - cf;
  3422. te[8] = a * d;
  3423. te[1] = a * f;
  3424. te[5] = a * e;
  3425. te[9] = -b;
  3426. te[2] = cf * b - de;
  3427. te[6] = df + ce * b;
  3428. te[10] = a * c;
  3429. } else if (euler.order === 'ZXY') {
  3430. const ce = c * e,
  3431. cf = c * f,
  3432. de = d * e,
  3433. df = d * f;
  3434. te[0] = ce - df * b;
  3435. te[4] = -a * f;
  3436. te[8] = de + cf * b;
  3437. te[1] = cf + de * b;
  3438. te[5] = a * e;
  3439. te[9] = df - ce * b;
  3440. te[2] = -a * d;
  3441. te[6] = b;
  3442. te[10] = a * c;
  3443. } else if (euler.order === 'ZYX') {
  3444. const ae = a * e,
  3445. af = a * f,
  3446. be = b * e,
  3447. bf = b * f;
  3448. te[0] = c * e;
  3449. te[4] = be * d - af;
  3450. te[8] = ae * d + bf;
  3451. te[1] = c * f;
  3452. te[5] = bf * d + ae;
  3453. te[9] = af * d - be;
  3454. te[2] = -d;
  3455. te[6] = b * c;
  3456. te[10] = a * c;
  3457. } else if (euler.order === 'YZX') {
  3458. const ac = a * c,
  3459. ad = a * d,
  3460. bc = b * c,
  3461. bd = b * d;
  3462. te[0] = c * e;
  3463. te[4] = bd - ac * f;
  3464. te[8] = bc * f + ad;
  3465. te[1] = f;
  3466. te[5] = a * e;
  3467. te[9] = -b * e;
  3468. te[2] = -d * e;
  3469. te[6] = ad * f + bc;
  3470. te[10] = ac - bd * f;
  3471. } else if (euler.order === 'XZY') {
  3472. const ac = a * c,
  3473. ad = a * d,
  3474. bc = b * c,
  3475. bd = b * d;
  3476. te[0] = c * e;
  3477. te[4] = -f;
  3478. te[8] = d * e;
  3479. te[1] = ac * f + bd;
  3480. te[5] = a * e;
  3481. te[9] = ad * f - bc;
  3482. te[2] = bc * f - ad;
  3483. te[6] = b * e;
  3484. te[10] = bd * f + ac;
  3485. } // bottom row
  3486. te[3] = 0;
  3487. te[7] = 0;
  3488. te[11] = 0; // last column
  3489. te[12] = 0;
  3490. te[13] = 0;
  3491. te[14] = 0;
  3492. te[15] = 1;
  3493. return this;
  3494. }
  3495. makeRotationFromQuaternion(q) {
  3496. return this.compose(_zero, q, _one);
  3497. }
  3498. lookAt(eye, target, up) {
  3499. const te = this.elements;
  3500. _z.subVectors(eye, target);
  3501. if (_z.lengthSq() === 0) {
  3502. // eye and target are in the same position
  3503. _z.z = 1;
  3504. }
  3505. _z.normalize();
  3506. _x.crossVectors(up, _z);
  3507. if (_x.lengthSq() === 0) {
  3508. // up and z are parallel
  3509. if (Math.abs(up.z) === 1) {
  3510. _z.x += 0.0001;
  3511. } else {
  3512. _z.z += 0.0001;
  3513. }
  3514. _z.normalize();
  3515. _x.crossVectors(up, _z);
  3516. }
  3517. _x.normalize();
  3518. _y.crossVectors(_z, _x);
  3519. te[0] = _x.x;
  3520. te[4] = _y.x;
  3521. te[8] = _z.x;
  3522. te[1] = _x.y;
  3523. te[5] = _y.y;
  3524. te[9] = _z.y;
  3525. te[2] = _x.z;
  3526. te[6] = _y.z;
  3527. te[10] = _z.z;
  3528. return this;
  3529. }
  3530. multiply(m, n) {
  3531. if (n !== undefined) {
  3532. console.warn('THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.');
  3533. return this.multiplyMatrices(m, n);
  3534. }
  3535. return this.multiplyMatrices(this, m);
  3536. }
  3537. premultiply(m) {
  3538. return this.multiplyMatrices(m, this);
  3539. }
  3540. multiplyMatrices(a, b) {
  3541. const ae = a.elements;
  3542. const be = b.elements;
  3543. const te = this.elements;
  3544. const a11 = ae[0],
  3545. a12 = ae[4],
  3546. a13 = ae[8],
  3547. a14 = ae[12];
  3548. const a21 = ae[1],
  3549. a22 = ae[5],
  3550. a23 = ae[9],
  3551. a24 = ae[13];
  3552. const a31 = ae[2],
  3553. a32 = ae[6],
  3554. a33 = ae[10],
  3555. a34 = ae[14];
  3556. const a41 = ae[3],
  3557. a42 = ae[7],
  3558. a43 = ae[11],
  3559. a44 = ae[15];
  3560. const b11 = be[0],
  3561. b12 = be[4],
  3562. b13 = be[8],
  3563. b14 = be[12];
  3564. const b21 = be[1],
  3565. b22 = be[5],
  3566. b23 = be[9],
  3567. b24 = be[13];
  3568. const b31 = be[2],
  3569. b32 = be[6],
  3570. b33 = be[10],
  3571. b34 = be[14];
  3572. const b41 = be[3],
  3573. b42 = be[7],
  3574. b43 = be[11],
  3575. b44 = be[15];
  3576. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3577. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3578. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3579. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3580. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3581. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3582. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3583. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3584. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3585. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3586. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3587. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3588. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3589. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3590. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3591. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3592. return this;
  3593. }
  3594. multiplyScalar(s) {
  3595. const te = this.elements;
  3596. te[0] *= s;
  3597. te[4] *= s;
  3598. te[8] *= s;
  3599. te[12] *= s;
  3600. te[1] *= s;
  3601. te[5] *= s;
  3602. te[9] *= s;
  3603. te[13] *= s;
  3604. te[2] *= s;
  3605. te[6] *= s;
  3606. te[10] *= s;
  3607. te[14] *= s;
  3608. te[3] *= s;
  3609. te[7] *= s;
  3610. te[11] *= s;
  3611. te[15] *= s;
  3612. return this;
  3613. }
  3614. determinant() {
  3615. const te = this.elements;
  3616. const n11 = te[0],
  3617. n12 = te[4],
  3618. n13 = te[8],
  3619. n14 = te[12];
  3620. const n21 = te[1],
  3621. n22 = te[5],
  3622. n23 = te[9],
  3623. n24 = te[13];
  3624. const n31 = te[2],
  3625. n32 = te[6],
  3626. n33 = te[10],
  3627. n34 = te[14];
  3628. const n41 = te[3],
  3629. n42 = te[7],
  3630. n43 = te[11],
  3631. n44 = te[15]; //TODO: make this more efficient
  3632. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3633. 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);
  3634. }
  3635. transpose() {
  3636. const te = this.elements;
  3637. let tmp;
  3638. tmp = te[1];
  3639. te[1] = te[4];
  3640. te[4] = tmp;
  3641. tmp = te[2];
  3642. te[2] = te[8];
  3643. te[8] = tmp;
  3644. tmp = te[6];
  3645. te[6] = te[9];
  3646. te[9] = tmp;
  3647. tmp = te[3];
  3648. te[3] = te[12];
  3649. te[12] = tmp;
  3650. tmp = te[7];
  3651. te[7] = te[13];
  3652. te[13] = tmp;
  3653. tmp = te[11];
  3654. te[11] = te[14];
  3655. te[14] = tmp;
  3656. return this;
  3657. }
  3658. setPosition(x, y, z) {
  3659. const te = this.elements;
  3660. if (x.isVector3) {
  3661. te[12] = x.x;
  3662. te[13] = x.y;
  3663. te[14] = x.z;
  3664. } else {
  3665. te[12] = x;
  3666. te[13] = y;
  3667. te[14] = z;
  3668. }
  3669. return this;
  3670. }
  3671. invert() {
  3672. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3673. const te = this.elements,
  3674. n11 = te[0],
  3675. n21 = te[1],
  3676. n31 = te[2],
  3677. n41 = te[3],
  3678. n12 = te[4],
  3679. n22 = te[5],
  3680. n32 = te[6],
  3681. n42 = te[7],
  3682. n13 = te[8],
  3683. n23 = te[9],
  3684. n33 = te[10],
  3685. n43 = te[11],
  3686. n14 = te[12],
  3687. n24 = te[13],
  3688. n34 = te[14],
  3689. n44 = te[15],
  3690. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3691. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3692. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3693. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3694. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3695. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  3696. const detInv = 1 / det;
  3697. te[0] = t11 * detInv;
  3698. te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
  3699. te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
  3700. te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
  3701. te[4] = t12 * detInv;
  3702. te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
  3703. te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
  3704. te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
  3705. te[8] = t13 * detInv;
  3706. te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
  3707. te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
  3708. te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
  3709. te[12] = t14 * detInv;
  3710. te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
  3711. te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
  3712. te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
  3713. return this;
  3714. }
  3715. scale(v) {
  3716. const te = this.elements;
  3717. const x = v.x,
  3718. y = v.y,
  3719. z = v.z;
  3720. te[0] *= x;
  3721. te[4] *= y;
  3722. te[8] *= z;
  3723. te[1] *= x;
  3724. te[5] *= y;
  3725. te[9] *= z;
  3726. te[2] *= x;
  3727. te[6] *= y;
  3728. te[10] *= z;
  3729. te[3] *= x;
  3730. te[7] *= y;
  3731. te[11] *= z;
  3732. return this;
  3733. }
  3734. getMaxScaleOnAxis() {
  3735. const te = this.elements;
  3736. const scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  3737. const scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  3738. const scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  3739. return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
  3740. }
  3741. makeTranslation(x, y, z) {
  3742. this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
  3743. return this;
  3744. }
  3745. makeRotationX(theta) {
  3746. const c = Math.cos(theta),
  3747. s = Math.sin(theta);
  3748. this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
  3749. return this;
  3750. }
  3751. makeRotationY(theta) {
  3752. const c = Math.cos(theta),
  3753. s = Math.sin(theta);
  3754. this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
  3755. return this;
  3756. }
  3757. makeRotationZ(theta) {
  3758. const c = Math.cos(theta),
  3759. s = Math.sin(theta);
  3760. this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3761. return this;
  3762. }
  3763. makeRotationAxis(axis, angle) {
  3764. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3765. const c = Math.cos(angle);
  3766. const s = Math.sin(angle);
  3767. const t = 1 - c;
  3768. const x = axis.x,
  3769. y = axis.y,
  3770. z = axis.z;
  3771. const tx = t * x,
  3772. ty = t * y;
  3773. 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);
  3774. return this;
  3775. }
  3776. makeScale(x, y, z) {
  3777. this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
  3778. return this;
  3779. }
  3780. makeShear(xy, xz, yx, yz, zx, zy) {
  3781. this.set(1, yx, zx, 0, xy, 1, zy, 0, xz, yz, 1, 0, 0, 0, 0, 1);
  3782. return this;
  3783. }
  3784. compose(position, quaternion, scale) {
  3785. const te = this.elements;
  3786. const x = quaternion._x,
  3787. y = quaternion._y,
  3788. z = quaternion._z,
  3789. w = quaternion._w;
  3790. const x2 = x + x,
  3791. y2 = y + y,
  3792. z2 = z + z;
  3793. const xx = x * x2,
  3794. xy = x * y2,
  3795. xz = x * z2;
  3796. const yy = y * y2,
  3797. yz = y * z2,
  3798. zz = z * z2;
  3799. const wx = w * x2,
  3800. wy = w * y2,
  3801. wz = w * z2;
  3802. const sx = scale.x,
  3803. sy = scale.y,
  3804. sz = scale.z;
  3805. te[0] = (1 - (yy + zz)) * sx;
  3806. te[1] = (xy + wz) * sx;
  3807. te[2] = (xz - wy) * sx;
  3808. te[3] = 0;
  3809. te[4] = (xy - wz) * sy;
  3810. te[5] = (1 - (xx + zz)) * sy;
  3811. te[6] = (yz + wx) * sy;
  3812. te[7] = 0;
  3813. te[8] = (xz + wy) * sz;
  3814. te[9] = (yz - wx) * sz;
  3815. te[10] = (1 - (xx + yy)) * sz;
  3816. te[11] = 0;
  3817. te[12] = position.x;
  3818. te[13] = position.y;
  3819. te[14] = position.z;
  3820. te[15] = 1;
  3821. return this;
  3822. }
  3823. decompose(position, quaternion, scale) {
  3824. const te = this.elements;
  3825. let sx = _v1$5.set(te[0], te[1], te[2]).length();
  3826. const sy = _v1$5.set(te[4], te[5], te[6]).length();
  3827. const sz = _v1$5.set(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale
  3828. const det = this.determinant();
  3829. if (det < 0) sx = -sx;
  3830. position.x = te[12];
  3831. position.y = te[13];
  3832. position.z = te[14]; // scale the rotation part
  3833. _m1$2.copy(this);
  3834. const invSX = 1 / sx;
  3835. const invSY = 1 / sy;
  3836. const invSZ = 1 / sz;
  3837. _m1$2.elements[0] *= invSX;
  3838. _m1$2.elements[1] *= invSX;
  3839. _m1$2.elements[2] *= invSX;
  3840. _m1$2.elements[4] *= invSY;
  3841. _m1$2.elements[5] *= invSY;
  3842. _m1$2.elements[6] *= invSY;
  3843. _m1$2.elements[8] *= invSZ;
  3844. _m1$2.elements[9] *= invSZ;
  3845. _m1$2.elements[10] *= invSZ;
  3846. quaternion.setFromRotationMatrix(_m1$2);
  3847. scale.x = sx;
  3848. scale.y = sy;
  3849. scale.z = sz;
  3850. return this;
  3851. }
  3852. makePerspective(left, right, top, bottom, near, far) {
  3853. if (far === undefined) {
  3854. console.warn('THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.');
  3855. }
  3856. const te = this.elements;
  3857. const x = 2 * near / (right - left);
  3858. const y = 2 * near / (top - bottom);
  3859. const a = (right + left) / (right - left);
  3860. const b = (top + bottom) / (top - bottom);
  3861. const c = -(far + near) / (far - near);
  3862. const d = -2 * far * near / (far - near);
  3863. te[0] = x;
  3864. te[4] = 0;
  3865. te[8] = a;
  3866. te[12] = 0;
  3867. te[1] = 0;
  3868. te[5] = y;
  3869. te[9] = b;
  3870. te[13] = 0;
  3871. te[2] = 0;
  3872. te[6] = 0;
  3873. te[10] = c;
  3874. te[14] = d;
  3875. te[3] = 0;
  3876. te[7] = 0;
  3877. te[11] = -1;
  3878. te[15] = 0;
  3879. return this;
  3880. }
  3881. makeOrthographic(left, right, top, bottom, near, far) {
  3882. const te = this.elements;
  3883. const w = 1.0 / (right - left);
  3884. const h = 1.0 / (top - bottom);
  3885. const p = 1.0 / (far - near);
  3886. const x = (right + left) * w;
  3887. const y = (top + bottom) * h;
  3888. const z = (far + near) * p;
  3889. te[0] = 2 * w;
  3890. te[4] = 0;
  3891. te[8] = 0;
  3892. te[12] = -x;
  3893. te[1] = 0;
  3894. te[5] = 2 * h;
  3895. te[9] = 0;
  3896. te[13] = -y;
  3897. te[2] = 0;
  3898. te[6] = 0;
  3899. te[10] = -2 * p;
  3900. te[14] = -z;
  3901. te[3] = 0;
  3902. te[7] = 0;
  3903. te[11] = 0;
  3904. te[15] = 1;
  3905. return this;
  3906. }
  3907. equals(matrix) {
  3908. const te = this.elements;
  3909. const me = matrix.elements;
  3910. for (let i = 0; i < 16; i++) {
  3911. if (te[i] !== me[i]) return false;
  3912. }
  3913. return true;
  3914. }
  3915. fromArray(array, offset = 0) {
  3916. for (let i = 0; i < 16; i++) {
  3917. this.elements[i] = array[i + offset];
  3918. }
  3919. return this;
  3920. }
  3921. toArray(array = [], offset = 0) {
  3922. const te = this.elements;
  3923. array[offset] = te[0];
  3924. array[offset + 1] = te[1];
  3925. array[offset + 2] = te[2];
  3926. array[offset + 3] = te[3];
  3927. array[offset + 4] = te[4];
  3928. array[offset + 5] = te[5];
  3929. array[offset + 6] = te[6];
  3930. array[offset + 7] = te[7];
  3931. array[offset + 8] = te[8];
  3932. array[offset + 9] = te[9];
  3933. array[offset + 10] = te[10];
  3934. array[offset + 11] = te[11];
  3935. array[offset + 12] = te[12];
  3936. array[offset + 13] = te[13];
  3937. array[offset + 14] = te[14];
  3938. array[offset + 15] = te[15];
  3939. return array;
  3940. }
  3941. }
  3942. Matrix4.prototype.isMatrix4 = true;
  3943. const _v1$5 = /*@__PURE__*/new Vector3();
  3944. const _m1$2 = /*@__PURE__*/new Matrix4();
  3945. const _zero = /*@__PURE__*/new Vector3(0, 0, 0);
  3946. const _one = /*@__PURE__*/new Vector3(1, 1, 1);
  3947. const _x = /*@__PURE__*/new Vector3();
  3948. const _y = /*@__PURE__*/new Vector3();
  3949. const _z = /*@__PURE__*/new Vector3();
  3950. const _matrix$1 = /*@__PURE__*/new Matrix4();
  3951. const _quaternion$3 = /*@__PURE__*/new Quaternion();
  3952. class Euler {
  3953. constructor(x = 0, y = 0, z = 0, order = Euler.DefaultOrder) {
  3954. this._x = x;
  3955. this._y = y;
  3956. this._z = z;
  3957. this._order = order;
  3958. }
  3959. get x() {
  3960. return this._x;
  3961. }
  3962. set x(value) {
  3963. this._x = value;
  3964. this._onChangeCallback();
  3965. }
  3966. get y() {
  3967. return this._y;
  3968. }
  3969. set y(value) {
  3970. this._y = value;
  3971. this._onChangeCallback();
  3972. }
  3973. get z() {
  3974. return this._z;
  3975. }
  3976. set z(value) {
  3977. this._z = value;
  3978. this._onChangeCallback();
  3979. }
  3980. get order() {
  3981. return this._order;
  3982. }
  3983. set order(value) {
  3984. this._order = value;
  3985. this._onChangeCallback();
  3986. }
  3987. set(x, y, z, order = this._order) {
  3988. this._x = x;
  3989. this._y = y;
  3990. this._z = z;
  3991. this._order = order;
  3992. this._onChangeCallback();
  3993. return this;
  3994. }
  3995. clone() {
  3996. return new this.constructor(this._x, this._y, this._z, this._order);
  3997. }
  3998. copy(euler) {
  3999. this._x = euler._x;
  4000. this._y = euler._y;
  4001. this._z = euler._z;
  4002. this._order = euler._order;
  4003. this._onChangeCallback();
  4004. return this;
  4005. }
  4006. setFromRotationMatrix(m, order = this._order, update = true) {
  4007. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4008. const te = m.elements;
  4009. const m11 = te[0],
  4010. m12 = te[4],
  4011. m13 = te[8];
  4012. const m21 = te[1],
  4013. m22 = te[5],
  4014. m23 = te[9];
  4015. const m31 = te[2],
  4016. m32 = te[6],
  4017. m33 = te[10];
  4018. switch (order) {
  4019. case 'XYZ':
  4020. this._y = Math.asin(clamp(m13, -1, 1));
  4021. if (Math.abs(m13) < 0.9999999) {
  4022. this._x = Math.atan2(-m23, m33);
  4023. this._z = Math.atan2(-m12, m11);
  4024. } else {
  4025. this._x = Math.atan2(m32, m22);
  4026. this._z = 0;
  4027. }
  4028. break;
  4029. case 'YXZ':
  4030. this._x = Math.asin(-clamp(m23, -1, 1));
  4031. if (Math.abs(m23) < 0.9999999) {
  4032. this._y = Math.atan2(m13, m33);
  4033. this._z = Math.atan2(m21, m22);
  4034. } else {
  4035. this._y = Math.atan2(-m31, m11);
  4036. this._z = 0;
  4037. }
  4038. break;
  4039. case 'ZXY':
  4040. this._x = Math.asin(clamp(m32, -1, 1));
  4041. if (Math.abs(m32) < 0.9999999) {
  4042. this._y = Math.atan2(-m31, m33);
  4043. this._z = Math.atan2(-m12, m22);
  4044. } else {
  4045. this._y = 0;
  4046. this._z = Math.atan2(m21, m11);
  4047. }
  4048. break;
  4049. case 'ZYX':
  4050. this._y = Math.asin(-clamp(m31, -1, 1));
  4051. if (Math.abs(m31) < 0.9999999) {
  4052. this._x = Math.atan2(m32, m33);
  4053. this._z = Math.atan2(m21, m11);
  4054. } else {
  4055. this._x = 0;
  4056. this._z = Math.atan2(-m12, m22);
  4057. }
  4058. break;
  4059. case 'YZX':
  4060. this._z = Math.asin(clamp(m21, -1, 1));
  4061. if (Math.abs(m21) < 0.9999999) {
  4062. this._x = Math.atan2(-m23, m22);
  4063. this._y = Math.atan2(-m31, m11);
  4064. } else {
  4065. this._x = 0;
  4066. this._y = Math.atan2(m13, m33);
  4067. }
  4068. break;
  4069. case 'XZY':
  4070. this._z = Math.asin(-clamp(m12, -1, 1));
  4071. if (Math.abs(m12) < 0.9999999) {
  4072. this._x = Math.atan2(m32, m22);
  4073. this._y = Math.atan2(m13, m11);
  4074. } else {
  4075. this._x = Math.atan2(-m23, m33);
  4076. this._y = 0;
  4077. }
  4078. break;
  4079. default:
  4080. console.warn('THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order);
  4081. }
  4082. this._order = order;
  4083. if (update === true) this._onChangeCallback();
  4084. return this;
  4085. }
  4086. setFromQuaternion(q, order, update) {
  4087. _matrix$1.makeRotationFromQuaternion(q);
  4088. return this.setFromRotationMatrix(_matrix$1, order, update);
  4089. }
  4090. setFromVector3(v, order = this._order) {
  4091. return this.set(v.x, v.y, v.z, order);
  4092. }
  4093. reorder(newOrder) {
  4094. // WARNING: this discards revolution information -bhouston
  4095. _quaternion$3.setFromEuler(this);
  4096. return this.setFromQuaternion(_quaternion$3, newOrder);
  4097. }
  4098. equals(euler) {
  4099. return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
  4100. }
  4101. fromArray(array) {
  4102. this._x = array[0];
  4103. this._y = array[1];
  4104. this._z = array[2];
  4105. if (array[3] !== undefined) this._order = array[3];
  4106. this._onChangeCallback();
  4107. return this;
  4108. }
  4109. toArray(array = [], offset = 0) {
  4110. array[offset] = this._x;
  4111. array[offset + 1] = this._y;
  4112. array[offset + 2] = this._z;
  4113. array[offset + 3] = this._order;
  4114. return array;
  4115. }
  4116. toVector3(optionalResult) {
  4117. if (optionalResult) {
  4118. return optionalResult.set(this._x, this._y, this._z);
  4119. } else {
  4120. return new Vector3(this._x, this._y, this._z);
  4121. }
  4122. }
  4123. _onChange(callback) {
  4124. this._onChangeCallback = callback;
  4125. return this;
  4126. }
  4127. _onChangeCallback() {}
  4128. }
  4129. Euler.prototype.isEuler = true;
  4130. Euler.DefaultOrder = 'XYZ';
  4131. Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  4132. class Layers {
  4133. constructor() {
  4134. this.mask = 1 | 0;
  4135. }
  4136. set(channel) {
  4137. this.mask = (1 << channel | 0) >>> 0;
  4138. }
  4139. enable(channel) {
  4140. this.mask |= 1 << channel | 0;
  4141. }
  4142. enableAll() {
  4143. this.mask = 0xffffffff | 0;
  4144. }
  4145. toggle(channel) {
  4146. this.mask ^= 1 << channel | 0;
  4147. }
  4148. disable(channel) {
  4149. this.mask &= ~(1 << channel | 0);
  4150. }
  4151. disableAll() {
  4152. this.mask = 0;
  4153. }
  4154. test(layers) {
  4155. return (this.mask & layers.mask) !== 0;
  4156. }
  4157. isEnabled(channel) {
  4158. return (this.mask & (1 << channel | 0)) !== 0;
  4159. }
  4160. }
  4161. let _object3DId = 0;
  4162. const _v1$4 = /*@__PURE__*/new Vector3();
  4163. const _q1 = /*@__PURE__*/new Quaternion();
  4164. const _m1$1 = /*@__PURE__*/new Matrix4();
  4165. const _target = /*@__PURE__*/new Vector3();
  4166. const _position$3 = /*@__PURE__*/new Vector3();
  4167. const _scale$2 = /*@__PURE__*/new Vector3();
  4168. const _quaternion$2 = /*@__PURE__*/new Quaternion();
  4169. const _xAxis = /*@__PURE__*/new Vector3(1, 0, 0);
  4170. const _yAxis = /*@__PURE__*/new Vector3(0, 1, 0);
  4171. const _zAxis = /*@__PURE__*/new Vector3(0, 0, 1);
  4172. const _addedEvent = {
  4173. type: 'added'
  4174. };
  4175. const _removedEvent = {
  4176. type: 'removed'
  4177. };
  4178. class Object3D extends EventDispatcher {
  4179. constructor() {
  4180. super();
  4181. Object.defineProperty(this, 'id', {
  4182. value: _object3DId++
  4183. });
  4184. this.uuid = generateUUID();
  4185. this.name = '';
  4186. this.type = 'Object3D';
  4187. this.parent = null;
  4188. this.children = [];
  4189. this.up = Object3D.DefaultUp.clone();
  4190. const position = new Vector3();
  4191. const rotation = new Euler();
  4192. const quaternion = new Quaternion();
  4193. const scale = new Vector3(1, 1, 1);
  4194. function onRotationChange() {
  4195. quaternion.setFromEuler(rotation, false);
  4196. }
  4197. function onQuaternionChange() {
  4198. rotation.setFromQuaternion(quaternion, undefined, false);
  4199. }
  4200. rotation._onChange(onRotationChange);
  4201. quaternion._onChange(onQuaternionChange);
  4202. Object.defineProperties(this, {
  4203. position: {
  4204. configurable: true,
  4205. enumerable: true,
  4206. value: position
  4207. },
  4208. rotation: {
  4209. configurable: true,
  4210. enumerable: true,
  4211. value: rotation
  4212. },
  4213. quaternion: {
  4214. configurable: true,
  4215. enumerable: true,
  4216. value: quaternion
  4217. },
  4218. scale: {
  4219. configurable: true,
  4220. enumerable: true,
  4221. value: scale
  4222. },
  4223. modelViewMatrix: {
  4224. value: new Matrix4()
  4225. },
  4226. normalMatrix: {
  4227. value: new Matrix3()
  4228. }
  4229. });
  4230. this.matrix = new Matrix4();
  4231. this.matrixWorld = new Matrix4();
  4232. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  4233. this.matrixWorldNeedsUpdate = false;
  4234. this.layers = new Layers();
  4235. this.visible = true;
  4236. this.castShadow = false;
  4237. this.receiveShadow = false;
  4238. this.frustumCulled = true;
  4239. this.renderOrder = 0;
  4240. this.animations = [];
  4241. this.userData = {};
  4242. }
  4243. onBeforeRender() {}
  4244. onAfterRender() {}
  4245. applyMatrix4(matrix) {
  4246. if (this.matrixAutoUpdate) this.updateMatrix();
  4247. this.matrix.premultiply(matrix);
  4248. this.matrix.decompose(this.position, this.quaternion, this.scale);
  4249. }
  4250. applyQuaternion(q) {
  4251. this.quaternion.premultiply(q);
  4252. return this;
  4253. }
  4254. setRotationFromAxisAngle(axis, angle) {
  4255. // assumes axis is normalized
  4256. this.quaternion.setFromAxisAngle(axis, angle);
  4257. }
  4258. setRotationFromEuler(euler) {
  4259. this.quaternion.setFromEuler(euler, true);
  4260. }
  4261. setRotationFromMatrix(m) {
  4262. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4263. this.quaternion.setFromRotationMatrix(m);
  4264. }
  4265. setRotationFromQuaternion(q) {
  4266. // assumes q is normalized
  4267. this.quaternion.copy(q);
  4268. }
  4269. rotateOnAxis(axis, angle) {
  4270. // rotate object on axis in object space
  4271. // axis is assumed to be normalized
  4272. _q1.setFromAxisAngle(axis, angle);
  4273. this.quaternion.multiply(_q1);
  4274. return this;
  4275. }
  4276. rotateOnWorldAxis(axis, angle) {
  4277. // rotate object on axis in world space
  4278. // axis is assumed to be normalized
  4279. // method assumes no rotated parent
  4280. _q1.setFromAxisAngle(axis, angle);
  4281. this.quaternion.premultiply(_q1);
  4282. return this;
  4283. }
  4284. rotateX(angle) {
  4285. return this.rotateOnAxis(_xAxis, angle);
  4286. }
  4287. rotateY(angle) {
  4288. return this.rotateOnAxis(_yAxis, angle);
  4289. }
  4290. rotateZ(angle) {
  4291. return this.rotateOnAxis(_zAxis, angle);
  4292. }
  4293. translateOnAxis(axis, distance) {
  4294. // translate object by distance along axis in object space
  4295. // axis is assumed to be normalized
  4296. _v1$4.copy(axis).applyQuaternion(this.quaternion);
  4297. this.position.add(_v1$4.multiplyScalar(distance));
  4298. return this;
  4299. }
  4300. translateX(distance) {
  4301. return this.translateOnAxis(_xAxis, distance);
  4302. }
  4303. translateY(distance) {
  4304. return this.translateOnAxis(_yAxis, distance);
  4305. }
  4306. translateZ(distance) {
  4307. return this.translateOnAxis(_zAxis, distance);
  4308. }
  4309. localToWorld(vector) {
  4310. return vector.applyMatrix4(this.matrixWorld);
  4311. }
  4312. worldToLocal(vector) {
  4313. return vector.applyMatrix4(_m1$1.copy(this.matrixWorld).invert());
  4314. }
  4315. lookAt(x, y, z) {
  4316. // This method does not support objects having non-uniformly-scaled parent(s)
  4317. if (x.isVector3) {
  4318. _target.copy(x);
  4319. } else {
  4320. _target.set(x, y, z);
  4321. }
  4322. const parent = this.parent;
  4323. this.updateWorldMatrix(true, false);
  4324. _position$3.setFromMatrixPosition(this.matrixWorld);
  4325. if (this.isCamera || this.isLight) {
  4326. _m1$1.lookAt(_position$3, _target, this.up);
  4327. } else {
  4328. _m1$1.lookAt(_target, _position$3, this.up);
  4329. }
  4330. this.quaternion.setFromRotationMatrix(_m1$1);
  4331. if (parent) {
  4332. _m1$1.extractRotation(parent.matrixWorld);
  4333. _q1.setFromRotationMatrix(_m1$1);
  4334. this.quaternion.premultiply(_q1.invert());
  4335. }
  4336. }
  4337. add(object) {
  4338. if (arguments.length > 1) {
  4339. for (let i = 0; i < arguments.length; i++) {
  4340. this.add(arguments[i]);
  4341. }
  4342. return this;
  4343. }
  4344. if (object === this) {
  4345. console.error('THREE.Object3D.add: object can\'t be added as a child of itself.', object);
  4346. return this;
  4347. }
  4348. if (object && object.isObject3D) {
  4349. if (object.parent !== null) {
  4350. object.parent.remove(object);
  4351. }
  4352. object.parent = this;
  4353. this.children.push(object);
  4354. object.dispatchEvent(_addedEvent);
  4355. } else {
  4356. console.error('THREE.Object3D.add: object not an instance of THREE.Object3D.', object);
  4357. }
  4358. return this;
  4359. }
  4360. remove(object) {
  4361. if (arguments.length > 1) {
  4362. for (let i = 0; i < arguments.length; i++) {
  4363. this.remove(arguments[i]);
  4364. }
  4365. return this;
  4366. }
  4367. const index = this.children.indexOf(object);
  4368. if (index !== -1) {
  4369. object.parent = null;
  4370. this.children.splice(index, 1);
  4371. object.dispatchEvent(_removedEvent);
  4372. }
  4373. return this;
  4374. }
  4375. removeFromParent() {
  4376. const parent = this.parent;
  4377. if (parent !== null) {
  4378. parent.remove(this);
  4379. }
  4380. return this;
  4381. }
  4382. clear() {
  4383. for (let i = 0; i < this.children.length; i++) {
  4384. const object = this.children[i];
  4385. object.parent = null;
  4386. object.dispatchEvent(_removedEvent);
  4387. }
  4388. this.children.length = 0;
  4389. return this;
  4390. }
  4391. attach(object) {
  4392. // adds object as a child of this, while maintaining the object's world transform
  4393. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  4394. this.updateWorldMatrix(true, false);
  4395. _m1$1.copy(this.matrixWorld).invert();
  4396. if (object.parent !== null) {
  4397. object.parent.updateWorldMatrix(true, false);
  4398. _m1$1.multiply(object.parent.matrixWorld);
  4399. }
  4400. object.applyMatrix4(_m1$1);
  4401. this.add(object);
  4402. object.updateWorldMatrix(false, true);
  4403. return this;
  4404. }
  4405. getObjectById(id) {
  4406. return this.getObjectByProperty('id', id);
  4407. }
  4408. getObjectByName(name) {
  4409. return this.getObjectByProperty('name', name);
  4410. }
  4411. getObjectByProperty(name, value) {
  4412. if (this[name] === value) return this;
  4413. for (let i = 0, l = this.children.length; i < l; i++) {
  4414. const child = this.children[i];
  4415. const object = child.getObjectByProperty(name, value);
  4416. if (object !== undefined) {
  4417. return object;
  4418. }
  4419. }
  4420. return undefined;
  4421. }
  4422. getWorldPosition(target) {
  4423. this.updateWorldMatrix(true, false);
  4424. return target.setFromMatrixPosition(this.matrixWorld);
  4425. }
  4426. getWorldQuaternion(target) {
  4427. this.updateWorldMatrix(true, false);
  4428. this.matrixWorld.decompose(_position$3, target, _scale$2);
  4429. return target;
  4430. }
  4431. getWorldScale(target) {
  4432. this.updateWorldMatrix(true, false);
  4433. this.matrixWorld.decompose(_position$3, _quaternion$2, target);
  4434. return target;
  4435. }
  4436. getWorldDirection(target) {
  4437. this.updateWorldMatrix(true, false);
  4438. const e = this.matrixWorld.elements;
  4439. return target.set(e[8], e[9], e[10]).normalize();
  4440. }
  4441. raycast() {}
  4442. traverse(callback) {
  4443. callback(this);
  4444. const children = this.children;
  4445. for (let i = 0, l = children.length; i < l; i++) {
  4446. children[i].traverse(callback);
  4447. }
  4448. }
  4449. traverseVisible(callback) {
  4450. if (this.visible === false) return;
  4451. callback(this);
  4452. const children = this.children;
  4453. for (let i = 0, l = children.length; i < l; i++) {
  4454. children[i].traverseVisible(callback);
  4455. }
  4456. }
  4457. traverseAncestors(callback) {
  4458. const parent = this.parent;
  4459. if (parent !== null) {
  4460. callback(parent);
  4461. parent.traverseAncestors(callback);
  4462. }
  4463. }
  4464. updateMatrix() {
  4465. this.matrix.compose(this.position, this.quaternion, this.scale);
  4466. this.matrixWorldNeedsUpdate = true;
  4467. }
  4468. updateMatrixWorld(force) {
  4469. if (this.matrixAutoUpdate) this.updateMatrix();
  4470. if (this.matrixWorldNeedsUpdate || force) {
  4471. if (this.parent === null) {
  4472. this.matrixWorld.copy(this.matrix);
  4473. } else {
  4474. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4475. }
  4476. this.matrixWorldNeedsUpdate = false;
  4477. force = true;
  4478. } // update children
  4479. const children = this.children;
  4480. for (let i = 0, l = children.length; i < l; i++) {
  4481. children[i].updateMatrixWorld(force);
  4482. }
  4483. }
  4484. updateWorldMatrix(updateParents, updateChildren) {
  4485. const parent = this.parent;
  4486. if (updateParents === true && parent !== null) {
  4487. parent.updateWorldMatrix(true, false);
  4488. }
  4489. if (this.matrixAutoUpdate) this.updateMatrix();
  4490. if (this.parent === null) {
  4491. this.matrixWorld.copy(this.matrix);
  4492. } else {
  4493. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4494. } // update children
  4495. if (updateChildren === true) {
  4496. const children = this.children;
  4497. for (let i = 0, l = children.length; i < l; i++) {
  4498. children[i].updateWorldMatrix(false, true);
  4499. }
  4500. }
  4501. }
  4502. toJSON(meta) {
  4503. // meta is a string when called from JSON.stringify
  4504. const isRootObject = meta === undefined || typeof meta === 'string';
  4505. const output = {}; // meta is a hash used to collect geometries, materials.
  4506. // not providing it implies that this is the root object
  4507. // being serialized.
  4508. if (isRootObject) {
  4509. // initialize meta obj
  4510. meta = {
  4511. geometries: {},
  4512. materials: {},
  4513. textures: {},
  4514. images: {},
  4515. shapes: {},
  4516. skeletons: {},
  4517. animations: {}
  4518. };
  4519. output.metadata = {
  4520. version: 4.5,
  4521. type: 'Object',
  4522. generator: 'Object3D.toJSON'
  4523. };
  4524. } // standard Object3D serialization
  4525. const object = {};
  4526. object.uuid = this.uuid;
  4527. object.type = this.type;
  4528. if (this.name !== '') object.name = this.name;
  4529. if (this.castShadow === true) object.castShadow = true;
  4530. if (this.receiveShadow === true) object.receiveShadow = true;
  4531. if (this.visible === false) object.visible = false;
  4532. if (this.frustumCulled === false) object.frustumCulled = false;
  4533. if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
  4534. if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;
  4535. object.layers = this.layers.mask;
  4536. object.matrix = this.matrix.toArray();
  4537. if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; // object specific properties
  4538. if (this.isInstancedMesh) {
  4539. object.type = 'InstancedMesh';
  4540. object.count = this.count;
  4541. object.instanceMatrix = this.instanceMatrix.toJSON();
  4542. if (this.instanceColor !== null) object.instanceColor = this.instanceColor.toJSON();
  4543. } //
  4544. function serialize(library, element) {
  4545. if (library[element.uuid] === undefined) {
  4546. library[element.uuid] = element.toJSON(meta);
  4547. }
  4548. return element.uuid;
  4549. }
  4550. if (this.isScene) {
  4551. if (this.background) {
  4552. if (this.background.isColor) {
  4553. object.background = this.background.toJSON();
  4554. } else if (this.background.isTexture) {
  4555. object.background = this.background.toJSON(meta).uuid;
  4556. }
  4557. }
  4558. if (this.environment && this.environment.isTexture) {
  4559. object.environment = this.environment.toJSON(meta).uuid;
  4560. }
  4561. } else if (this.isMesh || this.isLine || this.isPoints) {
  4562. object.geometry = serialize(meta.geometries, this.geometry);
  4563. const parameters = this.geometry.parameters;
  4564. if (parameters !== undefined && parameters.shapes !== undefined) {
  4565. const shapes = parameters.shapes;
  4566. if (Array.isArray(shapes)) {
  4567. for (let i = 0, l = shapes.length; i < l; i++) {
  4568. const shape = shapes[i];
  4569. serialize(meta.shapes, shape);
  4570. }
  4571. } else {
  4572. serialize(meta.shapes, shapes);
  4573. }
  4574. }
  4575. }
  4576. if (this.isSkinnedMesh) {
  4577. object.bindMode = this.bindMode;
  4578. object.bindMatrix = this.bindMatrix.toArray();
  4579. if (this.skeleton !== undefined) {
  4580. serialize(meta.skeletons, this.skeleton);
  4581. object.skeleton = this.skeleton.uuid;
  4582. }
  4583. }
  4584. if (this.material !== undefined) {
  4585. if (Array.isArray(this.material)) {
  4586. const uuids = [];
  4587. for (let i = 0, l = this.material.length; i < l; i++) {
  4588. uuids.push(serialize(meta.materials, this.material[i]));
  4589. }
  4590. object.material = uuids;
  4591. } else {
  4592. object.material = serialize(meta.materials, this.material);
  4593. }
  4594. } //
  4595. if (this.children.length > 0) {
  4596. object.children = [];
  4597. for (let i = 0; i < this.children.length; i++) {
  4598. object.children.push(this.children[i].toJSON(meta).object);
  4599. }
  4600. } //
  4601. if (this.animations.length > 0) {
  4602. object.animations = [];
  4603. for (let i = 0; i < this.animations.length; i++) {
  4604. const animation = this.animations[i];
  4605. object.animations.push(serialize(meta.animations, animation));
  4606. }
  4607. }
  4608. if (isRootObject) {
  4609. const geometries = extractFromCache(meta.geometries);
  4610. const materials = extractFromCache(meta.materials);
  4611. const textures = extractFromCache(meta.textures);
  4612. const images = extractFromCache(meta.images);
  4613. const shapes = extractFromCache(meta.shapes);
  4614. const skeletons = extractFromCache(meta.skeletons);
  4615. const animations = extractFromCache(meta.animations);
  4616. if (geometries.length > 0) output.geometries = geometries;
  4617. if (materials.length > 0) output.materials = materials;
  4618. if (textures.length > 0) output.textures = textures;
  4619. if (images.length > 0) output.images = images;
  4620. if (shapes.length > 0) output.shapes = shapes;
  4621. if (skeletons.length > 0) output.skeletons = skeletons;
  4622. if (animations.length > 0) output.animations = animations;
  4623. }
  4624. output.object = object;
  4625. return output; // extract data from the cache hash
  4626. // remove metadata on each item
  4627. // and return as array
  4628. function extractFromCache(cache) {
  4629. const values = [];
  4630. for (const key in cache) {
  4631. const data = cache[key];
  4632. delete data.metadata;
  4633. values.push(data);
  4634. }
  4635. return values;
  4636. }
  4637. }
  4638. clone(recursive) {
  4639. return new this.constructor().copy(this, recursive);
  4640. }
  4641. copy(source, recursive = true) {
  4642. this.name = source.name;
  4643. this.up.copy(source.up);
  4644. this.position.copy(source.position);
  4645. this.rotation.order = source.rotation.order;
  4646. this.quaternion.copy(source.quaternion);
  4647. this.scale.copy(source.scale);
  4648. this.matrix.copy(source.matrix);
  4649. this.matrixWorld.copy(source.matrixWorld);
  4650. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4651. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4652. this.layers.mask = source.layers.mask;
  4653. this.visible = source.visible;
  4654. this.castShadow = source.castShadow;
  4655. this.receiveShadow = source.receiveShadow;
  4656. this.frustumCulled = source.frustumCulled;
  4657. this.renderOrder = source.renderOrder;
  4658. this.userData = JSON.parse(JSON.stringify(source.userData));
  4659. if (recursive === true) {
  4660. for (let i = 0; i < source.children.length; i++) {
  4661. const child = source.children[i];
  4662. this.add(child.clone());
  4663. }
  4664. }
  4665. return this;
  4666. }
  4667. }
  4668. Object3D.DefaultUp = new Vector3(0, 1, 0);
  4669. Object3D.DefaultMatrixAutoUpdate = true;
  4670. Object3D.prototype.isObject3D = true;
  4671. const _v0$1 = /*@__PURE__*/new Vector3();
  4672. const _v1$3 = /*@__PURE__*/new Vector3();
  4673. const _v2$2 = /*@__PURE__*/new Vector3();
  4674. const _v3$1 = /*@__PURE__*/new Vector3();
  4675. const _vab = /*@__PURE__*/new Vector3();
  4676. const _vac = /*@__PURE__*/new Vector3();
  4677. const _vbc = /*@__PURE__*/new Vector3();
  4678. const _vap = /*@__PURE__*/new Vector3();
  4679. const _vbp = /*@__PURE__*/new Vector3();
  4680. const _vcp = /*@__PURE__*/new Vector3();
  4681. class Triangle {
  4682. constructor(a = new Vector3(), b = new Vector3(), c = new Vector3()) {
  4683. this.a = a;
  4684. this.b = b;
  4685. this.c = c;
  4686. }
  4687. static getNormal(a, b, c, target) {
  4688. target.subVectors(c, b);
  4689. _v0$1.subVectors(a, b);
  4690. target.cross(_v0$1);
  4691. const targetLengthSq = target.lengthSq();
  4692. if (targetLengthSq > 0) {
  4693. return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
  4694. }
  4695. return target.set(0, 0, 0);
  4696. } // static/instance method to calculate barycentric coordinates
  4697. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4698. static getBarycoord(point, a, b, c, target) {
  4699. _v0$1.subVectors(c, a);
  4700. _v1$3.subVectors(b, a);
  4701. _v2$2.subVectors(point, a);
  4702. const dot00 = _v0$1.dot(_v0$1);
  4703. const dot01 = _v0$1.dot(_v1$3);
  4704. const dot02 = _v0$1.dot(_v2$2);
  4705. const dot11 = _v1$3.dot(_v1$3);
  4706. const dot12 = _v1$3.dot(_v2$2);
  4707. const denom = dot00 * dot11 - dot01 * dot01; // collinear or singular triangle
  4708. if (denom === 0) {
  4709. // arbitrary location outside of triangle?
  4710. // not sure if this is the best idea, maybe should be returning undefined
  4711. return target.set(-2, -1, -1);
  4712. }
  4713. const invDenom = 1 / denom;
  4714. const u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  4715. const v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1
  4716. return target.set(1 - u - v, v, u);
  4717. }
  4718. static containsPoint(point, a, b, c) {
  4719. this.getBarycoord(point, a, b, c, _v3$1);
  4720. return _v3$1.x >= 0 && _v3$1.y >= 0 && _v3$1.x + _v3$1.y <= 1;
  4721. }
  4722. static getUV(point, p1, p2, p3, uv1, uv2, uv3, target) {
  4723. this.getBarycoord(point, p1, p2, p3, _v3$1);
  4724. target.set(0, 0);
  4725. target.addScaledVector(uv1, _v3$1.x);
  4726. target.addScaledVector(uv2, _v3$1.y);
  4727. target.addScaledVector(uv3, _v3$1.z);
  4728. return target;
  4729. }
  4730. static isFrontFacing(a, b, c, direction) {
  4731. _v0$1.subVectors(c, b);
  4732. _v1$3.subVectors(a, b); // strictly front facing
  4733. return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
  4734. }
  4735. set(a, b, c) {
  4736. this.a.copy(a);
  4737. this.b.copy(b);
  4738. this.c.copy(c);
  4739. return this;
  4740. }
  4741. setFromPointsAndIndices(points, i0, i1, i2) {
  4742. this.a.copy(points[i0]);
  4743. this.b.copy(points[i1]);
  4744. this.c.copy(points[i2]);
  4745. return this;
  4746. }
  4747. setFromAttributeAndIndices(attribute, i0, i1, i2) {
  4748. this.a.fromBufferAttribute(attribute, i0);
  4749. this.b.fromBufferAttribute(attribute, i1);
  4750. this.c.fromBufferAttribute(attribute, i2);
  4751. return this;
  4752. }
  4753. clone() {
  4754. return new this.constructor().copy(this);
  4755. }
  4756. copy(triangle) {
  4757. this.a.copy(triangle.a);
  4758. this.b.copy(triangle.b);
  4759. this.c.copy(triangle.c);
  4760. return this;
  4761. }
  4762. getArea() {
  4763. _v0$1.subVectors(this.c, this.b);
  4764. _v1$3.subVectors(this.a, this.b);
  4765. return _v0$1.cross(_v1$3).length() * 0.5;
  4766. }
  4767. getMidpoint(target) {
  4768. return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  4769. }
  4770. getNormal(target) {
  4771. return Triangle.getNormal(this.a, this.b, this.c, target);
  4772. }
  4773. getPlane(target) {
  4774. return target.setFromCoplanarPoints(this.a, this.b, this.c);
  4775. }
  4776. getBarycoord(point, target) {
  4777. return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
  4778. }
  4779. getUV(point, uv1, uv2, uv3, target) {
  4780. return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
  4781. }
  4782. containsPoint(point) {
  4783. return Triangle.containsPoint(point, this.a, this.b, this.c);
  4784. }
  4785. isFrontFacing(direction) {
  4786. return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
  4787. }
  4788. intersectsBox(box) {
  4789. return box.intersectsTriangle(this);
  4790. }
  4791. closestPointToPoint(p, target) {
  4792. const a = this.a,
  4793. b = this.b,
  4794. c = this.c;
  4795. let v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  4796. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  4797. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  4798. // basically, we're distinguishing which of the voronoi regions of the triangle
  4799. // the point lies in with the minimum amount of redundant computation.
  4800. _vab.subVectors(b, a);
  4801. _vac.subVectors(c, a);
  4802. _vap.subVectors(p, a);
  4803. const d1 = _vab.dot(_vap);
  4804. const d2 = _vac.dot(_vap);
  4805. if (d1 <= 0 && d2 <= 0) {
  4806. // vertex region of A; barycentric coords (1, 0, 0)
  4807. return target.copy(a);
  4808. }
  4809. _vbp.subVectors(p, b);
  4810. const d3 = _vab.dot(_vbp);
  4811. const d4 = _vac.dot(_vbp);
  4812. if (d3 >= 0 && d4 <= d3) {
  4813. // vertex region of B; barycentric coords (0, 1, 0)
  4814. return target.copy(b);
  4815. }
  4816. const vc = d1 * d4 - d3 * d2;
  4817. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  4818. v = d1 / (d1 - d3); // edge region of AB; barycentric coords (1-v, v, 0)
  4819. return target.copy(a).addScaledVector(_vab, v);
  4820. }
  4821. _vcp.subVectors(p, c);
  4822. const d5 = _vab.dot(_vcp);
  4823. const d6 = _vac.dot(_vcp);
  4824. if (d6 >= 0 && d5 <= d6) {
  4825. // vertex region of C; barycentric coords (0, 0, 1)
  4826. return target.copy(c);
  4827. }
  4828. const vb = d5 * d2 - d1 * d6;
  4829. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  4830. w = d2 / (d2 - d6); // edge region of AC; barycentric coords (1-w, 0, w)
  4831. return target.copy(a).addScaledVector(_vac, w);
  4832. }
  4833. const va = d3 * d6 - d5 * d4;
  4834. if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
  4835. _vbc.subVectors(c, b);
  4836. w = (d4 - d3) / (d4 - d3 + (d5 - d6)); // edge region of BC; barycentric coords (0, 1-w, w)
  4837. return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
  4838. } // face region
  4839. const denom = 1 / (va + vb + vc); // u = va * denom
  4840. v = vb * denom;
  4841. w = vc * denom;
  4842. return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
  4843. }
  4844. equals(triangle) {
  4845. return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
  4846. }
  4847. }
  4848. let materialId = 0;
  4849. class Material extends EventDispatcher {
  4850. constructor() {
  4851. super();
  4852. Object.defineProperty(this, 'id', {
  4853. value: materialId++
  4854. });
  4855. this.uuid = generateUUID();
  4856. this.name = '';
  4857. this.type = 'Material';
  4858. this.fog = true;
  4859. this.blending = NormalBlending;
  4860. this.side = FrontSide;
  4861. this.vertexColors = false;
  4862. this.opacity = 1;
  4863. this.format = RGBAFormat;
  4864. this.transparent = false;
  4865. this.blendSrc = SrcAlphaFactor;
  4866. this.blendDst = OneMinusSrcAlphaFactor;
  4867. this.blendEquation = AddEquation;
  4868. this.blendSrcAlpha = null;
  4869. this.blendDstAlpha = null;
  4870. this.blendEquationAlpha = null;
  4871. this.depthFunc = LessEqualDepth;
  4872. this.depthTest = true;
  4873. this.depthWrite = true;
  4874. this.stencilWriteMask = 0xff;
  4875. this.stencilFunc = AlwaysStencilFunc;
  4876. this.stencilRef = 0;
  4877. this.stencilFuncMask = 0xff;
  4878. this.stencilFail = KeepStencilOp;
  4879. this.stencilZFail = KeepStencilOp;
  4880. this.stencilZPass = KeepStencilOp;
  4881. this.stencilWrite = false;
  4882. this.clippingPlanes = null;
  4883. this.clipIntersection = false;
  4884. this.clipShadows = false;
  4885. this.shadowSide = null;
  4886. this.colorWrite = true;
  4887. this.precision = null; // override the renderer's default precision for this material
  4888. this.polygonOffset = false;
  4889. this.polygonOffsetFactor = 0;
  4890. this.polygonOffsetUnits = 0;
  4891. this.dithering = false;
  4892. this.alphaToCoverage = false;
  4893. this.premultipliedAlpha = false;
  4894. this.visible = true;
  4895. this.toneMapped = true;
  4896. this.userData = {};
  4897. this.version = 0;
  4898. this._alphaTest = 0;
  4899. }
  4900. get alphaTest() {
  4901. return this._alphaTest;
  4902. }
  4903. set alphaTest(value) {
  4904. if (this._alphaTest > 0 !== value > 0) {
  4905. this.version++;
  4906. }
  4907. this._alphaTest = value;
  4908. }
  4909. onBuild() {}
  4910. onBeforeRender() {}
  4911. onBeforeCompile() {}
  4912. customProgramCacheKey() {
  4913. return this.onBeforeCompile.toString();
  4914. }
  4915. setValues(values) {
  4916. if (values === undefined) return;
  4917. for (const key in values) {
  4918. const newValue = values[key];
  4919. if (newValue === undefined) {
  4920. console.warn('THREE.Material: \'' + key + '\' parameter is undefined.');
  4921. continue;
  4922. } // for backward compatability if shading is set in the constructor
  4923. if (key === 'shading') {
  4924. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  4925. this.flatShading = newValue === FlatShading ? true : false;
  4926. continue;
  4927. }
  4928. const currentValue = this[key];
  4929. if (currentValue === undefined) {
  4930. console.warn('THREE.' + this.type + ': \'' + key + '\' is not a property of this material.');
  4931. continue;
  4932. }
  4933. if (currentValue && currentValue.isColor) {
  4934. currentValue.set(newValue);
  4935. } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
  4936. currentValue.copy(newValue);
  4937. } else {
  4938. this[key] = newValue;
  4939. }
  4940. }
  4941. }
  4942. toJSON(meta) {
  4943. const isRoot = meta === undefined || typeof meta === 'string';
  4944. if (isRoot) {
  4945. meta = {
  4946. textures: {},
  4947. images: {}
  4948. };
  4949. }
  4950. const data = {
  4951. metadata: {
  4952. version: 4.5,
  4953. type: 'Material',
  4954. generator: 'Material.toJSON'
  4955. }
  4956. }; // standard Material serialization
  4957. data.uuid = this.uuid;
  4958. data.type = this.type;
  4959. if (this.name !== '') data.name = this.name;
  4960. if (this.color && this.color.isColor) data.color = this.color.getHex();
  4961. if (this.roughness !== undefined) data.roughness = this.roughness;
  4962. if (this.metalness !== undefined) data.metalness = this.metalness;
  4963. if (this.sheen !== undefined) data.sheen = this.sheen;
  4964. if (this.sheenColor && this.sheenColor.isColor) data.sheenColor = this.sheenColor.getHex();
  4965. if (this.sheenRoughness !== undefined) data.sheenRoughness = this.sheenRoughness;
  4966. if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
  4967. if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
  4968. if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
  4969. if (this.specularIntensity !== undefined) data.specularIntensity = this.specularIntensity;
  4970. if (this.specularColor && this.specularColor.isColor) data.specularColor = this.specularColor.getHex();
  4971. if (this.shininess !== undefined) data.shininess = this.shininess;
  4972. if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;
  4973. if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness;
  4974. if (this.clearcoatMap && this.clearcoatMap.isTexture) {
  4975. data.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid;
  4976. }
  4977. if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) {
  4978. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid;
  4979. }
  4980. if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
  4981. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;
  4982. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  4983. }
  4984. if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid;
  4985. if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid;
  4986. if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid;
  4987. if (this.lightMap && this.lightMap.isTexture) {
  4988. data.lightMap = this.lightMap.toJSON(meta).uuid;
  4989. data.lightMapIntensity = this.lightMapIntensity;
  4990. }
  4991. if (this.aoMap && this.aoMap.isTexture) {
  4992. data.aoMap = this.aoMap.toJSON(meta).uuid;
  4993. data.aoMapIntensity = this.aoMapIntensity;
  4994. }
  4995. if (this.bumpMap && this.bumpMap.isTexture) {
  4996. data.bumpMap = this.bumpMap.toJSON(meta).uuid;
  4997. data.bumpScale = this.bumpScale;
  4998. }
  4999. if (this.normalMap && this.normalMap.isTexture) {
  5000. data.normalMap = this.normalMap.toJSON(meta).uuid;
  5001. data.normalMapType = this.normalMapType;
  5002. data.normalScale = this.normalScale.toArray();
  5003. }
  5004. if (this.displacementMap && this.displacementMap.isTexture) {
  5005. data.displacementMap = this.displacementMap.toJSON(meta).uuid;
  5006. data.displacementScale = this.displacementScale;
  5007. data.displacementBias = this.displacementBias;
  5008. }
  5009. if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;
  5010. if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;
  5011. if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;
  5012. if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid;
  5013. if (this.specularIntensityMap && this.specularIntensityMap.isTexture) data.specularIntensityMap = this.specularIntensityMap.toJSON(meta).uuid;
  5014. if (this.specularColorMap && this.specularColorMap.isTexture) data.specularColorMap = this.specularColorMap.toJSON(meta).uuid;
  5015. if (this.envMap && this.envMap.isTexture) {
  5016. data.envMap = this.envMap.toJSON(meta).uuid;
  5017. if (this.combine !== undefined) data.combine = this.combine;
  5018. }
  5019. if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
  5020. if (this.reflectivity !== undefined) data.reflectivity = this.reflectivity;
  5021. if (this.refractionRatio !== undefined) data.refractionRatio = this.refractionRatio;
  5022. if (this.gradientMap && this.gradientMap.isTexture) {
  5023. data.gradientMap = this.gradientMap.toJSON(meta).uuid;
  5024. }
  5025. if (this.transmission !== undefined) data.transmission = this.transmission;
  5026. if (this.transmissionMap && this.transmissionMap.isTexture) data.transmissionMap = this.transmissionMap.toJSON(meta).uuid;
  5027. if (this.thickness !== undefined) data.thickness = this.thickness;
  5028. if (this.thicknessMap && this.thicknessMap.isTexture) data.thicknessMap = this.thicknessMap.toJSON(meta).uuid;
  5029. if (this.attenuationDistance !== undefined) data.attenuationDistance = this.attenuationDistance;
  5030. if (this.attenuationColor !== undefined) data.attenuationColor = this.attenuationColor.getHex();
  5031. if (this.size !== undefined) data.size = this.size;
  5032. if (this.shadowSide !== null) data.shadowSide = this.shadowSide;
  5033. if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
  5034. if (this.blending !== NormalBlending) data.blending = this.blending;
  5035. if (this.side !== FrontSide) data.side = this.side;
  5036. if (this.vertexColors) data.vertexColors = true;
  5037. if (this.opacity < 1) data.opacity = this.opacity;
  5038. if (this.format !== RGBAFormat) data.format = this.format;
  5039. if (this.transparent === true) data.transparent = this.transparent;
  5040. data.depthFunc = this.depthFunc;
  5041. data.depthTest = this.depthTest;
  5042. data.depthWrite = this.depthWrite;
  5043. data.colorWrite = this.colorWrite;
  5044. data.stencilWrite = this.stencilWrite;
  5045. data.stencilWriteMask = this.stencilWriteMask;
  5046. data.stencilFunc = this.stencilFunc;
  5047. data.stencilRef = this.stencilRef;
  5048. data.stencilFuncMask = this.stencilFuncMask;
  5049. data.stencilFail = this.stencilFail;
  5050. data.stencilZFail = this.stencilZFail;
  5051. data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial)
  5052. if (this.rotation && this.rotation !== 0) data.rotation = this.rotation;
  5053. if (this.polygonOffset === true) data.polygonOffset = true;
  5054. if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5055. if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5056. if (this.linewidth && this.linewidth !== 1) data.linewidth = this.linewidth;
  5057. if (this.dashSize !== undefined) data.dashSize = this.dashSize;
  5058. if (this.gapSize !== undefined) data.gapSize = this.gapSize;
  5059. if (this.scale !== undefined) data.scale = this.scale;
  5060. if (this.dithering === true) data.dithering = true;
  5061. if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
  5062. if (this.alphaToCoverage === true) data.alphaToCoverage = this.alphaToCoverage;
  5063. if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
  5064. if (this.wireframe === true) data.wireframe = this.wireframe;
  5065. if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
  5066. if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;
  5067. if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;
  5068. if (this.flatShading === true) data.flatShading = this.flatShading;
  5069. if (this.visible === false) data.visible = false;
  5070. if (this.toneMapped === false) data.toneMapped = false;
  5071. if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData; // TODO: Copied from Object3D.toJSON
  5072. function extractFromCache(cache) {
  5073. const values = [];
  5074. for (const key in cache) {
  5075. const data = cache[key];
  5076. delete data.metadata;
  5077. values.push(data);
  5078. }
  5079. return values;
  5080. }
  5081. if (isRoot) {
  5082. const textures = extractFromCache(meta.textures);
  5083. const images = extractFromCache(meta.images);
  5084. if (textures.length > 0) data.textures = textures;
  5085. if (images.length > 0) data.images = images;
  5086. }
  5087. return data;
  5088. }
  5089. clone() {
  5090. return new this.constructor().copy(this);
  5091. }
  5092. copy(source) {
  5093. this.name = source.name;
  5094. this.fog = source.fog;
  5095. this.blending = source.blending;
  5096. this.side = source.side;
  5097. this.vertexColors = source.vertexColors;
  5098. this.opacity = source.opacity;
  5099. this.format = source.format;
  5100. this.transparent = source.transparent;
  5101. this.blendSrc = source.blendSrc;
  5102. this.blendDst = source.blendDst;
  5103. this.blendEquation = source.blendEquation;
  5104. this.blendSrcAlpha = source.blendSrcAlpha;
  5105. this.blendDstAlpha = source.blendDstAlpha;
  5106. this.blendEquationAlpha = source.blendEquationAlpha;
  5107. this.depthFunc = source.depthFunc;
  5108. this.depthTest = source.depthTest;
  5109. this.depthWrite = source.depthWrite;
  5110. this.stencilWriteMask = source.stencilWriteMask;
  5111. this.stencilFunc = source.stencilFunc;
  5112. this.stencilRef = source.stencilRef;
  5113. this.stencilFuncMask = source.stencilFuncMask;
  5114. this.stencilFail = source.stencilFail;
  5115. this.stencilZFail = source.stencilZFail;
  5116. this.stencilZPass = source.stencilZPass;
  5117. this.stencilWrite = source.stencilWrite;
  5118. const srcPlanes = source.clippingPlanes;
  5119. let dstPlanes = null;
  5120. if (srcPlanes !== null) {
  5121. const n = srcPlanes.length;
  5122. dstPlanes = new Array(n);
  5123. for (let i = 0; i !== n; ++i) {
  5124. dstPlanes[i] = srcPlanes[i].clone();
  5125. }
  5126. }
  5127. this.clippingPlanes = dstPlanes;
  5128. this.clipIntersection = source.clipIntersection;
  5129. this.clipShadows = source.clipShadows;
  5130. this.shadowSide = source.shadowSide;
  5131. this.colorWrite = source.colorWrite;
  5132. this.precision = source.precision;
  5133. this.polygonOffset = source.polygonOffset;
  5134. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5135. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5136. this.dithering = source.dithering;
  5137. this.alphaTest = source.alphaTest;
  5138. this.alphaToCoverage = source.alphaToCoverage;
  5139. this.premultipliedAlpha = source.premultipliedAlpha;
  5140. this.visible = source.visible;
  5141. this.toneMapped = source.toneMapped;
  5142. this.userData = JSON.parse(JSON.stringify(source.userData));
  5143. return this;
  5144. }
  5145. dispose() {
  5146. this.dispatchEvent({
  5147. type: 'dispose'
  5148. });
  5149. }
  5150. set needsUpdate(value) {
  5151. if (value === true) this.version++;
  5152. }
  5153. }
  5154. Material.prototype.isMaterial = true;
  5155. const _colorKeywords = {
  5156. 'aliceblue': 0xF0F8FF,
  5157. 'antiquewhite': 0xFAEBD7,
  5158. 'aqua': 0x00FFFF,
  5159. 'aquamarine': 0x7FFFD4,
  5160. 'azure': 0xF0FFFF,
  5161. 'beige': 0xF5F5DC,
  5162. 'bisque': 0xFFE4C4,
  5163. 'black': 0x000000,
  5164. 'blanchedalmond': 0xFFEBCD,
  5165. 'blue': 0x0000FF,
  5166. 'blueviolet': 0x8A2BE2,
  5167. 'brown': 0xA52A2A,
  5168. 'burlywood': 0xDEB887,
  5169. 'cadetblue': 0x5F9EA0,
  5170. 'chartreuse': 0x7FFF00,
  5171. 'chocolate': 0xD2691E,
  5172. 'coral': 0xFF7F50,
  5173. 'cornflowerblue': 0x6495ED,
  5174. 'cornsilk': 0xFFF8DC,
  5175. 'crimson': 0xDC143C,
  5176. 'cyan': 0x00FFFF,
  5177. 'darkblue': 0x00008B,
  5178. 'darkcyan': 0x008B8B,
  5179. 'darkgoldenrod': 0xB8860B,
  5180. 'darkgray': 0xA9A9A9,
  5181. 'darkgreen': 0x006400,
  5182. 'darkgrey': 0xA9A9A9,
  5183. 'darkkhaki': 0xBDB76B,
  5184. 'darkmagenta': 0x8B008B,
  5185. 'darkolivegreen': 0x556B2F,
  5186. 'darkorange': 0xFF8C00,
  5187. 'darkorchid': 0x9932CC,
  5188. 'darkred': 0x8B0000,
  5189. 'darksalmon': 0xE9967A,
  5190. 'darkseagreen': 0x8FBC8F,
  5191. 'darkslateblue': 0x483D8B,
  5192. 'darkslategray': 0x2F4F4F,
  5193. 'darkslategrey': 0x2F4F4F,
  5194. 'darkturquoise': 0x00CED1,
  5195. 'darkviolet': 0x9400D3,
  5196. 'deeppink': 0xFF1493,
  5197. 'deepskyblue': 0x00BFFF,
  5198. 'dimgray': 0x696969,
  5199. 'dimgrey': 0x696969,
  5200. 'dodgerblue': 0x1E90FF,
  5201. 'firebrick': 0xB22222,
  5202. 'floralwhite': 0xFFFAF0,
  5203. 'forestgreen': 0x228B22,
  5204. 'fuchsia': 0xFF00FF,
  5205. 'gainsboro': 0xDCDCDC,
  5206. 'ghostwhite': 0xF8F8FF,
  5207. 'gold': 0xFFD700,
  5208. 'goldenrod': 0xDAA520,
  5209. 'gray': 0x808080,
  5210. 'green': 0x008000,
  5211. 'greenyellow': 0xADFF2F,
  5212. 'grey': 0x808080,
  5213. 'honeydew': 0xF0FFF0,
  5214. 'hotpink': 0xFF69B4,
  5215. 'indianred': 0xCD5C5C,
  5216. 'indigo': 0x4B0082,
  5217. 'ivory': 0xFFFFF0,
  5218. 'khaki': 0xF0E68C,
  5219. 'lavender': 0xE6E6FA,
  5220. 'lavenderblush': 0xFFF0F5,
  5221. 'lawngreen': 0x7CFC00,
  5222. 'lemonchiffon': 0xFFFACD,
  5223. 'lightblue': 0xADD8E6,
  5224. 'lightcoral': 0xF08080,
  5225. 'lightcyan': 0xE0FFFF,
  5226. 'lightgoldenrodyellow': 0xFAFAD2,
  5227. 'lightgray': 0xD3D3D3,
  5228. 'lightgreen': 0x90EE90,
  5229. 'lightgrey': 0xD3D3D3,
  5230. 'lightpink': 0xFFB6C1,
  5231. 'lightsalmon': 0xFFA07A,
  5232. 'lightseagreen': 0x20B2AA,
  5233. 'lightskyblue': 0x87CEFA,
  5234. 'lightslategray': 0x778899,
  5235. 'lightslategrey': 0x778899,
  5236. 'lightsteelblue': 0xB0C4DE,
  5237. 'lightyellow': 0xFFFFE0,
  5238. 'lime': 0x00FF00,
  5239. 'limegreen': 0x32CD32,
  5240. 'linen': 0xFAF0E6,
  5241. 'magenta': 0xFF00FF,
  5242. 'maroon': 0x800000,
  5243. 'mediumaquamarine': 0x66CDAA,
  5244. 'mediumblue': 0x0000CD,
  5245. 'mediumorchid': 0xBA55D3,
  5246. 'mediumpurple': 0x9370DB,
  5247. 'mediumseagreen': 0x3CB371,
  5248. 'mediumslateblue': 0x7B68EE,
  5249. 'mediumspringgreen': 0x00FA9A,
  5250. 'mediumturquoise': 0x48D1CC,
  5251. 'mediumvioletred': 0xC71585,
  5252. 'midnightblue': 0x191970,
  5253. 'mintcream': 0xF5FFFA,
  5254. 'mistyrose': 0xFFE4E1,
  5255. 'moccasin': 0xFFE4B5,
  5256. 'navajowhite': 0xFFDEAD,
  5257. 'navy': 0x000080,
  5258. 'oldlace': 0xFDF5E6,
  5259. 'olive': 0x808000,
  5260. 'olivedrab': 0x6B8E23,
  5261. 'orange': 0xFFA500,
  5262. 'orangered': 0xFF4500,
  5263. 'orchid': 0xDA70D6,
  5264. 'palegoldenrod': 0xEEE8AA,
  5265. 'palegreen': 0x98FB98,
  5266. 'paleturquoise': 0xAFEEEE,
  5267. 'palevioletred': 0xDB7093,
  5268. 'papayawhip': 0xFFEFD5,
  5269. 'peachpuff': 0xFFDAB9,
  5270. 'peru': 0xCD853F,
  5271. 'pink': 0xFFC0CB,
  5272. 'plum': 0xDDA0DD,
  5273. 'powderblue': 0xB0E0E6,
  5274. 'purple': 0x800080,
  5275. 'rebeccapurple': 0x663399,
  5276. 'red': 0xFF0000,
  5277. 'rosybrown': 0xBC8F8F,
  5278. 'royalblue': 0x4169E1,
  5279. 'saddlebrown': 0x8B4513,
  5280. 'salmon': 0xFA8072,
  5281. 'sandybrown': 0xF4A460,
  5282. 'seagreen': 0x2E8B57,
  5283. 'seashell': 0xFFF5EE,
  5284. 'sienna': 0xA0522D,
  5285. 'silver': 0xC0C0C0,
  5286. 'skyblue': 0x87CEEB,
  5287. 'slateblue': 0x6A5ACD,
  5288. 'slategray': 0x708090,
  5289. 'slategrey': 0x708090,
  5290. 'snow': 0xFFFAFA,
  5291. 'springgreen': 0x00FF7F,
  5292. 'steelblue': 0x4682B4,
  5293. 'tan': 0xD2B48C,
  5294. 'teal': 0x008080,
  5295. 'thistle': 0xD8BFD8,
  5296. 'tomato': 0xFF6347,
  5297. 'turquoise': 0x40E0D0,
  5298. 'violet': 0xEE82EE,
  5299. 'wheat': 0xF5DEB3,
  5300. 'white': 0xFFFFFF,
  5301. 'whitesmoke': 0xF5F5F5,
  5302. 'yellow': 0xFFFF00,
  5303. 'yellowgreen': 0x9ACD32
  5304. };
  5305. const _hslA = {
  5306. h: 0,
  5307. s: 0,
  5308. l: 0
  5309. };
  5310. const _hslB = {
  5311. h: 0,
  5312. s: 0,
  5313. l: 0
  5314. };
  5315. function hue2rgb(p, q, t) {
  5316. if (t < 0) t += 1;
  5317. if (t > 1) t -= 1;
  5318. if (t < 1 / 6) return p + (q - p) * 6 * t;
  5319. if (t < 1 / 2) return q;
  5320. if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t);
  5321. return p;
  5322. }
  5323. function SRGBToLinear(c) {
  5324. return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
  5325. }
  5326. function LinearToSRGB(c) {
  5327. return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
  5328. }
  5329. class Color {
  5330. constructor(r, g, b) {
  5331. if (g === undefined && b === undefined) {
  5332. // r is THREE.Color, hex or string
  5333. return this.set(r);
  5334. }
  5335. return this.setRGB(r, g, b);
  5336. }
  5337. set(value) {
  5338. if (value && value.isColor) {
  5339. this.copy(value);
  5340. } else if (typeof value === 'number') {
  5341. this.setHex(value);
  5342. } else if (typeof value === 'string') {
  5343. this.setStyle(value);
  5344. }
  5345. return this;
  5346. }
  5347. setScalar(scalar) {
  5348. this.r = scalar;
  5349. this.g = scalar;
  5350. this.b = scalar;
  5351. return this;
  5352. }
  5353. setHex(hex) {
  5354. hex = Math.floor(hex);
  5355. this.r = (hex >> 16 & 255) / 255;
  5356. this.g = (hex >> 8 & 255) / 255;
  5357. this.b = (hex & 255) / 255;
  5358. return this;
  5359. }
  5360. setRGB(r, g, b) {
  5361. this.r = r;
  5362. this.g = g;
  5363. this.b = b;
  5364. return this;
  5365. }
  5366. setHSL(h, s, l) {
  5367. // h,s,l ranges are in 0.0 - 1.0
  5368. h = euclideanModulo(h, 1);
  5369. s = clamp(s, 0, 1);
  5370. l = clamp(l, 0, 1);
  5371. if (s === 0) {
  5372. this.r = this.g = this.b = l;
  5373. } else {
  5374. const p = l <= 0.5 ? l * (1 + s) : l + s - l * s;
  5375. const q = 2 * l - p;
  5376. this.r = hue2rgb(q, p, h + 1 / 3);
  5377. this.g = hue2rgb(q, p, h);
  5378. this.b = hue2rgb(q, p, h - 1 / 3);
  5379. }
  5380. return this;
  5381. }
  5382. setStyle(style) {
  5383. function handleAlpha(string) {
  5384. if (string === undefined) return;
  5385. if (parseFloat(string) < 1) {
  5386. console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
  5387. }
  5388. }
  5389. let m;
  5390. if (m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec(style)) {
  5391. // rgb / hsl
  5392. let color;
  5393. const name = m[1];
  5394. const components = m[2];
  5395. switch (name) {
  5396. case 'rgb':
  5397. case 'rgba':
  5398. if (color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  5399. // rgb(255,0,0) rgba(255,0,0,0.5)
  5400. this.r = Math.min(255, parseInt(color[1], 10)) / 255;
  5401. this.g = Math.min(255, parseInt(color[2], 10)) / 255;
  5402. this.b = Math.min(255, parseInt(color[3], 10)) / 255;
  5403. handleAlpha(color[4]);
  5404. return this;
  5405. }
  5406. if (color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  5407. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5408. this.r = Math.min(100, parseInt(color[1], 10)) / 100;
  5409. this.g = Math.min(100, parseInt(color[2], 10)) / 100;
  5410. this.b = Math.min(100, parseInt(color[3], 10)) / 100;
  5411. handleAlpha(color[4]);
  5412. return this;
  5413. }
  5414. break;
  5415. case 'hsl':
  5416. case 'hsla':
  5417. if (color = /^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  5418. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5419. const h = parseFloat(color[1]) / 360;
  5420. const s = parseInt(color[2], 10) / 100;
  5421. const l = parseInt(color[3], 10) / 100;
  5422. handleAlpha(color[4]);
  5423. return this.setHSL(h, s, l);
  5424. }
  5425. break;
  5426. }
  5427. } else if (m = /^\#([A-Fa-f\d]+)$/.exec(style)) {
  5428. // hex color
  5429. const hex = m[1];
  5430. const size = hex.length;
  5431. if (size === 3) {
  5432. // #ff0
  5433. this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
  5434. this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
  5435. this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
  5436. return this;
  5437. } else if (size === 6) {
  5438. // #ff0000
  5439. this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
  5440. this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
  5441. this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
  5442. return this;
  5443. }
  5444. }
  5445. if (style && style.length > 0) {
  5446. return this.setColorName(style);
  5447. }
  5448. return this;
  5449. }
  5450. setColorName(style) {
  5451. // color keywords
  5452. const hex = _colorKeywords[style.toLowerCase()];
  5453. if (hex !== undefined) {
  5454. // red
  5455. this.setHex(hex);
  5456. } else {
  5457. // unknown color
  5458. console.warn('THREE.Color: Unknown color ' + style);
  5459. }
  5460. return this;
  5461. }
  5462. clone() {
  5463. return new this.constructor(this.r, this.g, this.b);
  5464. }
  5465. copy(color) {
  5466. this.r = color.r;
  5467. this.g = color.g;
  5468. this.b = color.b;
  5469. return this;
  5470. }
  5471. copySRGBToLinear(color) {
  5472. this.r = SRGBToLinear(color.r);
  5473. this.g = SRGBToLinear(color.g);
  5474. this.b = SRGBToLinear(color.b);
  5475. return this;
  5476. }
  5477. copyLinearToSRGB(color) {
  5478. this.r = LinearToSRGB(color.r);
  5479. this.g = LinearToSRGB(color.g);
  5480. this.b = LinearToSRGB(color.b);
  5481. return this;
  5482. }
  5483. convertSRGBToLinear() {
  5484. this.copySRGBToLinear(this);
  5485. return this;
  5486. }
  5487. convertLinearToSRGB() {
  5488. this.copyLinearToSRGB(this);
  5489. return this;
  5490. }
  5491. getHex() {
  5492. return this.r * 255 << 16 ^ this.g * 255 << 8 ^ this.b * 255 << 0;
  5493. }
  5494. getHexString() {
  5495. return ('000000' + this.getHex().toString(16)).slice(-6);
  5496. }
  5497. getHSL(target) {
  5498. // h,s,l ranges are in 0.0 - 1.0
  5499. const r = this.r,
  5500. g = this.g,
  5501. b = this.b;
  5502. const max = Math.max(r, g, b);
  5503. const min = Math.min(r, g, b);
  5504. let hue, saturation;
  5505. const lightness = (min + max) / 2.0;
  5506. if (min === max) {
  5507. hue = 0;
  5508. saturation = 0;
  5509. } else {
  5510. const delta = max - min;
  5511. saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
  5512. switch (max) {
  5513. case r:
  5514. hue = (g - b) / delta + (g < b ? 6 : 0);
  5515. break;
  5516. case g:
  5517. hue = (b - r) / delta + 2;
  5518. break;
  5519. case b:
  5520. hue = (r - g) / delta + 4;
  5521. break;
  5522. }
  5523. hue /= 6;
  5524. }
  5525. target.h = hue;
  5526. target.s = saturation;
  5527. target.l = lightness;
  5528. return target;
  5529. }
  5530. getStyle() {
  5531. return 'rgb(' + (this.r * 255 | 0) + ',' + (this.g * 255 | 0) + ',' + (this.b * 255 | 0) + ')';
  5532. }
  5533. offsetHSL(h, s, l) {
  5534. this.getHSL(_hslA);
  5535. _hslA.h += h;
  5536. _hslA.s += s;
  5537. _hslA.l += l;
  5538. this.setHSL(_hslA.h, _hslA.s, _hslA.l);
  5539. return this;
  5540. }
  5541. add(color) {
  5542. this.r += color.r;
  5543. this.g += color.g;
  5544. this.b += color.b;
  5545. return this;
  5546. }
  5547. addColors(color1, color2) {
  5548. this.r = color1.r + color2.r;
  5549. this.g = color1.g + color2.g;
  5550. this.b = color1.b + color2.b;
  5551. return this;
  5552. }
  5553. addScalar(s) {
  5554. this.r += s;
  5555. this.g += s;
  5556. this.b += s;
  5557. return this;
  5558. }
  5559. sub(color) {
  5560. this.r = Math.max(0, this.r - color.r);
  5561. this.g = Math.max(0, this.g - color.g);
  5562. this.b = Math.max(0, this.b - color.b);
  5563. return this;
  5564. }
  5565. multiply(color) {
  5566. this.r *= color.r;
  5567. this.g *= color.g;
  5568. this.b *= color.b;
  5569. return this;
  5570. }
  5571. multiplyScalar(s) {
  5572. this.r *= s;
  5573. this.g *= s;
  5574. this.b *= s;
  5575. return this;
  5576. }
  5577. lerp(color, alpha) {
  5578. this.r += (color.r - this.r) * alpha;
  5579. this.g += (color.g - this.g) * alpha;
  5580. this.b += (color.b - this.b) * alpha;
  5581. return this;
  5582. }
  5583. lerpColors(color1, color2, alpha) {
  5584. this.r = color1.r + (color2.r - color1.r) * alpha;
  5585. this.g = color1.g + (color2.g - color1.g) * alpha;
  5586. this.b = color1.b + (color2.b - color1.b) * alpha;
  5587. return this;
  5588. }
  5589. lerpHSL(color, alpha) {
  5590. this.getHSL(_hslA);
  5591. color.getHSL(_hslB);
  5592. const h = lerp(_hslA.h, _hslB.h, alpha);
  5593. const s = lerp(_hslA.s, _hslB.s, alpha);
  5594. const l = lerp(_hslA.l, _hslB.l, alpha);
  5595. this.setHSL(h, s, l);
  5596. return this;
  5597. }
  5598. equals(c) {
  5599. return c.r === this.r && c.g === this.g && c.b === this.b;
  5600. }
  5601. fromArray(array, offset = 0) {
  5602. this.r = array[offset];
  5603. this.g = array[offset + 1];
  5604. this.b = array[offset + 2];
  5605. return this;
  5606. }
  5607. toArray(array = [], offset = 0) {
  5608. array[offset] = this.r;
  5609. array[offset + 1] = this.g;
  5610. array[offset + 2] = this.b;
  5611. return array;
  5612. }
  5613. fromBufferAttribute(attribute, index) {
  5614. this.r = attribute.getX(index);
  5615. this.g = attribute.getY(index);
  5616. this.b = attribute.getZ(index);
  5617. if (attribute.normalized === true) {
  5618. // assuming Uint8Array
  5619. this.r /= 255;
  5620. this.g /= 255;
  5621. this.b /= 255;
  5622. }
  5623. return this;
  5624. }
  5625. toJSON() {
  5626. return this.getHex();
  5627. }
  5628. }
  5629. Color.NAMES = _colorKeywords;
  5630. Color.prototype.isColor = true;
  5631. Color.prototype.r = 1;
  5632. Color.prototype.g = 1;
  5633. Color.prototype.b = 1;
  5634. /**
  5635. * parameters = {
  5636. * color: <hex>,
  5637. * opacity: <float>,
  5638. * map: new THREE.Texture( <Image> ),
  5639. *
  5640. * lightMap: new THREE.Texture( <Image> ),
  5641. * lightMapIntensity: <float>
  5642. *
  5643. * aoMap: new THREE.Texture( <Image> ),
  5644. * aoMapIntensity: <float>
  5645. *
  5646. * specularMap: new THREE.Texture( <Image> ),
  5647. *
  5648. * alphaMap: new THREE.Texture( <Image> ),
  5649. *
  5650. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  5651. * combine: THREE.Multiply,
  5652. * reflectivity: <float>,
  5653. * refractionRatio: <float>,
  5654. *
  5655. * depthTest: <bool>,
  5656. * depthWrite: <bool>,
  5657. *
  5658. * wireframe: <boolean>,
  5659. * wireframeLinewidth: <float>,
  5660. * }
  5661. */
  5662. class MeshBasicMaterial extends Material {
  5663. constructor(parameters) {
  5664. super();
  5665. this.type = 'MeshBasicMaterial';
  5666. this.color = new Color(0xffffff); // emissive
  5667. this.map = null;
  5668. this.lightMap = null;
  5669. this.lightMapIntensity = 1.0;
  5670. this.aoMap = null;
  5671. this.aoMapIntensity = 1.0;
  5672. this.specularMap = null;
  5673. this.alphaMap = null;
  5674. this.envMap = null;
  5675. this.combine = MultiplyOperation;
  5676. this.reflectivity = 1;
  5677. this.refractionRatio = 0.98;
  5678. this.wireframe = false;
  5679. this.wireframeLinewidth = 1;
  5680. this.wireframeLinecap = 'round';
  5681. this.wireframeLinejoin = 'round';
  5682. this.setValues(parameters);
  5683. }
  5684. copy(source) {
  5685. super.copy(source);
  5686. this.color.copy(source.color);
  5687. this.map = source.map;
  5688. this.lightMap = source.lightMap;
  5689. this.lightMapIntensity = source.lightMapIntensity;
  5690. this.aoMap = source.aoMap;
  5691. this.aoMapIntensity = source.aoMapIntensity;
  5692. this.specularMap = source.specularMap;
  5693. this.alphaMap = source.alphaMap;
  5694. this.envMap = source.envMap;
  5695. this.combine = source.combine;
  5696. this.reflectivity = source.reflectivity;
  5697. this.refractionRatio = source.refractionRatio;
  5698. this.wireframe = source.wireframe;
  5699. this.wireframeLinewidth = source.wireframeLinewidth;
  5700. this.wireframeLinecap = source.wireframeLinecap;
  5701. this.wireframeLinejoin = source.wireframeLinejoin;
  5702. return this;
  5703. }
  5704. }
  5705. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  5706. const _vector$9 = /*@__PURE__*/new Vector3();
  5707. const _vector2$1 = /*@__PURE__*/new Vector2();
  5708. class BufferAttribute {
  5709. constructor(array, itemSize, normalized) {
  5710. if (Array.isArray(array)) {
  5711. throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
  5712. }
  5713. this.name = '';
  5714. this.array = array;
  5715. this.itemSize = itemSize;
  5716. this.count = array !== undefined ? array.length / itemSize : 0;
  5717. this.normalized = normalized === true;
  5718. this.usage = StaticDrawUsage;
  5719. this.updateRange = {
  5720. offset: 0,
  5721. count: -1
  5722. };
  5723. this.version = 0;
  5724. }
  5725. onUploadCallback() {}
  5726. set needsUpdate(value) {
  5727. if (value === true) this.version++;
  5728. }
  5729. setUsage(value) {
  5730. this.usage = value;
  5731. return this;
  5732. }
  5733. copy(source) {
  5734. this.name = source.name;
  5735. this.array = new source.array.constructor(source.array);
  5736. this.itemSize = source.itemSize;
  5737. this.count = source.count;
  5738. this.normalized = source.normalized;
  5739. this.usage = source.usage;
  5740. return this;
  5741. }
  5742. copyAt(index1, attribute, index2) {
  5743. index1 *= this.itemSize;
  5744. index2 *= attribute.itemSize;
  5745. for (let i = 0, l = this.itemSize; i < l; i++) {
  5746. this.array[index1 + i] = attribute.array[index2 + i];
  5747. }
  5748. return this;
  5749. }
  5750. copyArray(array) {
  5751. this.array.set(array);
  5752. return this;
  5753. }
  5754. copyColorsArray(colors) {
  5755. const array = this.array;
  5756. let offset = 0;
  5757. for (let i = 0, l = colors.length; i < l; i++) {
  5758. let color = colors[i];
  5759. if (color === undefined) {
  5760. console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined', i);
  5761. color = new Color();
  5762. }
  5763. array[offset++] = color.r;
  5764. array[offset++] = color.g;
  5765. array[offset++] = color.b;
  5766. }
  5767. return this;
  5768. }
  5769. copyVector2sArray(vectors) {
  5770. const array = this.array;
  5771. let offset = 0;
  5772. for (let i = 0, l = vectors.length; i < l; i++) {
  5773. let vector = vectors[i];
  5774. if (vector === undefined) {
  5775. console.warn('THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i);
  5776. vector = new Vector2();
  5777. }
  5778. array[offset++] = vector.x;
  5779. array[offset++] = vector.y;
  5780. }
  5781. return this;
  5782. }
  5783. copyVector3sArray(vectors) {
  5784. const array = this.array;
  5785. let offset = 0;
  5786. for (let i = 0, l = vectors.length; i < l; i++) {
  5787. let vector = vectors[i];
  5788. if (vector === undefined) {
  5789. console.warn('THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i);
  5790. vector = new Vector3();
  5791. }
  5792. array[offset++] = vector.x;
  5793. array[offset++] = vector.y;
  5794. array[offset++] = vector.z;
  5795. }
  5796. return this;
  5797. }
  5798. copyVector4sArray(vectors) {
  5799. const array = this.array;
  5800. let offset = 0;
  5801. for (let i = 0, l = vectors.length; i < l; i++) {
  5802. let vector = vectors[i];
  5803. if (vector === undefined) {
  5804. console.warn('THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i);
  5805. vector = new Vector4();
  5806. }
  5807. array[offset++] = vector.x;
  5808. array[offset++] = vector.y;
  5809. array[offset++] = vector.z;
  5810. array[offset++] = vector.w;
  5811. }
  5812. return this;
  5813. }
  5814. applyMatrix3(m) {
  5815. if (this.itemSize === 2) {
  5816. for (let i = 0, l = this.count; i < l; i++) {
  5817. _vector2$1.fromBufferAttribute(this, i);
  5818. _vector2$1.applyMatrix3(m);
  5819. this.setXY(i, _vector2$1.x, _vector2$1.y);
  5820. }
  5821. } else if (this.itemSize === 3) {
  5822. for (let i = 0, l = this.count; i < l; i++) {
  5823. _vector$9.fromBufferAttribute(this, i);
  5824. _vector$9.applyMatrix3(m);
  5825. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5826. }
  5827. }
  5828. return this;
  5829. }
  5830. applyMatrix4(m) {
  5831. for (let i = 0, l = this.count; i < l; i++) {
  5832. _vector$9.x = this.getX(i);
  5833. _vector$9.y = this.getY(i);
  5834. _vector$9.z = this.getZ(i);
  5835. _vector$9.applyMatrix4(m);
  5836. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5837. }
  5838. return this;
  5839. }
  5840. applyNormalMatrix(m) {
  5841. for (let i = 0, l = this.count; i < l; i++) {
  5842. _vector$9.x = this.getX(i);
  5843. _vector$9.y = this.getY(i);
  5844. _vector$9.z = this.getZ(i);
  5845. _vector$9.applyNormalMatrix(m);
  5846. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5847. }
  5848. return this;
  5849. }
  5850. transformDirection(m) {
  5851. for (let i = 0, l = this.count; i < l; i++) {
  5852. _vector$9.x = this.getX(i);
  5853. _vector$9.y = this.getY(i);
  5854. _vector$9.z = this.getZ(i);
  5855. _vector$9.transformDirection(m);
  5856. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5857. }
  5858. return this;
  5859. }
  5860. set(value, offset = 0) {
  5861. this.array.set(value, offset);
  5862. return this;
  5863. }
  5864. getX(index) {
  5865. return this.array[index * this.itemSize];
  5866. }
  5867. setX(index, x) {
  5868. this.array[index * this.itemSize] = x;
  5869. return this;
  5870. }
  5871. getY(index) {
  5872. return this.array[index * this.itemSize + 1];
  5873. }
  5874. setY(index, y) {
  5875. this.array[index * this.itemSize + 1] = y;
  5876. return this;
  5877. }
  5878. getZ(index) {
  5879. return this.array[index * this.itemSize + 2];
  5880. }
  5881. setZ(index, z) {
  5882. this.array[index * this.itemSize + 2] = z;
  5883. return this;
  5884. }
  5885. getW(index) {
  5886. return this.array[index * this.itemSize + 3];
  5887. }
  5888. setW(index, w) {
  5889. this.array[index * this.itemSize + 3] = w;
  5890. return this;
  5891. }
  5892. setXY(index, x, y) {
  5893. index *= this.itemSize;
  5894. this.array[index + 0] = x;
  5895. this.array[index + 1] = y;
  5896. return this;
  5897. }
  5898. setXYZ(index, x, y, z) {
  5899. index *= this.itemSize;
  5900. this.array[index + 0] = x;
  5901. this.array[index + 1] = y;
  5902. this.array[index + 2] = z;
  5903. return this;
  5904. }
  5905. setXYZW(index, x, y, z, w) {
  5906. index *= this.itemSize;
  5907. this.array[index + 0] = x;
  5908. this.array[index + 1] = y;
  5909. this.array[index + 2] = z;
  5910. this.array[index + 3] = w;
  5911. return this;
  5912. }
  5913. onUpload(callback) {
  5914. this.onUploadCallback = callback;
  5915. return this;
  5916. }
  5917. clone() {
  5918. return new this.constructor(this.array, this.itemSize).copy(this);
  5919. }
  5920. toJSON() {
  5921. const data = {
  5922. itemSize: this.itemSize,
  5923. type: this.array.constructor.name,
  5924. array: Array.prototype.slice.call(this.array),
  5925. normalized: this.normalized
  5926. };
  5927. if (this.name !== '') data.name = this.name;
  5928. if (this.usage !== StaticDrawUsage) data.usage = this.usage;
  5929. if (this.updateRange.offset !== 0 || this.updateRange.count !== -1) data.updateRange = this.updateRange;
  5930. return data;
  5931. }
  5932. }
  5933. BufferAttribute.prototype.isBufferAttribute = true; //
  5934. class Int8BufferAttribute extends BufferAttribute {
  5935. constructor(array, itemSize, normalized) {
  5936. super(new Int8Array(array), itemSize, normalized);
  5937. }
  5938. }
  5939. class Uint8BufferAttribute extends BufferAttribute {
  5940. constructor(array, itemSize, normalized) {
  5941. super(new Uint8Array(array), itemSize, normalized);
  5942. }
  5943. }
  5944. class Uint8ClampedBufferAttribute extends BufferAttribute {
  5945. constructor(array, itemSize, normalized) {
  5946. super(new Uint8ClampedArray(array), itemSize, normalized);
  5947. }
  5948. }
  5949. class Int16BufferAttribute extends BufferAttribute {
  5950. constructor(array, itemSize, normalized) {
  5951. super(new Int16Array(array), itemSize, normalized);
  5952. }
  5953. }
  5954. class Uint16BufferAttribute extends BufferAttribute {
  5955. constructor(array, itemSize, normalized) {
  5956. super(new Uint16Array(array), itemSize, normalized);
  5957. }
  5958. }
  5959. class Int32BufferAttribute extends BufferAttribute {
  5960. constructor(array, itemSize, normalized) {
  5961. super(new Int32Array(array), itemSize, normalized);
  5962. }
  5963. }
  5964. class Uint32BufferAttribute extends BufferAttribute {
  5965. constructor(array, itemSize, normalized) {
  5966. super(new Uint32Array(array), itemSize, normalized);
  5967. }
  5968. }
  5969. class Float16BufferAttribute extends BufferAttribute {
  5970. constructor(array, itemSize, normalized) {
  5971. super(new Uint16Array(array), itemSize, normalized);
  5972. }
  5973. }
  5974. Float16BufferAttribute.prototype.isFloat16BufferAttribute = true;
  5975. class Float32BufferAttribute extends BufferAttribute {
  5976. constructor(array, itemSize, normalized) {
  5977. super(new Float32Array(array), itemSize, normalized);
  5978. }
  5979. }
  5980. class Float64BufferAttribute extends BufferAttribute {
  5981. constructor(array, itemSize, normalized) {
  5982. super(new Float64Array(array), itemSize, normalized);
  5983. }
  5984. } //
  5985. let _id$1 = 0;
  5986. const _m1 = /*@__PURE__*/new Matrix4();
  5987. const _obj = /*@__PURE__*/new Object3D();
  5988. const _offset = /*@__PURE__*/new Vector3();
  5989. const _box$1 = /*@__PURE__*/new Box3();
  5990. const _boxMorphTargets = /*@__PURE__*/new Box3();
  5991. const _vector$8 = /*@__PURE__*/new Vector3();
  5992. class BufferGeometry extends EventDispatcher {
  5993. constructor() {
  5994. super();
  5995. Object.defineProperty(this, 'id', {
  5996. value: _id$1++
  5997. });
  5998. this.uuid = generateUUID();
  5999. this.name = '';
  6000. this.type = 'BufferGeometry';
  6001. this.index = null;
  6002. this.attributes = {};
  6003. this.morphAttributes = {};
  6004. this.morphTargetsRelative = false;
  6005. this.groups = [];
  6006. this.boundingBox = null;
  6007. this.boundingSphere = null;
  6008. this.drawRange = {
  6009. start: 0,
  6010. count: Infinity
  6011. };
  6012. this.userData = {};
  6013. }
  6014. getIndex() {
  6015. return this.index;
  6016. }
  6017. setIndex(index) {
  6018. if (Array.isArray(index)) {
  6019. this.index = new (arrayMax(index) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
  6020. } else {
  6021. this.index = index;
  6022. }
  6023. return this;
  6024. }
  6025. getAttribute(name) {
  6026. return this.attributes[name];
  6027. }
  6028. setAttribute(name, attribute) {
  6029. this.attributes[name] = attribute;
  6030. return this;
  6031. }
  6032. deleteAttribute(name) {
  6033. delete this.attributes[name];
  6034. return this;
  6035. }
  6036. hasAttribute(name) {
  6037. return this.attributes[name] !== undefined;
  6038. }
  6039. addGroup(start, count, materialIndex = 0) {
  6040. this.groups.push({
  6041. start: start,
  6042. count: count,
  6043. materialIndex: materialIndex
  6044. });
  6045. }
  6046. clearGroups() {
  6047. this.groups = [];
  6048. }
  6049. setDrawRange(start, count) {
  6050. this.drawRange.start = start;
  6051. this.drawRange.count = count;
  6052. }
  6053. applyMatrix4(matrix) {
  6054. const position = this.attributes.position;
  6055. if (position !== undefined) {
  6056. position.applyMatrix4(matrix);
  6057. position.needsUpdate = true;
  6058. }
  6059. const normal = this.attributes.normal;
  6060. if (normal !== undefined) {
  6061. const normalMatrix = new Matrix3().getNormalMatrix(matrix);
  6062. normal.applyNormalMatrix(normalMatrix);
  6063. normal.needsUpdate = true;
  6064. }
  6065. const tangent = this.attributes.tangent;
  6066. if (tangent !== undefined) {
  6067. tangent.transformDirection(matrix);
  6068. tangent.needsUpdate = true;
  6069. }
  6070. if (this.boundingBox !== null) {
  6071. this.computeBoundingBox();
  6072. }
  6073. if (this.boundingSphere !== null) {
  6074. this.computeBoundingSphere();
  6075. }
  6076. return this;
  6077. }
  6078. applyQuaternion(q) {
  6079. _m1.makeRotationFromQuaternion(q);
  6080. this.applyMatrix4(_m1);
  6081. return this;
  6082. }
  6083. rotateX(angle) {
  6084. // rotate geometry around world x-axis
  6085. _m1.makeRotationX(angle);
  6086. this.applyMatrix4(_m1);
  6087. return this;
  6088. }
  6089. rotateY(angle) {
  6090. // rotate geometry around world y-axis
  6091. _m1.makeRotationY(angle);
  6092. this.applyMatrix4(_m1);
  6093. return this;
  6094. }
  6095. rotateZ(angle) {
  6096. // rotate geometry around world z-axis
  6097. _m1.makeRotationZ(angle);
  6098. this.applyMatrix4(_m1);
  6099. return this;
  6100. }
  6101. translate(x, y, z) {
  6102. // translate geometry
  6103. _m1.makeTranslation(x, y, z);
  6104. this.applyMatrix4(_m1);
  6105. return this;
  6106. }
  6107. scale(x, y, z) {
  6108. // scale geometry
  6109. _m1.makeScale(x, y, z);
  6110. this.applyMatrix4(_m1);
  6111. return this;
  6112. }
  6113. lookAt(vector) {
  6114. _obj.lookAt(vector);
  6115. _obj.updateMatrix();
  6116. this.applyMatrix4(_obj.matrix);
  6117. return this;
  6118. }
  6119. center() {
  6120. this.computeBoundingBox();
  6121. this.boundingBox.getCenter(_offset).negate();
  6122. this.translate(_offset.x, _offset.y, _offset.z);
  6123. return this;
  6124. }
  6125. setFromPoints(points) {
  6126. const position = [];
  6127. for (let i = 0, l = points.length; i < l; i++) {
  6128. const point = points[i];
  6129. position.push(point.x, point.y, point.z || 0);
  6130. }
  6131. this.setAttribute('position', new Float32BufferAttribute(position, 3));
  6132. return this;
  6133. }
  6134. computeBoundingBox() {
  6135. if (this.boundingBox === null) {
  6136. this.boundingBox = new Box3();
  6137. }
  6138. const position = this.attributes.position;
  6139. const morphAttributesPosition = this.morphAttributes.position;
  6140. if (position && position.isGLBufferAttribute) {
  6141. console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this);
  6142. this.boundingBox.set(new Vector3(-Infinity, -Infinity, -Infinity), new Vector3(+Infinity, +Infinity, +Infinity));
  6143. return;
  6144. }
  6145. if (position !== undefined) {
  6146. this.boundingBox.setFromBufferAttribute(position); // process morph attributes if present
  6147. if (morphAttributesPosition) {
  6148. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6149. const morphAttribute = morphAttributesPosition[i];
  6150. _box$1.setFromBufferAttribute(morphAttribute);
  6151. if (this.morphTargetsRelative) {
  6152. _vector$8.addVectors(this.boundingBox.min, _box$1.min);
  6153. this.boundingBox.expandByPoint(_vector$8);
  6154. _vector$8.addVectors(this.boundingBox.max, _box$1.max);
  6155. this.boundingBox.expandByPoint(_vector$8);
  6156. } else {
  6157. this.boundingBox.expandByPoint(_box$1.min);
  6158. this.boundingBox.expandByPoint(_box$1.max);
  6159. }
  6160. }
  6161. }
  6162. } else {
  6163. this.boundingBox.makeEmpty();
  6164. }
  6165. if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
  6166. console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  6167. }
  6168. }
  6169. computeBoundingSphere() {
  6170. if (this.boundingSphere === null) {
  6171. this.boundingSphere = new Sphere();
  6172. }
  6173. const position = this.attributes.position;
  6174. const morphAttributesPosition = this.morphAttributes.position;
  6175. if (position && position.isGLBufferAttribute) {
  6176. console.error('THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this);
  6177. this.boundingSphere.set(new Vector3(), Infinity);
  6178. return;
  6179. }
  6180. if (position) {
  6181. // first, find the center of the bounding sphere
  6182. const center = this.boundingSphere.center;
  6183. _box$1.setFromBufferAttribute(position); // process morph attributes if present
  6184. if (morphAttributesPosition) {
  6185. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6186. const morphAttribute = morphAttributesPosition[i];
  6187. _boxMorphTargets.setFromBufferAttribute(morphAttribute);
  6188. if (this.morphTargetsRelative) {
  6189. _vector$8.addVectors(_box$1.min, _boxMorphTargets.min);
  6190. _box$1.expandByPoint(_vector$8);
  6191. _vector$8.addVectors(_box$1.max, _boxMorphTargets.max);
  6192. _box$1.expandByPoint(_vector$8);
  6193. } else {
  6194. _box$1.expandByPoint(_boxMorphTargets.min);
  6195. _box$1.expandByPoint(_boxMorphTargets.max);
  6196. }
  6197. }
  6198. }
  6199. _box$1.getCenter(center); // second, try to find a boundingSphere with a radius smaller than the
  6200. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6201. let maxRadiusSq = 0;
  6202. for (let i = 0, il = position.count; i < il; i++) {
  6203. _vector$8.fromBufferAttribute(position, i);
  6204. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6205. } // process morph attributes if present
  6206. if (morphAttributesPosition) {
  6207. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6208. const morphAttribute = morphAttributesPosition[i];
  6209. const morphTargetsRelative = this.morphTargetsRelative;
  6210. for (let j = 0, jl = morphAttribute.count; j < jl; j++) {
  6211. _vector$8.fromBufferAttribute(morphAttribute, j);
  6212. if (morphTargetsRelative) {
  6213. _offset.fromBufferAttribute(position, j);
  6214. _vector$8.add(_offset);
  6215. }
  6216. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6217. }
  6218. }
  6219. }
  6220. this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
  6221. if (isNaN(this.boundingSphere.radius)) {
  6222. console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
  6223. }
  6224. }
  6225. }
  6226. computeTangents() {
  6227. const index = this.index;
  6228. const attributes = this.attributes; // based on http://www.terathon.com/code/tangent.html
  6229. // (per vertex tangents)
  6230. if (index === null || attributes.position === undefined || attributes.normal === undefined || attributes.uv === undefined) {
  6231. console.error('THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)');
  6232. return;
  6233. }
  6234. const indices = index.array;
  6235. const positions = attributes.position.array;
  6236. const normals = attributes.normal.array;
  6237. const uvs = attributes.uv.array;
  6238. const nVertices = positions.length / 3;
  6239. if (attributes.tangent === undefined) {
  6240. this.setAttribute('tangent', new BufferAttribute(new Float32Array(4 * nVertices), 4));
  6241. }
  6242. const tangents = attributes.tangent.array;
  6243. const tan1 = [],
  6244. tan2 = [];
  6245. for (let i = 0; i < nVertices; i++) {
  6246. tan1[i] = new Vector3();
  6247. tan2[i] = new Vector3();
  6248. }
  6249. const vA = new Vector3(),
  6250. vB = new Vector3(),
  6251. vC = new Vector3(),
  6252. uvA = new Vector2(),
  6253. uvB = new Vector2(),
  6254. uvC = new Vector2(),
  6255. sdir = new Vector3(),
  6256. tdir = new Vector3();
  6257. function handleTriangle(a, b, c) {
  6258. vA.fromArray(positions, a * 3);
  6259. vB.fromArray(positions, b * 3);
  6260. vC.fromArray(positions, c * 3);
  6261. uvA.fromArray(uvs, a * 2);
  6262. uvB.fromArray(uvs, b * 2);
  6263. uvC.fromArray(uvs, c * 2);
  6264. vB.sub(vA);
  6265. vC.sub(vA);
  6266. uvB.sub(uvA);
  6267. uvC.sub(uvA);
  6268. const r = 1.0 / (uvB.x * uvC.y - uvC.x * uvB.y); // silently ignore degenerate uv triangles having coincident or colinear vertices
  6269. if (!isFinite(r)) return;
  6270. sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r);
  6271. tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r);
  6272. tan1[a].add(sdir);
  6273. tan1[b].add(sdir);
  6274. tan1[c].add(sdir);
  6275. tan2[a].add(tdir);
  6276. tan2[b].add(tdir);
  6277. tan2[c].add(tdir);
  6278. }
  6279. let groups = this.groups;
  6280. if (groups.length === 0) {
  6281. groups = [{
  6282. start: 0,
  6283. count: indices.length
  6284. }];
  6285. }
  6286. for (let i = 0, il = groups.length; i < il; ++i) {
  6287. const group = groups[i];
  6288. const start = group.start;
  6289. const count = group.count;
  6290. for (let j = start, jl = start + count; j < jl; j += 3) {
  6291. handleTriangle(indices[j + 0], indices[j + 1], indices[j + 2]);
  6292. }
  6293. }
  6294. const tmp = new Vector3(),
  6295. tmp2 = new Vector3();
  6296. const n = new Vector3(),
  6297. n2 = new Vector3();
  6298. function handleVertex(v) {
  6299. n.fromArray(normals, v * 3);
  6300. n2.copy(n);
  6301. const t = tan1[v]; // Gram-Schmidt orthogonalize
  6302. tmp.copy(t);
  6303. tmp.sub(n.multiplyScalar(n.dot(t))).normalize(); // Calculate handedness
  6304. tmp2.crossVectors(n2, t);
  6305. const test = tmp2.dot(tan2[v]);
  6306. const w = test < 0.0 ? -1.0 : 1.0;
  6307. tangents[v * 4] = tmp.x;
  6308. tangents[v * 4 + 1] = tmp.y;
  6309. tangents[v * 4 + 2] = tmp.z;
  6310. tangents[v * 4 + 3] = w;
  6311. }
  6312. for (let i = 0, il = groups.length; i < il; ++i) {
  6313. const group = groups[i];
  6314. const start = group.start;
  6315. const count = group.count;
  6316. for (let j = start, jl = start + count; j < jl; j += 3) {
  6317. handleVertex(indices[j + 0]);
  6318. handleVertex(indices[j + 1]);
  6319. handleVertex(indices[j + 2]);
  6320. }
  6321. }
  6322. }
  6323. computeVertexNormals() {
  6324. const index = this.index;
  6325. const positionAttribute = this.getAttribute('position');
  6326. if (positionAttribute !== undefined) {
  6327. let normalAttribute = this.getAttribute('normal');
  6328. if (normalAttribute === undefined) {
  6329. normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3);
  6330. this.setAttribute('normal', normalAttribute);
  6331. } else {
  6332. // reset existing normals to zero
  6333. for (let i = 0, il = normalAttribute.count; i < il; i++) {
  6334. normalAttribute.setXYZ(i, 0, 0, 0);
  6335. }
  6336. }
  6337. const pA = new Vector3(),
  6338. pB = new Vector3(),
  6339. pC = new Vector3();
  6340. const nA = new Vector3(),
  6341. nB = new Vector3(),
  6342. nC = new Vector3();
  6343. const cb = new Vector3(),
  6344. ab = new Vector3(); // indexed elements
  6345. if (index) {
  6346. for (let i = 0, il = index.count; i < il; i += 3) {
  6347. const vA = index.getX(i + 0);
  6348. const vB = index.getX(i + 1);
  6349. const vC = index.getX(i + 2);
  6350. pA.fromBufferAttribute(positionAttribute, vA);
  6351. pB.fromBufferAttribute(positionAttribute, vB);
  6352. pC.fromBufferAttribute(positionAttribute, vC);
  6353. cb.subVectors(pC, pB);
  6354. ab.subVectors(pA, pB);
  6355. cb.cross(ab);
  6356. nA.fromBufferAttribute(normalAttribute, vA);
  6357. nB.fromBufferAttribute(normalAttribute, vB);
  6358. nC.fromBufferAttribute(normalAttribute, vC);
  6359. nA.add(cb);
  6360. nB.add(cb);
  6361. nC.add(cb);
  6362. normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z);
  6363. normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z);
  6364. normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z);
  6365. }
  6366. } else {
  6367. // non-indexed elements (unconnected triangle soup)
  6368. for (let i = 0, il = positionAttribute.count; i < il; i += 3) {
  6369. pA.fromBufferAttribute(positionAttribute, i + 0);
  6370. pB.fromBufferAttribute(positionAttribute, i + 1);
  6371. pC.fromBufferAttribute(positionAttribute, i + 2);
  6372. cb.subVectors(pC, pB);
  6373. ab.subVectors(pA, pB);
  6374. cb.cross(ab);
  6375. normalAttribute.setXYZ(i + 0, cb.x, cb.y, cb.z);
  6376. normalAttribute.setXYZ(i + 1, cb.x, cb.y, cb.z);
  6377. normalAttribute.setXYZ(i + 2, cb.x, cb.y, cb.z);
  6378. }
  6379. }
  6380. this.normalizeNormals();
  6381. normalAttribute.needsUpdate = true;
  6382. }
  6383. }
  6384. merge(geometry, offset) {
  6385. if (!(geometry && geometry.isBufferGeometry)) {
  6386. console.error('THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry);
  6387. return;
  6388. }
  6389. if (offset === undefined) {
  6390. offset = 0;
  6391. console.warn('THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.');
  6392. }
  6393. const attributes = this.attributes;
  6394. for (const key in attributes) {
  6395. if (geometry.attributes[key] === undefined) continue;
  6396. const attribute1 = attributes[key];
  6397. const attributeArray1 = attribute1.array;
  6398. const attribute2 = geometry.attributes[key];
  6399. const attributeArray2 = attribute2.array;
  6400. const attributeOffset = attribute2.itemSize * offset;
  6401. const length = Math.min(attributeArray2.length, attributeArray1.length - attributeOffset);
  6402. for (let i = 0, j = attributeOffset; i < length; i++, j++) {
  6403. attributeArray1[j] = attributeArray2[i];
  6404. }
  6405. }
  6406. return this;
  6407. }
  6408. normalizeNormals() {
  6409. const normals = this.attributes.normal;
  6410. for (let i = 0, il = normals.count; i < il; i++) {
  6411. _vector$8.fromBufferAttribute(normals, i);
  6412. _vector$8.normalize();
  6413. normals.setXYZ(i, _vector$8.x, _vector$8.y, _vector$8.z);
  6414. }
  6415. }
  6416. toNonIndexed() {
  6417. function convertBufferAttribute(attribute, indices) {
  6418. const array = attribute.array;
  6419. const itemSize = attribute.itemSize;
  6420. const normalized = attribute.normalized;
  6421. const array2 = new array.constructor(indices.length * itemSize);
  6422. let index = 0,
  6423. index2 = 0;
  6424. for (let i = 0, l = indices.length; i < l; i++) {
  6425. if (attribute.isInterleavedBufferAttribute) {
  6426. index = indices[i] * attribute.data.stride + attribute.offset;
  6427. } else {
  6428. index = indices[i] * itemSize;
  6429. }
  6430. for (let j = 0; j < itemSize; j++) {
  6431. array2[index2++] = array[index++];
  6432. }
  6433. }
  6434. return new BufferAttribute(array2, itemSize, normalized);
  6435. } //
  6436. if (this.index === null) {
  6437. console.warn('THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.');
  6438. return this;
  6439. }
  6440. const geometry2 = new BufferGeometry();
  6441. const indices = this.index.array;
  6442. const attributes = this.attributes; // attributes
  6443. for (const name in attributes) {
  6444. const attribute = attributes[name];
  6445. const newAttribute = convertBufferAttribute(attribute, indices);
  6446. geometry2.setAttribute(name, newAttribute);
  6447. } // morph attributes
  6448. const morphAttributes = this.morphAttributes;
  6449. for (const name in morphAttributes) {
  6450. const morphArray = [];
  6451. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6452. for (let i = 0, il = morphAttribute.length; i < il; i++) {
  6453. const attribute = morphAttribute[i];
  6454. const newAttribute = convertBufferAttribute(attribute, indices);
  6455. morphArray.push(newAttribute);
  6456. }
  6457. geometry2.morphAttributes[name] = morphArray;
  6458. }
  6459. geometry2.morphTargetsRelative = this.morphTargetsRelative; // groups
  6460. const groups = this.groups;
  6461. for (let i = 0, l = groups.length; i < l; i++) {
  6462. const group = groups[i];
  6463. geometry2.addGroup(group.start, group.count, group.materialIndex);
  6464. }
  6465. return geometry2;
  6466. }
  6467. toJSON() {
  6468. const data = {
  6469. metadata: {
  6470. version: 4.5,
  6471. type: 'BufferGeometry',
  6472. generator: 'BufferGeometry.toJSON'
  6473. }
  6474. }; // standard BufferGeometry serialization
  6475. data.uuid = this.uuid;
  6476. data.type = this.type;
  6477. if (this.name !== '') data.name = this.name;
  6478. if (Object.keys(this.userData).length > 0) data.userData = this.userData;
  6479. if (this.parameters !== undefined) {
  6480. const parameters = this.parameters;
  6481. for (const key in parameters) {
  6482. if (parameters[key] !== undefined) data[key] = parameters[key];
  6483. }
  6484. return data;
  6485. } // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6486. data.data = {
  6487. attributes: {}
  6488. };
  6489. const index = this.index;
  6490. if (index !== null) {
  6491. data.data.index = {
  6492. type: index.array.constructor.name,
  6493. array: Array.prototype.slice.call(index.array)
  6494. };
  6495. }
  6496. const attributes = this.attributes;
  6497. for (const key in attributes) {
  6498. const attribute = attributes[key];
  6499. data.data.attributes[key] = attribute.toJSON(data.data);
  6500. }
  6501. const morphAttributes = {};
  6502. let hasMorphAttributes = false;
  6503. for (const key in this.morphAttributes) {
  6504. const attributeArray = this.morphAttributes[key];
  6505. const array = [];
  6506. for (let i = 0, il = attributeArray.length; i < il; i++) {
  6507. const attribute = attributeArray[i];
  6508. array.push(attribute.toJSON(data.data));
  6509. }
  6510. if (array.length > 0) {
  6511. morphAttributes[key] = array;
  6512. hasMorphAttributes = true;
  6513. }
  6514. }
  6515. if (hasMorphAttributes) {
  6516. data.data.morphAttributes = morphAttributes;
  6517. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6518. }
  6519. const groups = this.groups;
  6520. if (groups.length > 0) {
  6521. data.data.groups = JSON.parse(JSON.stringify(groups));
  6522. }
  6523. const boundingSphere = this.boundingSphere;
  6524. if (boundingSphere !== null) {
  6525. data.data.boundingSphere = {
  6526. center: boundingSphere.center.toArray(),
  6527. radius: boundingSphere.radius
  6528. };
  6529. }
  6530. return data;
  6531. }
  6532. clone() {
  6533. return new this.constructor().copy(this);
  6534. }
  6535. copy(source) {
  6536. // reset
  6537. this.index = null;
  6538. this.attributes = {};
  6539. this.morphAttributes = {};
  6540. this.groups = [];
  6541. this.boundingBox = null;
  6542. this.boundingSphere = null; // used for storing cloned, shared data
  6543. const data = {}; // name
  6544. this.name = source.name; // index
  6545. const index = source.index;
  6546. if (index !== null) {
  6547. this.setIndex(index.clone(data));
  6548. } // attributes
  6549. const attributes = source.attributes;
  6550. for (const name in attributes) {
  6551. const attribute = attributes[name];
  6552. this.setAttribute(name, attribute.clone(data));
  6553. } // morph attributes
  6554. const morphAttributes = source.morphAttributes;
  6555. for (const name in morphAttributes) {
  6556. const array = [];
  6557. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6558. for (let i = 0, l = morphAttribute.length; i < l; i++) {
  6559. array.push(morphAttribute[i].clone(data));
  6560. }
  6561. this.morphAttributes[name] = array;
  6562. }
  6563. this.morphTargetsRelative = source.morphTargetsRelative; // groups
  6564. const groups = source.groups;
  6565. for (let i = 0, l = groups.length; i < l; i++) {
  6566. const group = groups[i];
  6567. this.addGroup(group.start, group.count, group.materialIndex);
  6568. } // bounding box
  6569. const boundingBox = source.boundingBox;
  6570. if (boundingBox !== null) {
  6571. this.boundingBox = boundingBox.clone();
  6572. } // bounding sphere
  6573. const boundingSphere = source.boundingSphere;
  6574. if (boundingSphere !== null) {
  6575. this.boundingSphere = boundingSphere.clone();
  6576. } // draw range
  6577. this.drawRange.start = source.drawRange.start;
  6578. this.drawRange.count = source.drawRange.count; // user data
  6579. this.userData = source.userData; // geometry generator parameters
  6580. if (source.parameters !== undefined) this.parameters = Object.assign({}, source.parameters);
  6581. return this;
  6582. }
  6583. dispose() {
  6584. this.dispatchEvent({
  6585. type: 'dispose'
  6586. });
  6587. }
  6588. }
  6589. BufferGeometry.prototype.isBufferGeometry = true;
  6590. const _inverseMatrix$2 = /*@__PURE__*/new Matrix4();
  6591. const _ray$2 = /*@__PURE__*/new Ray();
  6592. const _sphere$3 = /*@__PURE__*/new Sphere();
  6593. const _vA$1 = /*@__PURE__*/new Vector3();
  6594. const _vB$1 = /*@__PURE__*/new Vector3();
  6595. const _vC$1 = /*@__PURE__*/new Vector3();
  6596. const _tempA = /*@__PURE__*/new Vector3();
  6597. const _tempB = /*@__PURE__*/new Vector3();
  6598. const _tempC = /*@__PURE__*/new Vector3();
  6599. const _morphA = /*@__PURE__*/new Vector3();
  6600. const _morphB = /*@__PURE__*/new Vector3();
  6601. const _morphC = /*@__PURE__*/new Vector3();
  6602. const _uvA$1 = /*@__PURE__*/new Vector2();
  6603. const _uvB$1 = /*@__PURE__*/new Vector2();
  6604. const _uvC$1 = /*@__PURE__*/new Vector2();
  6605. const _intersectionPoint = /*@__PURE__*/new Vector3();
  6606. const _intersectionPointWorld = /*@__PURE__*/new Vector3();
  6607. class Mesh extends Object3D {
  6608. constructor(geometry = new BufferGeometry(), material = new MeshBasicMaterial()) {
  6609. super();
  6610. this.type = 'Mesh';
  6611. this.geometry = geometry;
  6612. this.material = material;
  6613. this.updateMorphTargets();
  6614. }
  6615. copy(source) {
  6616. super.copy(source);
  6617. if (source.morphTargetInfluences !== undefined) {
  6618. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6619. }
  6620. if (source.morphTargetDictionary !== undefined) {
  6621. this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
  6622. }
  6623. this.material = source.material;
  6624. this.geometry = source.geometry;
  6625. return this;
  6626. }
  6627. updateMorphTargets() {
  6628. const geometry = this.geometry;
  6629. if (geometry.isBufferGeometry) {
  6630. const morphAttributes = geometry.morphAttributes;
  6631. const keys = Object.keys(morphAttributes);
  6632. if (keys.length > 0) {
  6633. const morphAttribute = morphAttributes[keys[0]];
  6634. if (morphAttribute !== undefined) {
  6635. this.morphTargetInfluences = [];
  6636. this.morphTargetDictionary = {};
  6637. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  6638. const name = morphAttribute[m].name || String(m);
  6639. this.morphTargetInfluences.push(0);
  6640. this.morphTargetDictionary[name] = m;
  6641. }
  6642. }
  6643. }
  6644. } else {
  6645. const morphTargets = geometry.morphTargets;
  6646. if (morphTargets !== undefined && morphTargets.length > 0) {
  6647. console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  6648. }
  6649. }
  6650. }
  6651. raycast(raycaster, intersects) {
  6652. const geometry = this.geometry;
  6653. const material = this.material;
  6654. const matrixWorld = this.matrixWorld;
  6655. if (material === undefined) return; // Checking boundingSphere distance to ray
  6656. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  6657. _sphere$3.copy(geometry.boundingSphere);
  6658. _sphere$3.applyMatrix4(matrixWorld);
  6659. if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; //
  6660. _inverseMatrix$2.copy(matrixWorld).invert();
  6661. _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2); // Check boundingBox before continuing
  6662. if (geometry.boundingBox !== null) {
  6663. if (_ray$2.intersectsBox(geometry.boundingBox) === false) return;
  6664. }
  6665. let intersection;
  6666. if (geometry.isBufferGeometry) {
  6667. const index = geometry.index;
  6668. const position = geometry.attributes.position;
  6669. const morphPosition = geometry.morphAttributes.position;
  6670. const morphTargetsRelative = geometry.morphTargetsRelative;
  6671. const uv = geometry.attributes.uv;
  6672. const uv2 = geometry.attributes.uv2;
  6673. const groups = geometry.groups;
  6674. const drawRange = geometry.drawRange;
  6675. if (index !== null) {
  6676. // indexed buffer geometry
  6677. if (Array.isArray(material)) {
  6678. for (let i = 0, il = groups.length; i < il; i++) {
  6679. const group = groups[i];
  6680. const groupMaterial = material[group.materialIndex];
  6681. const start = Math.max(group.start, drawRange.start);
  6682. const end = Math.min(index.count, Math.min(group.start + group.count, drawRange.start + drawRange.count));
  6683. for (let j = start, jl = end; j < jl; j += 3) {
  6684. const a = index.getX(j);
  6685. const b = index.getX(j + 1);
  6686. const c = index.getX(j + 2);
  6687. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6688. if (intersection) {
  6689. intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
  6690. intersection.face.materialIndex = group.materialIndex;
  6691. intersects.push(intersection);
  6692. }
  6693. }
  6694. }
  6695. } else {
  6696. const start = Math.max(0, drawRange.start);
  6697. const end = Math.min(index.count, drawRange.start + drawRange.count);
  6698. for (let i = start, il = end; i < il; i += 3) {
  6699. const a = index.getX(i);
  6700. const b = index.getX(i + 1);
  6701. const c = index.getX(i + 2);
  6702. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6703. if (intersection) {
  6704. intersection.faceIndex = Math.floor(i / 3); // triangle number in indexed buffer semantics
  6705. intersects.push(intersection);
  6706. }
  6707. }
  6708. }
  6709. } else if (position !== undefined) {
  6710. // non-indexed buffer geometry
  6711. if (Array.isArray(material)) {
  6712. for (let i = 0, il = groups.length; i < il; i++) {
  6713. const group = groups[i];
  6714. const groupMaterial = material[group.materialIndex];
  6715. const start = Math.max(group.start, drawRange.start);
  6716. const end = Math.min(position.count, Math.min(group.start + group.count, drawRange.start + drawRange.count));
  6717. for (let j = start, jl = end; j < jl; j += 3) {
  6718. const a = j;
  6719. const b = j + 1;
  6720. const c = j + 2;
  6721. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6722. if (intersection) {
  6723. intersection.faceIndex = Math.floor(j / 3); // triangle number in non-indexed buffer semantics
  6724. intersection.face.materialIndex = group.materialIndex;
  6725. intersects.push(intersection);
  6726. }
  6727. }
  6728. }
  6729. } else {
  6730. const start = Math.max(0, drawRange.start);
  6731. const end = Math.min(position.count, drawRange.start + drawRange.count);
  6732. for (let i = start, il = end; i < il; i += 3) {
  6733. const a = i;
  6734. const b = i + 1;
  6735. const c = i + 2;
  6736. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6737. if (intersection) {
  6738. intersection.faceIndex = Math.floor(i / 3); // triangle number in non-indexed buffer semantics
  6739. intersects.push(intersection);
  6740. }
  6741. }
  6742. }
  6743. }
  6744. } else if (geometry.isGeometry) {
  6745. console.error('THREE.Mesh.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  6746. }
  6747. }
  6748. }
  6749. Mesh.prototype.isMesh = true;
  6750. function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
  6751. let intersect;
  6752. if (material.side === BackSide) {
  6753. intersect = ray.intersectTriangle(pC, pB, pA, true, point);
  6754. } else {
  6755. intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
  6756. }
  6757. if (intersect === null) return null;
  6758. _intersectionPointWorld.copy(point);
  6759. _intersectionPointWorld.applyMatrix4(object.matrixWorld);
  6760. const distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
  6761. if (distance < raycaster.near || distance > raycaster.far) return null;
  6762. return {
  6763. distance: distance,
  6764. point: _intersectionPointWorld.clone(),
  6765. object: object
  6766. };
  6767. }
  6768. function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c) {
  6769. _vA$1.fromBufferAttribute(position, a);
  6770. _vB$1.fromBufferAttribute(position, b);
  6771. _vC$1.fromBufferAttribute(position, c);
  6772. const morphInfluences = object.morphTargetInfluences;
  6773. if (morphPosition && morphInfluences) {
  6774. _morphA.set(0, 0, 0);
  6775. _morphB.set(0, 0, 0);
  6776. _morphC.set(0, 0, 0);
  6777. for (let i = 0, il = morphPosition.length; i < il; i++) {
  6778. const influence = morphInfluences[i];
  6779. const morphAttribute = morphPosition[i];
  6780. if (influence === 0) continue;
  6781. _tempA.fromBufferAttribute(morphAttribute, a);
  6782. _tempB.fromBufferAttribute(morphAttribute, b);
  6783. _tempC.fromBufferAttribute(morphAttribute, c);
  6784. if (morphTargetsRelative) {
  6785. _morphA.addScaledVector(_tempA, influence);
  6786. _morphB.addScaledVector(_tempB, influence);
  6787. _morphC.addScaledVector(_tempC, influence);
  6788. } else {
  6789. _morphA.addScaledVector(_tempA.sub(_vA$1), influence);
  6790. _morphB.addScaledVector(_tempB.sub(_vB$1), influence);
  6791. _morphC.addScaledVector(_tempC.sub(_vC$1), influence);
  6792. }
  6793. }
  6794. _vA$1.add(_morphA);
  6795. _vB$1.add(_morphB);
  6796. _vC$1.add(_morphC);
  6797. }
  6798. if (object.isSkinnedMesh) {
  6799. object.boneTransform(a, _vA$1);
  6800. object.boneTransform(b, _vB$1);
  6801. object.boneTransform(c, _vC$1);
  6802. }
  6803. const intersection = checkIntersection(object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint);
  6804. if (intersection) {
  6805. if (uv) {
  6806. _uvA$1.fromBufferAttribute(uv, a);
  6807. _uvB$1.fromBufferAttribute(uv, b);
  6808. _uvC$1.fromBufferAttribute(uv, c);
  6809. intersection.uv = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  6810. }
  6811. if (uv2) {
  6812. _uvA$1.fromBufferAttribute(uv2, a);
  6813. _uvB$1.fromBufferAttribute(uv2, b);
  6814. _uvC$1.fromBufferAttribute(uv2, c);
  6815. intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  6816. }
  6817. const face = {
  6818. a: a,
  6819. b: b,
  6820. c: c,
  6821. normal: new Vector3(),
  6822. materialIndex: 0
  6823. };
  6824. Triangle.getNormal(_vA$1, _vB$1, _vC$1, face.normal);
  6825. intersection.face = face;
  6826. }
  6827. return intersection;
  6828. }
  6829. class BoxGeometry extends BufferGeometry {
  6830. constructor(width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) {
  6831. super();
  6832. this.type = 'BoxGeometry';
  6833. this.parameters = {
  6834. width: width,
  6835. height: height,
  6836. depth: depth,
  6837. widthSegments: widthSegments,
  6838. heightSegments: heightSegments,
  6839. depthSegments: depthSegments
  6840. };
  6841. const scope = this; // segments
  6842. widthSegments = Math.floor(widthSegments);
  6843. heightSegments = Math.floor(heightSegments);
  6844. depthSegments = Math.floor(depthSegments); // buffers
  6845. const indices = [];
  6846. const vertices = [];
  6847. const normals = [];
  6848. const uvs = []; // helper variables
  6849. let numberOfVertices = 0;
  6850. let groupStart = 0; // build each side of the box geometry
  6851. buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
  6852. buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
  6853. buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
  6854. buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
  6855. buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
  6856. buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
  6857. // build geometry
  6858. this.setIndex(indices);
  6859. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  6860. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  6861. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  6862. function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {
  6863. const segmentWidth = width / gridX;
  6864. const segmentHeight = height / gridY;
  6865. const widthHalf = width / 2;
  6866. const heightHalf = height / 2;
  6867. const depthHalf = depth / 2;
  6868. const gridX1 = gridX + 1;
  6869. const gridY1 = gridY + 1;
  6870. let vertexCounter = 0;
  6871. let groupCount = 0;
  6872. const vector = new Vector3(); // generate vertices, normals and uvs
  6873. for (let iy = 0; iy < gridY1; iy++) {
  6874. const y = iy * segmentHeight - heightHalf;
  6875. for (let ix = 0; ix < gridX1; ix++) {
  6876. const x = ix * segmentWidth - widthHalf; // set values to correct vector component
  6877. vector[u] = x * udir;
  6878. vector[v] = y * vdir;
  6879. vector[w] = depthHalf; // now apply vector to vertex buffer
  6880. vertices.push(vector.x, vector.y, vector.z); // set values to correct vector component
  6881. vector[u] = 0;
  6882. vector[v] = 0;
  6883. vector[w] = depth > 0 ? 1 : -1; // now apply vector to normal buffer
  6884. normals.push(vector.x, vector.y, vector.z); // uvs
  6885. uvs.push(ix / gridX);
  6886. uvs.push(1 - iy / gridY); // counters
  6887. vertexCounter += 1;
  6888. }
  6889. } // indices
  6890. // 1. you need three indices to draw a single face
  6891. // 2. a single segment consists of two faces
  6892. // 3. so we need to generate six (2*3) indices per segment
  6893. for (let iy = 0; iy < gridY; iy++) {
  6894. for (let ix = 0; ix < gridX; ix++) {
  6895. const a = numberOfVertices + ix + gridX1 * iy;
  6896. const b = numberOfVertices + ix + gridX1 * (iy + 1);
  6897. const c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);
  6898. const d = numberOfVertices + (ix + 1) + gridX1 * iy; // faces
  6899. indices.push(a, b, d);
  6900. indices.push(b, c, d); // increase counter
  6901. groupCount += 6;
  6902. }
  6903. } // add a group to the geometry. this will ensure multi material support
  6904. scope.addGroup(groupStart, groupCount, materialIndex); // calculate new start value for groups
  6905. groupStart += groupCount; // update total number of vertices
  6906. numberOfVertices += vertexCounter;
  6907. }
  6908. }
  6909. static fromJSON(data) {
  6910. return new BoxGeometry(data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
  6911. }
  6912. }
  6913. /**
  6914. * Uniform Utilities
  6915. */
  6916. function cloneUniforms(src) {
  6917. const dst = {};
  6918. for (const u in src) {
  6919. dst[u] = {};
  6920. for (const p in src[u]) {
  6921. const property = src[u][p];
  6922. if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture || property.isQuaternion)) {
  6923. dst[u][p] = property.clone();
  6924. } else if (Array.isArray(property)) {
  6925. dst[u][p] = property.slice();
  6926. } else {
  6927. dst[u][p] = property;
  6928. }
  6929. }
  6930. }
  6931. return dst;
  6932. }
  6933. function mergeUniforms(uniforms) {
  6934. const merged = {};
  6935. for (let u = 0; u < uniforms.length; u++) {
  6936. const tmp = cloneUniforms(uniforms[u]);
  6937. for (const p in tmp) {
  6938. merged[p] = tmp[p];
  6939. }
  6940. }
  6941. return merged;
  6942. } // Legacy
  6943. const UniformsUtils = {
  6944. clone: cloneUniforms,
  6945. merge: mergeUniforms
  6946. };
  6947. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  6948. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  6949. /**
  6950. * parameters = {
  6951. * defines: { "label" : "value" },
  6952. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  6953. *
  6954. * fragmentShader: <string>,
  6955. * vertexShader: <string>,
  6956. *
  6957. * wireframe: <boolean>,
  6958. * wireframeLinewidth: <float>,
  6959. *
  6960. * lights: <bool>
  6961. * }
  6962. */
  6963. class ShaderMaterial extends Material {
  6964. constructor(parameters) {
  6965. super();
  6966. this.type = 'ShaderMaterial';
  6967. this.defines = {};
  6968. this.uniforms = {};
  6969. this.vertexShader = default_vertex;
  6970. this.fragmentShader = default_fragment;
  6971. this.linewidth = 1;
  6972. this.wireframe = false;
  6973. this.wireframeLinewidth = 1;
  6974. this.fog = false; // set to use scene fog
  6975. this.lights = false; // set to use scene lights
  6976. this.clipping = false; // set to use user-defined clipping planes
  6977. this.extensions = {
  6978. derivatives: false,
  6979. // set to use derivatives
  6980. fragDepth: false,
  6981. // set to use fragment depth values
  6982. drawBuffers: false,
  6983. // set to use draw buffers
  6984. shaderTextureLOD: false // set to use shader texture LOD
  6985. }; // When rendered geometry doesn't include these attributes but the material does,
  6986. // use these default values in WebGL. This avoids errors when buffer data is missing.
  6987. this.defaultAttributeValues = {
  6988. 'color': [1, 1, 1],
  6989. 'uv': [0, 0],
  6990. 'uv2': [0, 0]
  6991. };
  6992. this.index0AttributeName = undefined;
  6993. this.uniformsNeedUpdate = false;
  6994. this.glslVersion = null;
  6995. if (parameters !== undefined) {
  6996. if (parameters.attributes !== undefined) {
  6997. console.error('THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.');
  6998. }
  6999. this.setValues(parameters);
  7000. }
  7001. }
  7002. copy(source) {
  7003. super.copy(source);
  7004. this.fragmentShader = source.fragmentShader;
  7005. this.vertexShader = source.vertexShader;
  7006. this.uniforms = cloneUniforms(source.uniforms);
  7007. this.defines = Object.assign({}, source.defines);
  7008. this.wireframe = source.wireframe;
  7009. this.wireframeLinewidth = source.wireframeLinewidth;
  7010. this.lights = source.lights;
  7011. this.clipping = source.clipping;
  7012. this.extensions = Object.assign({}, source.extensions);
  7013. this.glslVersion = source.glslVersion;
  7014. return this;
  7015. }
  7016. toJSON(meta) {
  7017. const data = super.toJSON(meta);
  7018. data.glslVersion = this.glslVersion;
  7019. data.uniforms = {};
  7020. for (const name in this.uniforms) {
  7021. const uniform = this.uniforms[name];
  7022. const value = uniform.value;
  7023. if (value && value.isTexture) {
  7024. data.uniforms[name] = {
  7025. type: 't',
  7026. value: value.toJSON(meta).uuid
  7027. };
  7028. } else if (value && value.isColor) {
  7029. data.uniforms[name] = {
  7030. type: 'c',
  7031. value: value.getHex()
  7032. };
  7033. } else if (value && value.isVector2) {
  7034. data.uniforms[name] = {
  7035. type: 'v2',
  7036. value: value.toArray()
  7037. };
  7038. } else if (value && value.isVector3) {
  7039. data.uniforms[name] = {
  7040. type: 'v3',
  7041. value: value.toArray()
  7042. };
  7043. } else if (value && value.isVector4) {
  7044. data.uniforms[name] = {
  7045. type: 'v4',
  7046. value: value.toArray()
  7047. };
  7048. } else if (value && value.isMatrix3) {
  7049. data.uniforms[name] = {
  7050. type: 'm3',
  7051. value: value.toArray()
  7052. };
  7053. } else if (value && value.isMatrix4) {
  7054. data.uniforms[name] = {
  7055. type: 'm4',
  7056. value: value.toArray()
  7057. };
  7058. } else {
  7059. data.uniforms[name] = {
  7060. value: value
  7061. }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7062. }
  7063. }
  7064. if (Object.keys(this.defines).length > 0) data.defines = this.defines;
  7065. data.vertexShader = this.vertexShader;
  7066. data.fragmentShader = this.fragmentShader;
  7067. const extensions = {};
  7068. for (const key in this.extensions) {
  7069. if (this.extensions[key] === true) extensions[key] = true;
  7070. }
  7071. if (Object.keys(extensions).length > 0) data.extensions = extensions;
  7072. return data;
  7073. }
  7074. }
  7075. ShaderMaterial.prototype.isShaderMaterial = true;
  7076. class Camera extends Object3D {
  7077. constructor() {
  7078. super();
  7079. this.type = 'Camera';
  7080. this.matrixWorldInverse = new Matrix4();
  7081. this.projectionMatrix = new Matrix4();
  7082. this.projectionMatrixInverse = new Matrix4();
  7083. }
  7084. copy(source, recursive) {
  7085. super.copy(source, recursive);
  7086. this.matrixWorldInverse.copy(source.matrixWorldInverse);
  7087. this.projectionMatrix.copy(source.projectionMatrix);
  7088. this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
  7089. return this;
  7090. }
  7091. getWorldDirection(target) {
  7092. this.updateWorldMatrix(true, false);
  7093. const e = this.matrixWorld.elements;
  7094. return target.set(-e[8], -e[9], -e[10]).normalize();
  7095. }
  7096. updateMatrixWorld(force) {
  7097. super.updateMatrixWorld(force);
  7098. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7099. }
  7100. updateWorldMatrix(updateParents, updateChildren) {
  7101. super.updateWorldMatrix(updateParents, updateChildren);
  7102. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7103. }
  7104. clone() {
  7105. return new this.constructor().copy(this);
  7106. }
  7107. }
  7108. Camera.prototype.isCamera = true;
  7109. class PerspectiveCamera extends Camera {
  7110. constructor(fov = 50, aspect = 1, near = 0.1, far = 2000) {
  7111. super();
  7112. this.type = 'PerspectiveCamera';
  7113. this.fov = fov;
  7114. this.zoom = 1;
  7115. this.near = near;
  7116. this.far = far;
  7117. this.focus = 10;
  7118. this.aspect = aspect;
  7119. this.view = null;
  7120. this.filmGauge = 35; // width of the film (default in millimeters)
  7121. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7122. this.updateProjectionMatrix();
  7123. }
  7124. copy(source, recursive) {
  7125. super.copy(source, recursive);
  7126. this.fov = source.fov;
  7127. this.zoom = source.zoom;
  7128. this.near = source.near;
  7129. this.far = source.far;
  7130. this.focus = source.focus;
  7131. this.aspect = source.aspect;
  7132. this.view = source.view === null ? null : Object.assign({}, source.view);
  7133. this.filmGauge = source.filmGauge;
  7134. this.filmOffset = source.filmOffset;
  7135. return this;
  7136. }
  7137. /**
  7138. * Sets the FOV by focal length in respect to the current .filmGauge.
  7139. *
  7140. * The default film gauge is 35, so that the focal length can be specified for
  7141. * a 35mm (full frame) camera.
  7142. *
  7143. * Values for focal length and film gauge must have the same unit.
  7144. */
  7145. setFocalLength(focalLength) {
  7146. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7147. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7148. this.fov = RAD2DEG * 2 * Math.atan(vExtentSlope);
  7149. this.updateProjectionMatrix();
  7150. }
  7151. /**
  7152. * Calculates the focal length from the current .fov and .filmGauge.
  7153. */
  7154. getFocalLength() {
  7155. const vExtentSlope = Math.tan(DEG2RAD * 0.5 * this.fov);
  7156. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7157. }
  7158. getEffectiveFOV() {
  7159. return RAD2DEG * 2 * Math.atan(Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom);
  7160. }
  7161. getFilmWidth() {
  7162. // film not completely covered in portrait format (aspect < 1)
  7163. return this.filmGauge * Math.min(this.aspect, 1);
  7164. }
  7165. getFilmHeight() {
  7166. // film not completely covered in landscape format (aspect > 1)
  7167. return this.filmGauge / Math.max(this.aspect, 1);
  7168. }
  7169. /**
  7170. * Sets an offset in a larger frustum. This is useful for multi-window or
  7171. * multi-monitor/multi-machine setups.
  7172. *
  7173. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7174. * the monitors are in grid like this
  7175. *
  7176. * +---+---+---+
  7177. * | A | B | C |
  7178. * +---+---+---+
  7179. * | D | E | F |
  7180. * +---+---+---+
  7181. *
  7182. * then for each monitor you would call it like this
  7183. *
  7184. * const w = 1920;
  7185. * const h = 1080;
  7186. * const fullWidth = w * 3;
  7187. * const fullHeight = h * 2;
  7188. *
  7189. * --A--
  7190. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7191. * --B--
  7192. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7193. * --C--
  7194. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7195. * --D--
  7196. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7197. * --E--
  7198. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7199. * --F--
  7200. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7201. *
  7202. * Note there is no reason monitors have to be the same size or in a grid.
  7203. */
  7204. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  7205. this.aspect = fullWidth / fullHeight;
  7206. if (this.view === null) {
  7207. this.view = {
  7208. enabled: true,
  7209. fullWidth: 1,
  7210. fullHeight: 1,
  7211. offsetX: 0,
  7212. offsetY: 0,
  7213. width: 1,
  7214. height: 1
  7215. };
  7216. }
  7217. this.view.enabled = true;
  7218. this.view.fullWidth = fullWidth;
  7219. this.view.fullHeight = fullHeight;
  7220. this.view.offsetX = x;
  7221. this.view.offsetY = y;
  7222. this.view.width = width;
  7223. this.view.height = height;
  7224. this.updateProjectionMatrix();
  7225. }
  7226. clearViewOffset() {
  7227. if (this.view !== null) {
  7228. this.view.enabled = false;
  7229. }
  7230. this.updateProjectionMatrix();
  7231. }
  7232. updateProjectionMatrix() {
  7233. const near = this.near;
  7234. let top = near * Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom;
  7235. let height = 2 * top;
  7236. let width = this.aspect * height;
  7237. let left = -0.5 * width;
  7238. const view = this.view;
  7239. if (this.view !== null && this.view.enabled) {
  7240. const fullWidth = view.fullWidth,
  7241. fullHeight = view.fullHeight;
  7242. left += view.offsetX * width / fullWidth;
  7243. top -= view.offsetY * height / fullHeight;
  7244. width *= view.width / fullWidth;
  7245. height *= view.height / fullHeight;
  7246. }
  7247. const skew = this.filmOffset;
  7248. if (skew !== 0) left += near * skew / this.getFilmWidth();
  7249. this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);
  7250. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  7251. }
  7252. toJSON(meta) {
  7253. const data = super.toJSON(meta);
  7254. data.object.fov = this.fov;
  7255. data.object.zoom = this.zoom;
  7256. data.object.near = this.near;
  7257. data.object.far = this.far;
  7258. data.object.focus = this.focus;
  7259. data.object.aspect = this.aspect;
  7260. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  7261. data.object.filmGauge = this.filmGauge;
  7262. data.object.filmOffset = this.filmOffset;
  7263. return data;
  7264. }
  7265. }
  7266. PerspectiveCamera.prototype.isPerspectiveCamera = true;
  7267. const fov = 90,
  7268. aspect = 1;
  7269. class CubeCamera extends Object3D {
  7270. constructor(near, far, renderTarget) {
  7271. super();
  7272. this.type = 'CubeCamera';
  7273. if (renderTarget.isWebGLCubeRenderTarget !== true) {
  7274. console.error('THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.');
  7275. return;
  7276. }
  7277. this.renderTarget = renderTarget;
  7278. const cameraPX = new PerspectiveCamera(fov, aspect, near, far);
  7279. cameraPX.layers = this.layers;
  7280. cameraPX.up.set(0, -1, 0);
  7281. cameraPX.lookAt(new Vector3(1, 0, 0));
  7282. this.add(cameraPX);
  7283. const cameraNX = new PerspectiveCamera(fov, aspect, near, far);
  7284. cameraNX.layers = this.layers;
  7285. cameraNX.up.set(0, -1, 0);
  7286. cameraNX.lookAt(new Vector3(-1, 0, 0));
  7287. this.add(cameraNX);
  7288. const cameraPY = new PerspectiveCamera(fov, aspect, near, far);
  7289. cameraPY.layers = this.layers;
  7290. cameraPY.up.set(0, 0, 1);
  7291. cameraPY.lookAt(new Vector3(0, 1, 0));
  7292. this.add(cameraPY);
  7293. const cameraNY = new PerspectiveCamera(fov, aspect, near, far);
  7294. cameraNY.layers = this.layers;
  7295. cameraNY.up.set(0, 0, -1);
  7296. cameraNY.lookAt(new Vector3(0, -1, 0));
  7297. this.add(cameraNY);
  7298. const cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
  7299. cameraPZ.layers = this.layers;
  7300. cameraPZ.up.set(0, -1, 0);
  7301. cameraPZ.lookAt(new Vector3(0, 0, 1));
  7302. this.add(cameraPZ);
  7303. const cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
  7304. cameraNZ.layers = this.layers;
  7305. cameraNZ.up.set(0, -1, 0);
  7306. cameraNZ.lookAt(new Vector3(0, 0, -1));
  7307. this.add(cameraNZ);
  7308. }
  7309. update(renderer, scene) {
  7310. if (this.parent === null) this.updateMatrixWorld();
  7311. const renderTarget = this.renderTarget;
  7312. const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = this.children;
  7313. const currentXrEnabled = renderer.xr.enabled;
  7314. const currentRenderTarget = renderer.getRenderTarget();
  7315. renderer.xr.enabled = false;
  7316. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7317. renderTarget.texture.generateMipmaps = false;
  7318. renderer.setRenderTarget(renderTarget, 0);
  7319. renderer.render(scene, cameraPX);
  7320. renderer.setRenderTarget(renderTarget, 1);
  7321. renderer.render(scene, cameraNX);
  7322. renderer.setRenderTarget(renderTarget, 2);
  7323. renderer.render(scene, cameraPY);
  7324. renderer.setRenderTarget(renderTarget, 3);
  7325. renderer.render(scene, cameraNY);
  7326. renderer.setRenderTarget(renderTarget, 4);
  7327. renderer.render(scene, cameraPZ);
  7328. renderTarget.texture.generateMipmaps = generateMipmaps;
  7329. renderer.setRenderTarget(renderTarget, 5);
  7330. renderer.render(scene, cameraNZ);
  7331. renderer.setRenderTarget(currentRenderTarget);
  7332. renderer.xr.enabled = currentXrEnabled;
  7333. }
  7334. }
  7335. class CubeTexture extends Texture {
  7336. constructor(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  7337. images = images !== undefined ? images : [];
  7338. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7339. super(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  7340. this.flipY = false;
  7341. }
  7342. get images() {
  7343. return this.image;
  7344. }
  7345. set images(value) {
  7346. this.image = value;
  7347. }
  7348. }
  7349. CubeTexture.prototype.isCubeTexture = true;
  7350. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7351. constructor(size, options, dummy) {
  7352. if (Number.isInteger(options)) {
  7353. console.warn('THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )');
  7354. options = dummy;
  7355. }
  7356. super(size, size, options);
  7357. options = options || {}; // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7358. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7359. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7360. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7361. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7362. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7363. this.texture = new CubeTexture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  7364. this.texture.isRenderTargetTexture = true;
  7365. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7366. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7367. this.texture._needsFlipEnvMap = false;
  7368. }
  7369. fromEquirectangularTexture(renderer, texture) {
  7370. this.texture.type = texture.type;
  7371. this.texture.format = RGBAFormat; // see #18859
  7372. this.texture.encoding = texture.encoding;
  7373. this.texture.generateMipmaps = texture.generateMipmaps;
  7374. this.texture.minFilter = texture.minFilter;
  7375. this.texture.magFilter = texture.magFilter;
  7376. const shader = {
  7377. uniforms: {
  7378. tEquirect: {
  7379. value: null
  7380. }
  7381. },
  7382. vertexShader:
  7383. /* glsl */
  7384. `
  7385. varying vec3 vWorldDirection;
  7386. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7387. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7388. }
  7389. void main() {
  7390. vWorldDirection = transformDirection( position, modelMatrix );
  7391. #include <begin_vertex>
  7392. #include <project_vertex>
  7393. }
  7394. `,
  7395. fragmentShader:
  7396. /* glsl */
  7397. `
  7398. uniform sampler2D tEquirect;
  7399. varying vec3 vWorldDirection;
  7400. #include <common>
  7401. void main() {
  7402. vec3 direction = normalize( vWorldDirection );
  7403. vec2 sampleUV = equirectUv( direction );
  7404. gl_FragColor = texture2D( tEquirect, sampleUV );
  7405. }
  7406. `
  7407. };
  7408. const geometry = new BoxGeometry(5, 5, 5);
  7409. const material = new ShaderMaterial({
  7410. name: 'CubemapFromEquirect',
  7411. uniforms: cloneUniforms(shader.uniforms),
  7412. vertexShader: shader.vertexShader,
  7413. fragmentShader: shader.fragmentShader,
  7414. side: BackSide,
  7415. blending: NoBlending
  7416. });
  7417. material.uniforms.tEquirect.value = texture;
  7418. const mesh = new Mesh(geometry, material);
  7419. const currentMinFilter = texture.minFilter; // Avoid blurred poles
  7420. if (texture.minFilter === LinearMipmapLinearFilter) texture.minFilter = LinearFilter;
  7421. const camera = new CubeCamera(1, 10, this);
  7422. camera.update(renderer, mesh);
  7423. texture.minFilter = currentMinFilter;
  7424. mesh.geometry.dispose();
  7425. mesh.material.dispose();
  7426. return this;
  7427. }
  7428. clear(renderer, color, depth, stencil) {
  7429. const currentRenderTarget = renderer.getRenderTarget();
  7430. for (let i = 0; i < 6; i++) {
  7431. renderer.setRenderTarget(this, i);
  7432. renderer.clear(color, depth, stencil);
  7433. }
  7434. renderer.setRenderTarget(currentRenderTarget);
  7435. }
  7436. }
  7437. WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
  7438. const _vector1 = /*@__PURE__*/new Vector3();
  7439. const _vector2 = /*@__PURE__*/new Vector3();
  7440. const _normalMatrix = /*@__PURE__*/new Matrix3();
  7441. class Plane {
  7442. constructor(normal = new Vector3(1, 0, 0), constant = 0) {
  7443. // normal is assumed to be normalized
  7444. this.normal = normal;
  7445. this.constant = constant;
  7446. }
  7447. set(normal, constant) {
  7448. this.normal.copy(normal);
  7449. this.constant = constant;
  7450. return this;
  7451. }
  7452. setComponents(x, y, z, w) {
  7453. this.normal.set(x, y, z);
  7454. this.constant = w;
  7455. return this;
  7456. }
  7457. setFromNormalAndCoplanarPoint(normal, point) {
  7458. this.normal.copy(normal);
  7459. this.constant = -point.dot(this.normal);
  7460. return this;
  7461. }
  7462. setFromCoplanarPoints(a, b, c) {
  7463. const normal = _vector1.subVectors(c, b).cross(_vector2.subVectors(a, b)).normalize(); // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7464. this.setFromNormalAndCoplanarPoint(normal, a);
  7465. return this;
  7466. }
  7467. copy(plane) {
  7468. this.normal.copy(plane.normal);
  7469. this.constant = plane.constant;
  7470. return this;
  7471. }
  7472. normalize() {
  7473. // Note: will lead to a divide by zero if the plane is invalid.
  7474. const inverseNormalLength = 1.0 / this.normal.length();
  7475. this.normal.multiplyScalar(inverseNormalLength);
  7476. this.constant *= inverseNormalLength;
  7477. return this;
  7478. }
  7479. negate() {
  7480. this.constant *= -1;
  7481. this.normal.negate();
  7482. return this;
  7483. }
  7484. distanceToPoint(point) {
  7485. return this.normal.dot(point) + this.constant;
  7486. }
  7487. distanceToSphere(sphere) {
  7488. return this.distanceToPoint(sphere.center) - sphere.radius;
  7489. }
  7490. projectPoint(point, target) {
  7491. return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
  7492. }
  7493. intersectLine(line, target) {
  7494. const direction = line.delta(_vector1);
  7495. const denominator = this.normal.dot(direction);
  7496. if (denominator === 0) {
  7497. // line is coplanar, return origin
  7498. if (this.distanceToPoint(line.start) === 0) {
  7499. return target.copy(line.start);
  7500. } // Unsure if this is the correct method to handle this case.
  7501. return null;
  7502. }
  7503. const t = -(line.start.dot(this.normal) + this.constant) / denominator;
  7504. if (t < 0 || t > 1) {
  7505. return null;
  7506. }
  7507. return target.copy(direction).multiplyScalar(t).add(line.start);
  7508. }
  7509. intersectsLine(line) {
  7510. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7511. const startSign = this.distanceToPoint(line.start);
  7512. const endSign = this.distanceToPoint(line.end);
  7513. return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
  7514. }
  7515. intersectsBox(box) {
  7516. return box.intersectsPlane(this);
  7517. }
  7518. intersectsSphere(sphere) {
  7519. return sphere.intersectsPlane(this);
  7520. }
  7521. coplanarPoint(target) {
  7522. return target.copy(this.normal).multiplyScalar(-this.constant);
  7523. }
  7524. applyMatrix4(matrix, optionalNormalMatrix) {
  7525. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
  7526. const referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
  7527. const normal = this.normal.applyMatrix3(normalMatrix).normalize();
  7528. this.constant = -referencePoint.dot(normal);
  7529. return this;
  7530. }
  7531. translate(offset) {
  7532. this.constant -= offset.dot(this.normal);
  7533. return this;
  7534. }
  7535. equals(plane) {
  7536. return plane.normal.equals(this.normal) && plane.constant === this.constant;
  7537. }
  7538. clone() {
  7539. return new this.constructor().copy(this);
  7540. }
  7541. }
  7542. Plane.prototype.isPlane = true;
  7543. const _sphere$2 = /*@__PURE__*/new Sphere();
  7544. const _vector$7 = /*@__PURE__*/new Vector3();
  7545. class Frustum {
  7546. constructor(p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane()) {
  7547. this.planes = [p0, p1, p2, p3, p4, p5];
  7548. }
  7549. set(p0, p1, p2, p3, p4, p5) {
  7550. const planes = this.planes;
  7551. planes[0].copy(p0);
  7552. planes[1].copy(p1);
  7553. planes[2].copy(p2);
  7554. planes[3].copy(p3);
  7555. planes[4].copy(p4);
  7556. planes[5].copy(p5);
  7557. return this;
  7558. }
  7559. copy(frustum) {
  7560. const planes = this.planes;
  7561. for (let i = 0; i < 6; i++) {
  7562. planes[i].copy(frustum.planes[i]);
  7563. }
  7564. return this;
  7565. }
  7566. setFromProjectionMatrix(m) {
  7567. const planes = this.planes;
  7568. const me = m.elements;
  7569. const me0 = me[0],
  7570. me1 = me[1],
  7571. me2 = me[2],
  7572. me3 = me[3];
  7573. const me4 = me[4],
  7574. me5 = me[5],
  7575. me6 = me[6],
  7576. me7 = me[7];
  7577. const me8 = me[8],
  7578. me9 = me[9],
  7579. me10 = me[10],
  7580. me11 = me[11];
  7581. const me12 = me[12],
  7582. me13 = me[13],
  7583. me14 = me[14],
  7584. me15 = me[15];
  7585. planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
  7586. planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
  7587. planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
  7588. planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
  7589. planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
  7590. planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
  7591. return this;
  7592. }
  7593. intersectsObject(object) {
  7594. const geometry = object.geometry;
  7595. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  7596. _sphere$2.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
  7597. return this.intersectsSphere(_sphere$2);
  7598. }
  7599. intersectsSprite(sprite) {
  7600. _sphere$2.center.set(0, 0, 0);
  7601. _sphere$2.radius = 0.7071067811865476;
  7602. _sphere$2.applyMatrix4(sprite.matrixWorld);
  7603. return this.intersectsSphere(_sphere$2);
  7604. }
  7605. intersectsSphere(sphere) {
  7606. const planes = this.planes;
  7607. const center = sphere.center;
  7608. const negRadius = -sphere.radius;
  7609. for (let i = 0; i < 6; i++) {
  7610. const distance = planes[i].distanceToPoint(center);
  7611. if (distance < negRadius) {
  7612. return false;
  7613. }
  7614. }
  7615. return true;
  7616. }
  7617. intersectsBox(box) {
  7618. const planes = this.planes;
  7619. for (let i = 0; i < 6; i++) {
  7620. const plane = planes[i]; // corner at max distance
  7621. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7622. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7623. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7624. if (plane.distanceToPoint(_vector$7) < 0) {
  7625. return false;
  7626. }
  7627. }
  7628. return true;
  7629. }
  7630. containsPoint(point) {
  7631. const planes = this.planes;
  7632. for (let i = 0; i < 6; i++) {
  7633. if (planes[i].distanceToPoint(point) < 0) {
  7634. return false;
  7635. }
  7636. }
  7637. return true;
  7638. }
  7639. clone() {
  7640. return new this.constructor().copy(this);
  7641. }
  7642. }
  7643. function WebGLAnimation() {
  7644. let context = null;
  7645. let isAnimating = false;
  7646. let animationLoop = null;
  7647. let requestId = null;
  7648. function onAnimationFrame(time, frame) {
  7649. animationLoop(time, frame);
  7650. requestId = context.requestAnimationFrame(onAnimationFrame);
  7651. }
  7652. return {
  7653. start: function () {
  7654. if (isAnimating === true) return;
  7655. if (animationLoop === null) return;
  7656. requestId = context.requestAnimationFrame(onAnimationFrame);
  7657. isAnimating = true;
  7658. },
  7659. stop: function () {
  7660. context.cancelAnimationFrame(requestId);
  7661. isAnimating = false;
  7662. },
  7663. setAnimationLoop: function (callback) {
  7664. animationLoop = callback;
  7665. },
  7666. setContext: function (value) {
  7667. context = value;
  7668. }
  7669. };
  7670. }
  7671. function WebGLAttributes(gl, capabilities) {
  7672. const isWebGL2 = capabilities.isWebGL2;
  7673. const buffers = new WeakMap();
  7674. function createBuffer(attribute, bufferType) {
  7675. const array = attribute.array;
  7676. const usage = attribute.usage;
  7677. const buffer = gl.createBuffer();
  7678. gl.bindBuffer(bufferType, buffer);
  7679. gl.bufferData(bufferType, array, usage);
  7680. attribute.onUploadCallback();
  7681. let type = gl.FLOAT;
  7682. if (array instanceof Float32Array) {
  7683. type = gl.FLOAT;
  7684. } else if (array instanceof Float64Array) {
  7685. console.warn('THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.');
  7686. } else if (array instanceof Uint16Array) {
  7687. if (attribute.isFloat16BufferAttribute) {
  7688. if (isWebGL2) {
  7689. type = gl.HALF_FLOAT;
  7690. } else {
  7691. console.warn('THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.');
  7692. }
  7693. } else {
  7694. type = gl.UNSIGNED_SHORT;
  7695. }
  7696. } else if (array instanceof Int16Array) {
  7697. type = gl.SHORT;
  7698. } else if (array instanceof Uint32Array) {
  7699. type = gl.UNSIGNED_INT;
  7700. } else if (array instanceof Int32Array) {
  7701. type = gl.INT;
  7702. } else if (array instanceof Int8Array) {
  7703. type = gl.BYTE;
  7704. } else if (array instanceof Uint8Array) {
  7705. type = gl.UNSIGNED_BYTE;
  7706. } else if (array instanceof Uint8ClampedArray) {
  7707. type = gl.UNSIGNED_BYTE;
  7708. }
  7709. return {
  7710. buffer: buffer,
  7711. type: type,
  7712. bytesPerElement: array.BYTES_PER_ELEMENT,
  7713. version: attribute.version
  7714. };
  7715. }
  7716. function updateBuffer(buffer, attribute, bufferType) {
  7717. const array = attribute.array;
  7718. const updateRange = attribute.updateRange;
  7719. gl.bindBuffer(bufferType, buffer);
  7720. if (updateRange.count === -1) {
  7721. // Not using update ranges
  7722. gl.bufferSubData(bufferType, 0, array);
  7723. } else {
  7724. if (isWebGL2) {
  7725. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array, updateRange.offset, updateRange.count);
  7726. } else {
  7727. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
  7728. }
  7729. updateRange.count = -1; // reset range
  7730. }
  7731. } //
  7732. function get(attribute) {
  7733. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7734. return buffers.get(attribute);
  7735. }
  7736. function remove(attribute) {
  7737. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7738. const data = buffers.get(attribute);
  7739. if (data) {
  7740. gl.deleteBuffer(data.buffer);
  7741. buffers.delete(attribute);
  7742. }
  7743. }
  7744. function update(attribute, bufferType) {
  7745. if (attribute.isGLBufferAttribute) {
  7746. const cached = buffers.get(attribute);
  7747. if (!cached || cached.version < attribute.version) {
  7748. buffers.set(attribute, {
  7749. buffer: attribute.buffer,
  7750. type: attribute.type,
  7751. bytesPerElement: attribute.elementSize,
  7752. version: attribute.version
  7753. });
  7754. }
  7755. return;
  7756. }
  7757. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7758. const data = buffers.get(attribute);
  7759. if (data === undefined) {
  7760. buffers.set(attribute, createBuffer(attribute, bufferType));
  7761. } else if (data.version < attribute.version) {
  7762. updateBuffer(data.buffer, attribute, bufferType);
  7763. data.version = attribute.version;
  7764. }
  7765. }
  7766. return {
  7767. get: get,
  7768. remove: remove,
  7769. update: update
  7770. };
  7771. }
  7772. class PlaneGeometry extends BufferGeometry {
  7773. constructor(width = 1, height = 1, widthSegments = 1, heightSegments = 1) {
  7774. super();
  7775. this.type = 'PlaneGeometry';
  7776. this.parameters = {
  7777. width: width,
  7778. height: height,
  7779. widthSegments: widthSegments,
  7780. heightSegments: heightSegments
  7781. };
  7782. const width_half = width / 2;
  7783. const height_half = height / 2;
  7784. const gridX = Math.floor(widthSegments);
  7785. const gridY = Math.floor(heightSegments);
  7786. const gridX1 = gridX + 1;
  7787. const gridY1 = gridY + 1;
  7788. const segment_width = width / gridX;
  7789. const segment_height = height / gridY; //
  7790. const indices = [];
  7791. const vertices = [];
  7792. const normals = [];
  7793. const uvs = [];
  7794. for (let iy = 0; iy < gridY1; iy++) {
  7795. const y = iy * segment_height - height_half;
  7796. for (let ix = 0; ix < gridX1; ix++) {
  7797. const x = ix * segment_width - width_half;
  7798. vertices.push(x, -y, 0);
  7799. normals.push(0, 0, 1);
  7800. uvs.push(ix / gridX);
  7801. uvs.push(1 - iy / gridY);
  7802. }
  7803. }
  7804. for (let iy = 0; iy < gridY; iy++) {
  7805. for (let ix = 0; ix < gridX; ix++) {
  7806. const a = ix + gridX1 * iy;
  7807. const b = ix + gridX1 * (iy + 1);
  7808. const c = ix + 1 + gridX1 * (iy + 1);
  7809. const d = ix + 1 + gridX1 * iy;
  7810. indices.push(a, b, d);
  7811. indices.push(b, c, d);
  7812. }
  7813. }
  7814. this.setIndex(indices);
  7815. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  7816. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  7817. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  7818. }
  7819. static fromJSON(data) {
  7820. return new PlaneGeometry(data.width, data.height, data.widthSegments, data.heightSegments);
  7821. }
  7822. }
  7823. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  7824. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7825. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif";
  7826. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  7827. var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif";
  7828. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7829. var begin_vertex = "vec3 transformed = vec3( position );";
  7830. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  7831. var bsdfs = "vec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif";
  7832. 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";
  7833. 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";
  7834. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  7835. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  7836. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  7837. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7838. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7839. 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";
  7840. 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";
  7841. var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}";
  7842. 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 ) + 0.5;\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\treturn texture2D( envMap, uv ).rgb;\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";
  7843. 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";
  7844. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  7845. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  7846. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  7847. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  7848. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  7849. var encodings_pars_fragment = "vec4 LinearToLinear( in vec4 value ) {\n\treturn value;\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}";
  7850. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t\tenvColor = envMapTexelToLinear( envColor );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";
  7851. var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\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";
  7852. 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";
  7853. 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";
  7854. 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";
  7855. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  7856. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  7857. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif";
  7858. var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif";
  7859. 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 vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t#endif\n}";
  7860. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tlightMapIrradiance *= PI;\n\t#endif\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
  7861. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7862. 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.normal );\n#ifdef DOUBLE_SIDED\n\tvIndirectBack += getAmbientLightIrradiance( ambientLightColor );\n\tvIndirectBack += getLightProbeIrradiance( lightProbe, backGeometry.normal );\n#endif\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointLightInfo( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotLightInfo( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalLightInfo( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry.normal );\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif";
  7863. 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 vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tif ( cutoffDistance > 0.0 ) {\n\t\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t}\n\t\treturn distanceFalloff;\n\t#else\n\t\tif ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\t\treturn pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t\t}\n\t\treturn 1.0;\n\t#endif\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif";
  7864. var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 reflectVec;\n\t\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\t\treflectVec = reflect( - viewDir, normal );\n\t\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\t#else\n\t\t\t\treflectVec = refract( - viewDir, normal, refractionRatio );\n\t\t\t#endif\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n#endif";
  7865. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  7866. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n#define Material_LightProbeLOD( material )\t(0)";
  7867. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  7868. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)";
  7869. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\t#ifdef SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULARINTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a;\n\t\t#endif\n\t\t#ifdef USE_SPECULARCOLORMAP\n\t\t\tspecularColorFactor *= specularColorMapTexelToLinear( texture2D( specularColorMap, vUv ) ).rgb;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( ior - 1.0 ) / ( ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tmaterial.sheenColor *= sheenColorMapTexelToLinear( texture2D( sheenColorMap, vUv ) ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vUv ).a;\n\t#endif\n#endif";
  7870. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec3 sheenSpecular = vec3( 0.0 );\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\tvec3 FssEss = specularColor * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecular += ccIrradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.clearcoatNormal, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * BRDF_Sheen( directLight.direction, geometry.viewDir, geometry.normal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.roughness );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * material.sheenColor * IBLSheenBRDF( geometry.normal, geometry.viewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tcomputeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}";
  7871. var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef USE_CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry.normal );\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.normal );\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";
  7872. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometry.normal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness );\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif";
  7873. 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";
  7874. 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";
  7875. 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";
  7876. 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";
  7877. 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";
  7878. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  7879. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  7880. 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";
  7881. 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";
  7882. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  7883. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  7884. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] > 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1, 2 ) * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\t\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\t\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\t\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n\t#endif\n#endif";
  7885. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\tuniform sampler2DArray morphTargetsTexture;\n\t\tuniform vec2 morphTargetsTextureSize;\n\t\tvec3 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset, const in int stride ) {\n\t\t\tfloat texelIndex = float( vertexIndex * stride + offset );\n\t\t\tfloat y = floor( texelIndex / morphTargetsTextureSize.x );\n\t\t\tfloat x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tvec3 morphUV = vec3( ( x + 0.5 ) / morphTargetsTextureSize.x, y / morphTargetsTextureSize.y, morphTargetIndex );\n\t\t\treturn texture( morphTargetsTexture, morphUV ).xyz;\n\t\t}\n\t#else\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\tuniform float morphTargetInfluences[ 8 ];\n\t\t#else\n\t\t\tuniform float morphTargetInfluences[ 4 ];\n\t\t#endif\n\t#endif\n#endif";
  7886. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\t#ifndef USE_MORPHNORMALS\n\t\t\t\tif ( morphTargetInfluences[ i ] > 0.0 ) transformed += getMorph( gl_VertexID, i, 0, 1 ) * morphTargetInfluences[ i ];\n\t\t\t#else\n\t\t\t\tif ( morphTargetInfluences[ i ] > 0.0 ) transformed += getMorph( gl_VertexID, i, 0, 2 ) * morphTargetInfluences[ i ];\n\t\t\t#endif\n\t\t}\n\t#else\n\t\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\t\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\t\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\t\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t\t#endif\n\t#endif\n#endif";
  7887. 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;";
  7888. 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";
  7889. var normal_pars_fragment = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif";
  7890. var normal_pars_vertex = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif";
  7891. var normal_vertex = "#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif";
  7892. 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";
  7893. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  7894. 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";
  7895. 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";
  7896. var output_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= transmissionAlpha + 0.1;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );";
  7897. 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}";
  7898. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  7899. 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;";
  7900. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  7901. 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";
  7902. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  7903. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  7904. 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";
  7905. 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";
  7906. 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";
  7907. 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}";
  7908. 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";
  7909. 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";
  7910. 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";
  7911. 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";
  7912. 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";
  7913. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  7914. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  7915. 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; }";
  7916. var transmission_fragment = "#ifdef USE_TRANSMISSION\n\tfloat transmissionAlpha = 1.0;\n\tfloat transmissionFactor = transmission;\n\tfloat thicknessFactor = thickness;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\ttransmissionFactor *= texture2D( transmissionMap, vUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tthicknessFactor *= texture2D( thicknessMap, vUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmission = getIBLVolumeRefraction(\n\t\tn, v, roughnessFactor, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, ior, thicknessFactor,\n\t\tattenuationColor, attenuationDistance );\n\ttotalDiffuse = mix( totalDiffuse, transmission.rgb, transmissionFactor );\n\ttransmissionAlpha = mix( transmissionAlpha, transmission.a, transmissionFactor );\n#endif";
  7917. var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tvec3 getVolumeTransmissionRay( vec3 n, vec3 v, float thickness, float ior, mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( float roughness, float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( vec2 fragCoord, float roughness, float ior ) {\n\t\tfloat framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\treturn texture2DLodEXT( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#else\n\t\t\treturn texture2D( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#endif\n\t}\n\tvec3 applyVolumeAttenuation( vec3 radiance, float transmissionDistance, vec3 attenuationColor, float attenuationDistance ) {\n\t\tif ( attenuationDistance == 0.0 ) {\n\t\t\treturn radiance;\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance * radiance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( vec3 n, vec3 v, float roughness, vec3 diffuseColor, vec3 specularColor, float specularF90,\n\t\tvec3 position, mat4 modelMatrix, mat4 viewMatrix, mat4 projMatrix, float ior, float thickness,\n\t\tvec3 attenuationColor, float attenuationDistance ) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\tvec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );\n\t}\n#endif";
  7918. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  7919. 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";
  7920. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  7921. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  7922. 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";
  7923. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  7924. 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";
  7925. const vertex$g = "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}";
  7926. const fragment$g = "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}";
  7927. const vertex$f = "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}";
  7928. const fragment$f = "#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}";
  7929. const vertex$e = "#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}";
  7930. const fragment$e = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}";
  7931. const vertex$d = "#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}";
  7932. const fragment$d = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}";
  7933. const vertex$c = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}";
  7934. const fragment$c = "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}";
  7935. const vertex$b = "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}";
  7936. const fragment$b = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  7937. const vertex$a = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinbase_vertex>\n\t\t#include <skinnormal_vertex>\n\t\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";
  7938. const fragment$a = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7939. const vertex$9 = "#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}";
  7940. const fragment$9 = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack;\n\t#else\n\t\treflectedLight.indirectDiffuse += vIndirectFront;\n\t#endif\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7941. const vertex$8 = "#define MATCAP\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";
  7942. const fragment$8 = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t\tmatcapColor = matcapTexelToLinear( matcapColor );\n\t#else\n\t\tvec4 matcapColor = vec4( 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7943. const vertex$7 = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
  7944. const fragment$7 = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}";
  7945. const vertex$6 = "#define PHONG\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7946. const fragment$6 = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7947. const vertex$5 = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}";
  7948. const fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULARINTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n\t#ifdef USE_SPECULARCOLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_physical_pars_fragment>\n#include <transmission_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include <transmission_fragment>\n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecular;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + clearcoatSpecular * material.clearcoat;\n\t#endif\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7949. const vertex$4 = "#define TOON\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7950. const fragment$4 = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7951. const vertex$3 = "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}";
  7952. const fragment$3 = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  7953. const vertex$2 = "#include <common>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\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 <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7954. const fragment$2 = "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}";
  7955. const vertex$1 = "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}";
  7956. const fragment$1 = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  7957. const ShaderChunk = {
  7958. alphamap_fragment: alphamap_fragment,
  7959. alphamap_pars_fragment: alphamap_pars_fragment,
  7960. alphatest_fragment: alphatest_fragment,
  7961. alphatest_pars_fragment: alphatest_pars_fragment,
  7962. aomap_fragment: aomap_fragment,
  7963. aomap_pars_fragment: aomap_pars_fragment,
  7964. begin_vertex: begin_vertex,
  7965. beginnormal_vertex: beginnormal_vertex,
  7966. bsdfs: bsdfs,
  7967. bumpmap_pars_fragment: bumpmap_pars_fragment,
  7968. clipping_planes_fragment: clipping_planes_fragment,
  7969. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  7970. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  7971. clipping_planes_vertex: clipping_planes_vertex,
  7972. color_fragment: color_fragment,
  7973. color_pars_fragment: color_pars_fragment,
  7974. color_pars_vertex: color_pars_vertex,
  7975. color_vertex: color_vertex,
  7976. common: common,
  7977. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  7978. defaultnormal_vertex: defaultnormal_vertex,
  7979. displacementmap_pars_vertex: displacementmap_pars_vertex,
  7980. displacementmap_vertex: displacementmap_vertex,
  7981. emissivemap_fragment: emissivemap_fragment,
  7982. emissivemap_pars_fragment: emissivemap_pars_fragment,
  7983. encodings_fragment: encodings_fragment,
  7984. encodings_pars_fragment: encodings_pars_fragment,
  7985. envmap_fragment: envmap_fragment,
  7986. envmap_common_pars_fragment: envmap_common_pars_fragment,
  7987. envmap_pars_fragment: envmap_pars_fragment,
  7988. envmap_pars_vertex: envmap_pars_vertex,
  7989. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  7990. envmap_vertex: envmap_vertex,
  7991. fog_vertex: fog_vertex,
  7992. fog_pars_vertex: fog_pars_vertex,
  7993. fog_fragment: fog_fragment,
  7994. fog_pars_fragment: fog_pars_fragment,
  7995. gradientmap_pars_fragment: gradientmap_pars_fragment,
  7996. lightmap_fragment: lightmap_fragment,
  7997. lightmap_pars_fragment: lightmap_pars_fragment,
  7998. lights_lambert_vertex: lights_lambert_vertex,
  7999. lights_pars_begin: lights_pars_begin,
  8000. lights_toon_fragment: lights_toon_fragment,
  8001. lights_toon_pars_fragment: lights_toon_pars_fragment,
  8002. lights_phong_fragment: lights_phong_fragment,
  8003. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8004. lights_physical_fragment: lights_physical_fragment,
  8005. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8006. lights_fragment_begin: lights_fragment_begin,
  8007. lights_fragment_maps: lights_fragment_maps,
  8008. lights_fragment_end: lights_fragment_end,
  8009. logdepthbuf_fragment: logdepthbuf_fragment,
  8010. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8011. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8012. logdepthbuf_vertex: logdepthbuf_vertex,
  8013. map_fragment: map_fragment,
  8014. map_pars_fragment: map_pars_fragment,
  8015. map_particle_fragment: map_particle_fragment,
  8016. map_particle_pars_fragment: map_particle_pars_fragment,
  8017. metalnessmap_fragment: metalnessmap_fragment,
  8018. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8019. morphnormal_vertex: morphnormal_vertex,
  8020. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8021. morphtarget_vertex: morphtarget_vertex,
  8022. normal_fragment_begin: normal_fragment_begin,
  8023. normal_fragment_maps: normal_fragment_maps,
  8024. normal_pars_fragment: normal_pars_fragment,
  8025. normal_pars_vertex: normal_pars_vertex,
  8026. normal_vertex: normal_vertex,
  8027. normalmap_pars_fragment: normalmap_pars_fragment,
  8028. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8029. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8030. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8031. output_fragment: output_fragment,
  8032. packing: packing,
  8033. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8034. project_vertex: project_vertex,
  8035. dithering_fragment: dithering_fragment,
  8036. dithering_pars_fragment: dithering_pars_fragment,
  8037. roughnessmap_fragment: roughnessmap_fragment,
  8038. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8039. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8040. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8041. shadowmap_vertex: shadowmap_vertex,
  8042. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8043. skinbase_vertex: skinbase_vertex,
  8044. skinning_pars_vertex: skinning_pars_vertex,
  8045. skinning_vertex: skinning_vertex,
  8046. skinnormal_vertex: skinnormal_vertex,
  8047. specularmap_fragment: specularmap_fragment,
  8048. specularmap_pars_fragment: specularmap_pars_fragment,
  8049. tonemapping_fragment: tonemapping_fragment,
  8050. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8051. transmission_fragment: transmission_fragment,
  8052. transmission_pars_fragment: transmission_pars_fragment,
  8053. uv_pars_fragment: uv_pars_fragment,
  8054. uv_pars_vertex: uv_pars_vertex,
  8055. uv_vertex: uv_vertex,
  8056. uv2_pars_fragment: uv2_pars_fragment,
  8057. uv2_pars_vertex: uv2_pars_vertex,
  8058. uv2_vertex: uv2_vertex,
  8059. worldpos_vertex: worldpos_vertex,
  8060. background_vert: vertex$g,
  8061. background_frag: fragment$g,
  8062. cube_vert: vertex$f,
  8063. cube_frag: fragment$f,
  8064. depth_vert: vertex$e,
  8065. depth_frag: fragment$e,
  8066. distanceRGBA_vert: vertex$d,
  8067. distanceRGBA_frag: fragment$d,
  8068. equirect_vert: vertex$c,
  8069. equirect_frag: fragment$c,
  8070. linedashed_vert: vertex$b,
  8071. linedashed_frag: fragment$b,
  8072. meshbasic_vert: vertex$a,
  8073. meshbasic_frag: fragment$a,
  8074. meshlambert_vert: vertex$9,
  8075. meshlambert_frag: fragment$9,
  8076. meshmatcap_vert: vertex$8,
  8077. meshmatcap_frag: fragment$8,
  8078. meshnormal_vert: vertex$7,
  8079. meshnormal_frag: fragment$7,
  8080. meshphong_vert: vertex$6,
  8081. meshphong_frag: fragment$6,
  8082. meshphysical_vert: vertex$5,
  8083. meshphysical_frag: fragment$5,
  8084. meshtoon_vert: vertex$4,
  8085. meshtoon_frag: fragment$4,
  8086. points_vert: vertex$3,
  8087. points_frag: fragment$3,
  8088. shadow_vert: vertex$2,
  8089. shadow_frag: fragment$2,
  8090. sprite_vert: vertex$1,
  8091. sprite_frag: fragment$1
  8092. };
  8093. /**
  8094. * Uniforms library for shared webgl shaders
  8095. */
  8096. const UniformsLib = {
  8097. common: {
  8098. diffuse: {
  8099. value: new Color(0xffffff)
  8100. },
  8101. opacity: {
  8102. value: 1.0
  8103. },
  8104. map: {
  8105. value: null
  8106. },
  8107. uvTransform: {
  8108. value: new Matrix3()
  8109. },
  8110. uv2Transform: {
  8111. value: new Matrix3()
  8112. },
  8113. alphaMap: {
  8114. value: null
  8115. },
  8116. alphaTest: {
  8117. value: 0
  8118. }
  8119. },
  8120. specularmap: {
  8121. specularMap: {
  8122. value: null
  8123. }
  8124. },
  8125. envmap: {
  8126. envMap: {
  8127. value: null
  8128. },
  8129. flipEnvMap: {
  8130. value: -1
  8131. },
  8132. reflectivity: {
  8133. value: 1.0
  8134. },
  8135. // basic, lambert, phong
  8136. ior: {
  8137. value: 1.5
  8138. },
  8139. // standard, physical
  8140. refractionRatio: {
  8141. value: 0.98
  8142. }
  8143. },
  8144. aomap: {
  8145. aoMap: {
  8146. value: null
  8147. },
  8148. aoMapIntensity: {
  8149. value: 1
  8150. }
  8151. },
  8152. lightmap: {
  8153. lightMap: {
  8154. value: null
  8155. },
  8156. lightMapIntensity: {
  8157. value: 1
  8158. }
  8159. },
  8160. emissivemap: {
  8161. emissiveMap: {
  8162. value: null
  8163. }
  8164. },
  8165. bumpmap: {
  8166. bumpMap: {
  8167. value: null
  8168. },
  8169. bumpScale: {
  8170. value: 1
  8171. }
  8172. },
  8173. normalmap: {
  8174. normalMap: {
  8175. value: null
  8176. },
  8177. normalScale: {
  8178. value: new Vector2(1, 1)
  8179. }
  8180. },
  8181. displacementmap: {
  8182. displacementMap: {
  8183. value: null
  8184. },
  8185. displacementScale: {
  8186. value: 1
  8187. },
  8188. displacementBias: {
  8189. value: 0
  8190. }
  8191. },
  8192. roughnessmap: {
  8193. roughnessMap: {
  8194. value: null
  8195. }
  8196. },
  8197. metalnessmap: {
  8198. metalnessMap: {
  8199. value: null
  8200. }
  8201. },
  8202. gradientmap: {
  8203. gradientMap: {
  8204. value: null
  8205. }
  8206. },
  8207. fog: {
  8208. fogDensity: {
  8209. value: 0.00025
  8210. },
  8211. fogNear: {
  8212. value: 1
  8213. },
  8214. fogFar: {
  8215. value: 2000
  8216. },
  8217. fogColor: {
  8218. value: new Color(0xffffff)
  8219. }
  8220. },
  8221. lights: {
  8222. ambientLightColor: {
  8223. value: []
  8224. },
  8225. lightProbe: {
  8226. value: []
  8227. },
  8228. directionalLights: {
  8229. value: [],
  8230. properties: {
  8231. direction: {},
  8232. color: {}
  8233. }
  8234. },
  8235. directionalLightShadows: {
  8236. value: [],
  8237. properties: {
  8238. shadowBias: {},
  8239. shadowNormalBias: {},
  8240. shadowRadius: {},
  8241. shadowMapSize: {}
  8242. }
  8243. },
  8244. directionalShadowMap: {
  8245. value: []
  8246. },
  8247. directionalShadowMatrix: {
  8248. value: []
  8249. },
  8250. spotLights: {
  8251. value: [],
  8252. properties: {
  8253. color: {},
  8254. position: {},
  8255. direction: {},
  8256. distance: {},
  8257. coneCos: {},
  8258. penumbraCos: {},
  8259. decay: {}
  8260. }
  8261. },
  8262. spotLightShadows: {
  8263. value: [],
  8264. properties: {
  8265. shadowBias: {},
  8266. shadowNormalBias: {},
  8267. shadowRadius: {},
  8268. shadowMapSize: {}
  8269. }
  8270. },
  8271. spotShadowMap: {
  8272. value: []
  8273. },
  8274. spotShadowMatrix: {
  8275. value: []
  8276. },
  8277. pointLights: {
  8278. value: [],
  8279. properties: {
  8280. color: {},
  8281. position: {},
  8282. decay: {},
  8283. distance: {}
  8284. }
  8285. },
  8286. pointLightShadows: {
  8287. value: [],
  8288. properties: {
  8289. shadowBias: {},
  8290. shadowNormalBias: {},
  8291. shadowRadius: {},
  8292. shadowMapSize: {},
  8293. shadowCameraNear: {},
  8294. shadowCameraFar: {}
  8295. }
  8296. },
  8297. pointShadowMap: {
  8298. value: []
  8299. },
  8300. pointShadowMatrix: {
  8301. value: []
  8302. },
  8303. hemisphereLights: {
  8304. value: [],
  8305. properties: {
  8306. direction: {},
  8307. skyColor: {},
  8308. groundColor: {}
  8309. }
  8310. },
  8311. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8312. rectAreaLights: {
  8313. value: [],
  8314. properties: {
  8315. color: {},
  8316. position: {},
  8317. width: {},
  8318. height: {}
  8319. }
  8320. },
  8321. ltc_1: {
  8322. value: null
  8323. },
  8324. ltc_2: {
  8325. value: null
  8326. }
  8327. },
  8328. points: {
  8329. diffuse: {
  8330. value: new Color(0xffffff)
  8331. },
  8332. opacity: {
  8333. value: 1.0
  8334. },
  8335. size: {
  8336. value: 1.0
  8337. },
  8338. scale: {
  8339. value: 1.0
  8340. },
  8341. map: {
  8342. value: null
  8343. },
  8344. alphaMap: {
  8345. value: null
  8346. },
  8347. alphaTest: {
  8348. value: 0
  8349. },
  8350. uvTransform: {
  8351. value: new Matrix3()
  8352. }
  8353. },
  8354. sprite: {
  8355. diffuse: {
  8356. value: new Color(0xffffff)
  8357. },
  8358. opacity: {
  8359. value: 1.0
  8360. },
  8361. center: {
  8362. value: new Vector2(0.5, 0.5)
  8363. },
  8364. rotation: {
  8365. value: 0.0
  8366. },
  8367. map: {
  8368. value: null
  8369. },
  8370. alphaMap: {
  8371. value: null
  8372. },
  8373. alphaTest: {
  8374. value: 0
  8375. },
  8376. uvTransform: {
  8377. value: new Matrix3()
  8378. }
  8379. }
  8380. };
  8381. const ShaderLib = {
  8382. basic: {
  8383. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
  8384. vertexShader: ShaderChunk.meshbasic_vert,
  8385. fragmentShader: ShaderChunk.meshbasic_frag
  8386. },
  8387. lambert: {
  8388. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.fog, UniformsLib.lights, {
  8389. emissive: {
  8390. value: new Color(0x000000)
  8391. }
  8392. }]),
  8393. vertexShader: ShaderChunk.meshlambert_vert,
  8394. fragmentShader: ShaderChunk.meshlambert_frag
  8395. },
  8396. phong: {
  8397. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, UniformsLib.lights, {
  8398. emissive: {
  8399. value: new Color(0x000000)
  8400. },
  8401. specular: {
  8402. value: new Color(0x111111)
  8403. },
  8404. shininess: {
  8405. value: 30
  8406. }
  8407. }]),
  8408. vertexShader: ShaderChunk.meshphong_vert,
  8409. fragmentShader: ShaderChunk.meshphong_frag
  8410. },
  8411. standard: {
  8412. 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, {
  8413. emissive: {
  8414. value: new Color(0x000000)
  8415. },
  8416. roughness: {
  8417. value: 1.0
  8418. },
  8419. metalness: {
  8420. value: 0.0
  8421. },
  8422. envMapIntensity: {
  8423. value: 1
  8424. } // temporary
  8425. }]),
  8426. vertexShader: ShaderChunk.meshphysical_vert,
  8427. fragmentShader: ShaderChunk.meshphysical_frag
  8428. },
  8429. toon: {
  8430. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.gradientmap, UniformsLib.fog, UniformsLib.lights, {
  8431. emissive: {
  8432. value: new Color(0x000000)
  8433. }
  8434. }]),
  8435. vertexShader: ShaderChunk.meshtoon_vert,
  8436. fragmentShader: ShaderChunk.meshtoon_frag
  8437. },
  8438. matcap: {
  8439. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
  8440. matcap: {
  8441. value: null
  8442. }
  8443. }]),
  8444. vertexShader: ShaderChunk.meshmatcap_vert,
  8445. fragmentShader: ShaderChunk.meshmatcap_frag
  8446. },
  8447. points: {
  8448. uniforms: mergeUniforms([UniformsLib.points, UniformsLib.fog]),
  8449. vertexShader: ShaderChunk.points_vert,
  8450. fragmentShader: ShaderChunk.points_frag
  8451. },
  8452. dashed: {
  8453. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.fog, {
  8454. scale: {
  8455. value: 1
  8456. },
  8457. dashSize: {
  8458. value: 1
  8459. },
  8460. totalSize: {
  8461. value: 2
  8462. }
  8463. }]),
  8464. vertexShader: ShaderChunk.linedashed_vert,
  8465. fragmentShader: ShaderChunk.linedashed_frag
  8466. },
  8467. depth: {
  8468. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
  8469. vertexShader: ShaderChunk.depth_vert,
  8470. fragmentShader: ShaderChunk.depth_frag
  8471. },
  8472. normal: {
  8473. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
  8474. opacity: {
  8475. value: 1.0
  8476. }
  8477. }]),
  8478. vertexShader: ShaderChunk.meshnormal_vert,
  8479. fragmentShader: ShaderChunk.meshnormal_frag
  8480. },
  8481. sprite: {
  8482. uniforms: mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
  8483. vertexShader: ShaderChunk.sprite_vert,
  8484. fragmentShader: ShaderChunk.sprite_frag
  8485. },
  8486. background: {
  8487. uniforms: {
  8488. uvTransform: {
  8489. value: new Matrix3()
  8490. },
  8491. t2D: {
  8492. value: null
  8493. }
  8494. },
  8495. vertexShader: ShaderChunk.background_vert,
  8496. fragmentShader: ShaderChunk.background_frag
  8497. },
  8498. /* -------------------------------------------------------------------------
  8499. // Cube map shader
  8500. ------------------------------------------------------------------------- */
  8501. cube: {
  8502. uniforms: mergeUniforms([UniformsLib.envmap, {
  8503. opacity: {
  8504. value: 1.0
  8505. }
  8506. }]),
  8507. vertexShader: ShaderChunk.cube_vert,
  8508. fragmentShader: ShaderChunk.cube_frag
  8509. },
  8510. equirect: {
  8511. uniforms: {
  8512. tEquirect: {
  8513. value: null
  8514. }
  8515. },
  8516. vertexShader: ShaderChunk.equirect_vert,
  8517. fragmentShader: ShaderChunk.equirect_frag
  8518. },
  8519. distanceRGBA: {
  8520. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
  8521. referencePosition: {
  8522. value: new Vector3()
  8523. },
  8524. nearDistance: {
  8525. value: 1
  8526. },
  8527. farDistance: {
  8528. value: 1000
  8529. }
  8530. }]),
  8531. vertexShader: ShaderChunk.distanceRGBA_vert,
  8532. fragmentShader: ShaderChunk.distanceRGBA_frag
  8533. },
  8534. shadow: {
  8535. uniforms: mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
  8536. color: {
  8537. value: new Color(0x00000)
  8538. },
  8539. opacity: {
  8540. value: 1.0
  8541. }
  8542. }]),
  8543. vertexShader: ShaderChunk.shadow_vert,
  8544. fragmentShader: ShaderChunk.shadow_frag
  8545. }
  8546. };
  8547. ShaderLib.physical = {
  8548. uniforms: mergeUniforms([ShaderLib.standard.uniforms, {
  8549. clearcoat: {
  8550. value: 0
  8551. },
  8552. clearcoatMap: {
  8553. value: null
  8554. },
  8555. clearcoatRoughness: {
  8556. value: 0
  8557. },
  8558. clearcoatRoughnessMap: {
  8559. value: null
  8560. },
  8561. clearcoatNormalScale: {
  8562. value: new Vector2(1, 1)
  8563. },
  8564. clearcoatNormalMap: {
  8565. value: null
  8566. },
  8567. sheen: {
  8568. value: 0
  8569. },
  8570. sheenColor: {
  8571. value: new Color(0x000000)
  8572. },
  8573. sheenColorMap: {
  8574. value: null
  8575. },
  8576. sheenRoughness: {
  8577. value: 0
  8578. },
  8579. sheenRoughnessMap: {
  8580. value: null
  8581. },
  8582. transmission: {
  8583. value: 0
  8584. },
  8585. transmissionMap: {
  8586. value: null
  8587. },
  8588. transmissionSamplerSize: {
  8589. value: new Vector2()
  8590. },
  8591. transmissionSamplerMap: {
  8592. value: null
  8593. },
  8594. thickness: {
  8595. value: 0
  8596. },
  8597. thicknessMap: {
  8598. value: null
  8599. },
  8600. attenuationDistance: {
  8601. value: 0
  8602. },
  8603. attenuationColor: {
  8604. value: new Color(0x000000)
  8605. },
  8606. specularIntensity: {
  8607. value: 0
  8608. },
  8609. specularIntensityMap: {
  8610. value: null
  8611. },
  8612. specularColor: {
  8613. value: new Color(1, 1, 1)
  8614. },
  8615. specularColorMap: {
  8616. value: null
  8617. }
  8618. }]),
  8619. vertexShader: ShaderChunk.meshphysical_vert,
  8620. fragmentShader: ShaderChunk.meshphysical_frag
  8621. };
  8622. function WebGLBackground(renderer, cubemaps, state, objects, premultipliedAlpha) {
  8623. const clearColor = new Color(0x000000);
  8624. let clearAlpha = 0;
  8625. let planeMesh;
  8626. let boxMesh;
  8627. let currentBackground = null;
  8628. let currentBackgroundVersion = 0;
  8629. let currentTonemapping = null;
  8630. function render(renderList, scene) {
  8631. let forceClear = false;
  8632. let background = scene.isScene === true ? scene.background : null;
  8633. if (background && background.isTexture) {
  8634. background = cubemaps.get(background);
  8635. } // Ignore background in AR
  8636. // TODO: Reconsider this.
  8637. const xr = renderer.xr;
  8638. const session = xr.getSession && xr.getSession();
  8639. if (session && session.environmentBlendMode === 'additive') {
  8640. background = null;
  8641. }
  8642. if (background === null) {
  8643. setClear(clearColor, clearAlpha);
  8644. } else if (background && background.isColor) {
  8645. setClear(background, 1);
  8646. forceClear = true;
  8647. }
  8648. if (renderer.autoClear || forceClear) {
  8649. renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
  8650. }
  8651. if (background && (background.isCubeTexture || background.mapping === CubeUVReflectionMapping)) {
  8652. if (boxMesh === undefined) {
  8653. boxMesh = new Mesh(new BoxGeometry(1, 1, 1), new ShaderMaterial({
  8654. name: 'BackgroundCubeMaterial',
  8655. uniforms: cloneUniforms(ShaderLib.cube.uniforms),
  8656. vertexShader: ShaderLib.cube.vertexShader,
  8657. fragmentShader: ShaderLib.cube.fragmentShader,
  8658. side: BackSide,
  8659. depthTest: false,
  8660. depthWrite: false,
  8661. fog: false
  8662. }));
  8663. boxMesh.geometry.deleteAttribute('normal');
  8664. boxMesh.geometry.deleteAttribute('uv');
  8665. boxMesh.onBeforeRender = function (renderer, scene, camera) {
  8666. this.matrixWorld.copyPosition(camera.matrixWorld);
  8667. }; // enable code injection for non-built-in material
  8668. Object.defineProperty(boxMesh.material, 'envMap', {
  8669. get: function () {
  8670. return this.uniforms.envMap.value;
  8671. }
  8672. });
  8673. objects.update(boxMesh);
  8674. }
  8675. boxMesh.material.uniforms.envMap.value = background;
  8676. boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background.isRenderTargetTexture === false ? -1 : 1;
  8677. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8678. boxMesh.material.needsUpdate = true;
  8679. currentBackground = background;
  8680. currentBackgroundVersion = background.version;
  8681. currentTonemapping = renderer.toneMapping;
  8682. } // push to the pre-sorted opaque render list
  8683. renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
  8684. } else if (background && background.isTexture) {
  8685. if (planeMesh === undefined) {
  8686. planeMesh = new Mesh(new PlaneGeometry(2, 2), new ShaderMaterial({
  8687. name: 'BackgroundMaterial',
  8688. uniforms: cloneUniforms(ShaderLib.background.uniforms),
  8689. vertexShader: ShaderLib.background.vertexShader,
  8690. fragmentShader: ShaderLib.background.fragmentShader,
  8691. side: FrontSide,
  8692. depthTest: false,
  8693. depthWrite: false,
  8694. fog: false
  8695. }));
  8696. planeMesh.geometry.deleteAttribute('normal'); // enable code injection for non-built-in material
  8697. Object.defineProperty(planeMesh.material, 'map', {
  8698. get: function () {
  8699. return this.uniforms.t2D.value;
  8700. }
  8701. });
  8702. objects.update(planeMesh);
  8703. }
  8704. planeMesh.material.uniforms.t2D.value = background;
  8705. if (background.matrixAutoUpdate === true) {
  8706. background.updateMatrix();
  8707. }
  8708. planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
  8709. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8710. planeMesh.material.needsUpdate = true;
  8711. currentBackground = background;
  8712. currentBackgroundVersion = background.version;
  8713. currentTonemapping = renderer.toneMapping;
  8714. } // push to the pre-sorted opaque render list
  8715. renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
  8716. }
  8717. }
  8718. function setClear(color, alpha) {
  8719. state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha);
  8720. }
  8721. return {
  8722. getClearColor: function () {
  8723. return clearColor;
  8724. },
  8725. setClearColor: function (color, alpha = 1) {
  8726. clearColor.set(color);
  8727. clearAlpha = alpha;
  8728. setClear(clearColor, clearAlpha);
  8729. },
  8730. getClearAlpha: function () {
  8731. return clearAlpha;
  8732. },
  8733. setClearAlpha: function (alpha) {
  8734. clearAlpha = alpha;
  8735. setClear(clearColor, clearAlpha);
  8736. },
  8737. render: render
  8738. };
  8739. }
  8740. function WebGLBindingStates(gl, extensions, attributes, capabilities) {
  8741. const maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  8742. const extension = capabilities.isWebGL2 ? null : extensions.get('OES_vertex_array_object');
  8743. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8744. const bindingStates = {};
  8745. const defaultState = createBindingState(null);
  8746. let currentState = defaultState;
  8747. function setup(object, material, program, geometry, index) {
  8748. let updateBuffers = false;
  8749. if (vaoAvailable) {
  8750. const state = getBindingState(geometry, program, material);
  8751. if (currentState !== state) {
  8752. currentState = state;
  8753. bindVertexArrayObject(currentState.object);
  8754. }
  8755. updateBuffers = needsUpdate(geometry, index);
  8756. if (updateBuffers) saveCache(geometry, index);
  8757. } else {
  8758. const wireframe = material.wireframe === true;
  8759. if (currentState.geometry !== geometry.id || currentState.program !== program.id || currentState.wireframe !== wireframe) {
  8760. currentState.geometry = geometry.id;
  8761. currentState.program = program.id;
  8762. currentState.wireframe = wireframe;
  8763. updateBuffers = true;
  8764. }
  8765. }
  8766. if (object.isInstancedMesh === true) {
  8767. updateBuffers = true;
  8768. }
  8769. if (index !== null) {
  8770. attributes.update(index, gl.ELEMENT_ARRAY_BUFFER);
  8771. }
  8772. if (updateBuffers) {
  8773. setupVertexAttributes(object, material, program, geometry);
  8774. if (index !== null) {
  8775. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, attributes.get(index).buffer);
  8776. }
  8777. }
  8778. }
  8779. function createVertexArrayObject() {
  8780. if (capabilities.isWebGL2) return gl.createVertexArray();
  8781. return extension.createVertexArrayOES();
  8782. }
  8783. function bindVertexArrayObject(vao) {
  8784. if (capabilities.isWebGL2) return gl.bindVertexArray(vao);
  8785. return extension.bindVertexArrayOES(vao);
  8786. }
  8787. function deleteVertexArrayObject(vao) {
  8788. if (capabilities.isWebGL2) return gl.deleteVertexArray(vao);
  8789. return extension.deleteVertexArrayOES(vao);
  8790. }
  8791. function getBindingState(geometry, program, material) {
  8792. const wireframe = material.wireframe === true;
  8793. let programMap = bindingStates[geometry.id];
  8794. if (programMap === undefined) {
  8795. programMap = {};
  8796. bindingStates[geometry.id] = programMap;
  8797. }
  8798. let stateMap = programMap[program.id];
  8799. if (stateMap === undefined) {
  8800. stateMap = {};
  8801. programMap[program.id] = stateMap;
  8802. }
  8803. let state = stateMap[wireframe];
  8804. if (state === undefined) {
  8805. state = createBindingState(createVertexArrayObject());
  8806. stateMap[wireframe] = state;
  8807. }
  8808. return state;
  8809. }
  8810. function createBindingState(vao) {
  8811. const newAttributes = [];
  8812. const enabledAttributes = [];
  8813. const attributeDivisors = [];
  8814. for (let i = 0; i < maxVertexAttributes; i++) {
  8815. newAttributes[i] = 0;
  8816. enabledAttributes[i] = 0;
  8817. attributeDivisors[i] = 0;
  8818. }
  8819. return {
  8820. // for backward compatibility on non-VAO support browser
  8821. geometry: null,
  8822. program: null,
  8823. wireframe: false,
  8824. newAttributes: newAttributes,
  8825. enabledAttributes: enabledAttributes,
  8826. attributeDivisors: attributeDivisors,
  8827. object: vao,
  8828. attributes: {},
  8829. index: null
  8830. };
  8831. }
  8832. function needsUpdate(geometry, index) {
  8833. const cachedAttributes = currentState.attributes;
  8834. const geometryAttributes = geometry.attributes;
  8835. let attributesNum = 0;
  8836. for (const key in geometryAttributes) {
  8837. const cachedAttribute = cachedAttributes[key];
  8838. const geometryAttribute = geometryAttributes[key];
  8839. if (cachedAttribute === undefined) return true;
  8840. if (cachedAttribute.attribute !== geometryAttribute) return true;
  8841. if (cachedAttribute.data !== geometryAttribute.data) return true;
  8842. attributesNum++;
  8843. }
  8844. if (currentState.attributesNum !== attributesNum) return true;
  8845. if (currentState.index !== index) return true;
  8846. return false;
  8847. }
  8848. function saveCache(geometry, index) {
  8849. const cache = {};
  8850. const attributes = geometry.attributes;
  8851. let attributesNum = 0;
  8852. for (const key in attributes) {
  8853. const attribute = attributes[key];
  8854. const data = {};
  8855. data.attribute = attribute;
  8856. if (attribute.data) {
  8857. data.data = attribute.data;
  8858. }
  8859. cache[key] = data;
  8860. attributesNum++;
  8861. }
  8862. currentState.attributes = cache;
  8863. currentState.attributesNum = attributesNum;
  8864. currentState.index = index;
  8865. }
  8866. function initAttributes() {
  8867. const newAttributes = currentState.newAttributes;
  8868. for (let i = 0, il = newAttributes.length; i < il; i++) {
  8869. newAttributes[i] = 0;
  8870. }
  8871. }
  8872. function enableAttribute(attribute) {
  8873. enableAttributeAndDivisor(attribute, 0);
  8874. }
  8875. function enableAttributeAndDivisor(attribute, meshPerAttribute) {
  8876. const newAttributes = currentState.newAttributes;
  8877. const enabledAttributes = currentState.enabledAttributes;
  8878. const attributeDivisors = currentState.attributeDivisors;
  8879. newAttributes[attribute] = 1;
  8880. if (enabledAttributes[attribute] === 0) {
  8881. gl.enableVertexAttribArray(attribute);
  8882. enabledAttributes[attribute] = 1;
  8883. }
  8884. if (attributeDivisors[attribute] !== meshPerAttribute) {
  8885. const extension = capabilities.isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
  8886. extension[capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);
  8887. attributeDivisors[attribute] = meshPerAttribute;
  8888. }
  8889. }
  8890. function disableUnusedAttributes() {
  8891. const newAttributes = currentState.newAttributes;
  8892. const enabledAttributes = currentState.enabledAttributes;
  8893. for (let i = 0, il = enabledAttributes.length; i < il; i++) {
  8894. if (enabledAttributes[i] !== newAttributes[i]) {
  8895. gl.disableVertexAttribArray(i);
  8896. enabledAttributes[i] = 0;
  8897. }
  8898. }
  8899. }
  8900. function vertexAttribPointer(index, size, type, normalized, stride, offset) {
  8901. if (capabilities.isWebGL2 === true && (type === gl.INT || type === gl.UNSIGNED_INT)) {
  8902. gl.vertexAttribIPointer(index, size, type, stride, offset);
  8903. } else {
  8904. gl.vertexAttribPointer(index, size, type, normalized, stride, offset);
  8905. }
  8906. }
  8907. function setupVertexAttributes(object, material, program, geometry) {
  8908. if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
  8909. if (extensions.get('ANGLE_instanced_arrays') === null) return;
  8910. }
  8911. initAttributes();
  8912. const geometryAttributes = geometry.attributes;
  8913. const programAttributes = program.getAttributes();
  8914. const materialDefaultAttributeValues = material.defaultAttributeValues;
  8915. for (const name in programAttributes) {
  8916. const programAttribute = programAttributes[name];
  8917. if (programAttribute.location >= 0) {
  8918. let geometryAttribute = geometryAttributes[name];
  8919. if (geometryAttribute === undefined) {
  8920. if (name === 'instanceMatrix' && object.instanceMatrix) geometryAttribute = object.instanceMatrix;
  8921. if (name === 'instanceColor' && object.instanceColor) geometryAttribute = object.instanceColor;
  8922. }
  8923. if (geometryAttribute !== undefined) {
  8924. const normalized = geometryAttribute.normalized;
  8925. const size = geometryAttribute.itemSize;
  8926. const attribute = attributes.get(geometryAttribute); // TODO Attribute may not be available on context restore
  8927. if (attribute === undefined) continue;
  8928. const buffer = attribute.buffer;
  8929. const type = attribute.type;
  8930. const bytesPerElement = attribute.bytesPerElement;
  8931. if (geometryAttribute.isInterleavedBufferAttribute) {
  8932. const data = geometryAttribute.data;
  8933. const stride = data.stride;
  8934. const offset = geometryAttribute.offset;
  8935. if (data && data.isInstancedInterleavedBuffer) {
  8936. for (let i = 0; i < programAttribute.locationSize; i++) {
  8937. enableAttributeAndDivisor(programAttribute.location + i, data.meshPerAttribute);
  8938. }
  8939. if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) {
  8940. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  8941. }
  8942. } else {
  8943. for (let i = 0; i < programAttribute.locationSize; i++) {
  8944. enableAttribute(programAttribute.location + i);
  8945. }
  8946. }
  8947. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8948. for (let i = 0; i < programAttribute.locationSize; i++) {
  8949. vertexAttribPointer(programAttribute.location + i, size / programAttribute.locationSize, type, normalized, stride * bytesPerElement, (offset + size / programAttribute.locationSize * i) * bytesPerElement);
  8950. }
  8951. } else {
  8952. if (geometryAttribute.isInstancedBufferAttribute) {
  8953. for (let i = 0; i < programAttribute.locationSize; i++) {
  8954. enableAttributeAndDivisor(programAttribute.location + i, geometryAttribute.meshPerAttribute);
  8955. }
  8956. if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) {
  8957. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  8958. }
  8959. } else {
  8960. for (let i = 0; i < programAttribute.locationSize; i++) {
  8961. enableAttribute(programAttribute.location + i);
  8962. }
  8963. }
  8964. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8965. for (let i = 0; i < programAttribute.locationSize; i++) {
  8966. vertexAttribPointer(programAttribute.location + i, size / programAttribute.locationSize, type, normalized, size * bytesPerElement, size / programAttribute.locationSize * i * bytesPerElement);
  8967. }
  8968. }
  8969. } else if (materialDefaultAttributeValues !== undefined) {
  8970. const value = materialDefaultAttributeValues[name];
  8971. if (value !== undefined) {
  8972. switch (value.length) {
  8973. case 2:
  8974. gl.vertexAttrib2fv(programAttribute.location, value);
  8975. break;
  8976. case 3:
  8977. gl.vertexAttrib3fv(programAttribute.location, value);
  8978. break;
  8979. case 4:
  8980. gl.vertexAttrib4fv(programAttribute.location, value);
  8981. break;
  8982. default:
  8983. gl.vertexAttrib1fv(programAttribute.location, value);
  8984. }
  8985. }
  8986. }
  8987. }
  8988. }
  8989. disableUnusedAttributes();
  8990. }
  8991. function dispose() {
  8992. reset();
  8993. for (const geometryId in bindingStates) {
  8994. const programMap = bindingStates[geometryId];
  8995. for (const programId in programMap) {
  8996. const stateMap = programMap[programId];
  8997. for (const wireframe in stateMap) {
  8998. deleteVertexArrayObject(stateMap[wireframe].object);
  8999. delete stateMap[wireframe];
  9000. }
  9001. delete programMap[programId];
  9002. }
  9003. delete bindingStates[geometryId];
  9004. }
  9005. }
  9006. function releaseStatesOfGeometry(geometry) {
  9007. if (bindingStates[geometry.id] === undefined) return;
  9008. const programMap = bindingStates[geometry.id];
  9009. for (const programId in programMap) {
  9010. const stateMap = programMap[programId];
  9011. for (const wireframe in stateMap) {
  9012. deleteVertexArrayObject(stateMap[wireframe].object);
  9013. delete stateMap[wireframe];
  9014. }
  9015. delete programMap[programId];
  9016. }
  9017. delete bindingStates[geometry.id];
  9018. }
  9019. function releaseStatesOfProgram(program) {
  9020. for (const geometryId in bindingStates) {
  9021. const programMap = bindingStates[geometryId];
  9022. if (programMap[program.id] === undefined) continue;
  9023. const stateMap = programMap[program.id];
  9024. for (const wireframe in stateMap) {
  9025. deleteVertexArrayObject(stateMap[wireframe].object);
  9026. delete stateMap[wireframe];
  9027. }
  9028. delete programMap[program.id];
  9029. }
  9030. }
  9031. function reset() {
  9032. resetDefaultState();
  9033. if (currentState === defaultState) return;
  9034. currentState = defaultState;
  9035. bindVertexArrayObject(currentState.object);
  9036. } // for backward-compatilibity
  9037. function resetDefaultState() {
  9038. defaultState.geometry = null;
  9039. defaultState.program = null;
  9040. defaultState.wireframe = false;
  9041. }
  9042. return {
  9043. setup: setup,
  9044. reset: reset,
  9045. resetDefaultState: resetDefaultState,
  9046. dispose: dispose,
  9047. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9048. releaseStatesOfProgram: releaseStatesOfProgram,
  9049. initAttributes: initAttributes,
  9050. enableAttribute: enableAttribute,
  9051. disableUnusedAttributes: disableUnusedAttributes
  9052. };
  9053. }
  9054. function WebGLBufferRenderer(gl, extensions, info, capabilities) {
  9055. const isWebGL2 = capabilities.isWebGL2;
  9056. let mode;
  9057. function setMode(value) {
  9058. mode = value;
  9059. }
  9060. function render(start, count) {
  9061. gl.drawArrays(mode, start, count);
  9062. info.update(count, mode, 1);
  9063. }
  9064. function renderInstances(start, count, primcount) {
  9065. if (primcount === 0) return;
  9066. let extension, methodName;
  9067. if (isWebGL2) {
  9068. extension = gl;
  9069. methodName = 'drawArraysInstanced';
  9070. } else {
  9071. extension = extensions.get('ANGLE_instanced_arrays');
  9072. methodName = 'drawArraysInstancedANGLE';
  9073. if (extension === null) {
  9074. console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  9075. return;
  9076. }
  9077. }
  9078. extension[methodName](mode, start, count, primcount);
  9079. info.update(count, mode, primcount);
  9080. } //
  9081. this.setMode = setMode;
  9082. this.render = render;
  9083. this.renderInstances = renderInstances;
  9084. }
  9085. function WebGLCapabilities(gl, extensions, parameters) {
  9086. let maxAnisotropy;
  9087. function getMaxAnisotropy() {
  9088. if (maxAnisotropy !== undefined) return maxAnisotropy;
  9089. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  9090. const extension = extensions.get('EXT_texture_filter_anisotropic');
  9091. maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  9092. } else {
  9093. maxAnisotropy = 0;
  9094. }
  9095. return maxAnisotropy;
  9096. }
  9097. function getMaxPrecision(precision) {
  9098. if (precision === 'highp') {
  9099. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT).precision > 0) {
  9100. return 'highp';
  9101. }
  9102. precision = 'mediump';
  9103. }
  9104. if (precision === 'mediump') {
  9105. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT).precision > 0) {
  9106. return 'mediump';
  9107. }
  9108. }
  9109. return 'lowp';
  9110. }
  9111. const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext || typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext;
  9112. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9113. const maxPrecision = getMaxPrecision(precision);
  9114. if (maxPrecision !== precision) {
  9115. console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
  9116. precision = maxPrecision;
  9117. }
  9118. const drawBuffers = isWebGL2 || extensions.has('WEBGL_draw_buffers');
  9119. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9120. const maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
  9121. const maxVertexTextures = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  9122. const maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
  9123. const maxCubemapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  9124. const maxAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  9125. const maxVertexUniforms = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS);
  9126. const maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS);
  9127. const maxFragmentUniforms = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  9128. const vertexTextures = maxVertexTextures > 0;
  9129. const floatFragmentTextures = isWebGL2 || extensions.has('OES_texture_float');
  9130. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  9131. const maxSamples = isWebGL2 ? gl.getParameter(gl.MAX_SAMPLES) : 0;
  9132. return {
  9133. isWebGL2: isWebGL2,
  9134. drawBuffers: drawBuffers,
  9135. getMaxAnisotropy: getMaxAnisotropy,
  9136. getMaxPrecision: getMaxPrecision,
  9137. precision: precision,
  9138. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9139. maxTextures: maxTextures,
  9140. maxVertexTextures: maxVertexTextures,
  9141. maxTextureSize: maxTextureSize,
  9142. maxCubemapSize: maxCubemapSize,
  9143. maxAttributes: maxAttributes,
  9144. maxVertexUniforms: maxVertexUniforms,
  9145. maxVaryings: maxVaryings,
  9146. maxFragmentUniforms: maxFragmentUniforms,
  9147. vertexTextures: vertexTextures,
  9148. floatFragmentTextures: floatFragmentTextures,
  9149. floatVertexTextures: floatVertexTextures,
  9150. maxSamples: maxSamples
  9151. };
  9152. }
  9153. function WebGLClipping(properties) {
  9154. const scope = this;
  9155. let globalState = null,
  9156. numGlobalPlanes = 0,
  9157. localClippingEnabled = false,
  9158. renderingShadows = false;
  9159. const plane = new Plane(),
  9160. viewNormalMatrix = new Matrix3(),
  9161. uniform = {
  9162. value: null,
  9163. needsUpdate: false
  9164. };
  9165. this.uniform = uniform;
  9166. this.numPlanes = 0;
  9167. this.numIntersection = 0;
  9168. this.init = function (planes, enableLocalClipping, camera) {
  9169. const enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to
  9170. // run another frame in order to reset the state:
  9171. numGlobalPlanes !== 0 || localClippingEnabled;
  9172. localClippingEnabled = enableLocalClipping;
  9173. globalState = projectPlanes(planes, camera, 0);
  9174. numGlobalPlanes = planes.length;
  9175. return enabled;
  9176. };
  9177. this.beginShadows = function () {
  9178. renderingShadows = true;
  9179. projectPlanes(null);
  9180. };
  9181. this.endShadows = function () {
  9182. renderingShadows = false;
  9183. resetGlobalState();
  9184. };
  9185. this.setState = function (material, camera, useCache) {
  9186. const planes = material.clippingPlanes,
  9187. clipIntersection = material.clipIntersection,
  9188. clipShadows = material.clipShadows;
  9189. const materialProperties = properties.get(material);
  9190. if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
  9191. // there's no local clipping
  9192. if (renderingShadows) {
  9193. // there's no global clipping
  9194. projectPlanes(null);
  9195. } else {
  9196. resetGlobalState();
  9197. }
  9198. } else {
  9199. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9200. lGlobal = nGlobal * 4;
  9201. let dstArray = materialProperties.clippingState || null;
  9202. uniform.value = dstArray; // ensure unique state
  9203. dstArray = projectPlanes(planes, camera, lGlobal, useCache);
  9204. for (let i = 0; i !== lGlobal; ++i) {
  9205. dstArray[i] = globalState[i];
  9206. }
  9207. materialProperties.clippingState = dstArray;
  9208. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9209. this.numPlanes += nGlobal;
  9210. }
  9211. };
  9212. function resetGlobalState() {
  9213. if (uniform.value !== globalState) {
  9214. uniform.value = globalState;
  9215. uniform.needsUpdate = numGlobalPlanes > 0;
  9216. }
  9217. scope.numPlanes = numGlobalPlanes;
  9218. scope.numIntersection = 0;
  9219. }
  9220. function projectPlanes(planes, camera, dstOffset, skipTransform) {
  9221. const nPlanes = planes !== null ? planes.length : 0;
  9222. let dstArray = null;
  9223. if (nPlanes !== 0) {
  9224. dstArray = uniform.value;
  9225. if (skipTransform !== true || dstArray === null) {
  9226. const flatSize = dstOffset + nPlanes * 4,
  9227. viewMatrix = camera.matrixWorldInverse;
  9228. viewNormalMatrix.getNormalMatrix(viewMatrix);
  9229. if (dstArray === null || dstArray.length < flatSize) {
  9230. dstArray = new Float32Array(flatSize);
  9231. }
  9232. for (let i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
  9233. plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
  9234. plane.normal.toArray(dstArray, i4);
  9235. dstArray[i4 + 3] = plane.constant;
  9236. }
  9237. }
  9238. uniform.value = dstArray;
  9239. uniform.needsUpdate = true;
  9240. }
  9241. scope.numPlanes = nPlanes;
  9242. scope.numIntersection = 0;
  9243. return dstArray;
  9244. }
  9245. }
  9246. function WebGLCubeMaps(renderer) {
  9247. let cubemaps = new WeakMap();
  9248. function mapTextureMapping(texture, mapping) {
  9249. if (mapping === EquirectangularReflectionMapping) {
  9250. texture.mapping = CubeReflectionMapping;
  9251. } else if (mapping === EquirectangularRefractionMapping) {
  9252. texture.mapping = CubeRefractionMapping;
  9253. }
  9254. return texture;
  9255. }
  9256. function get(texture) {
  9257. if (texture && texture.isTexture && texture.isRenderTargetTexture === false) {
  9258. const mapping = texture.mapping;
  9259. if (mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping) {
  9260. if (cubemaps.has(texture)) {
  9261. const cubemap = cubemaps.get(texture).texture;
  9262. return mapTextureMapping(cubemap, texture.mapping);
  9263. } else {
  9264. const image = texture.image;
  9265. if (image && image.height > 0) {
  9266. const currentRenderTarget = renderer.getRenderTarget();
  9267. const renderTarget = new WebGLCubeRenderTarget(image.height / 2);
  9268. renderTarget.fromEquirectangularTexture(renderer, texture);
  9269. cubemaps.set(texture, renderTarget);
  9270. renderer.setRenderTarget(currentRenderTarget);
  9271. texture.addEventListener('dispose', onTextureDispose);
  9272. return mapTextureMapping(renderTarget.texture, texture.mapping);
  9273. } else {
  9274. // image not yet ready. try the conversion next frame
  9275. return null;
  9276. }
  9277. }
  9278. }
  9279. }
  9280. return texture;
  9281. }
  9282. function onTextureDispose(event) {
  9283. const texture = event.target;
  9284. texture.removeEventListener('dispose', onTextureDispose);
  9285. const cubemap = cubemaps.get(texture);
  9286. if (cubemap !== undefined) {
  9287. cubemaps.delete(texture);
  9288. cubemap.dispose();
  9289. }
  9290. }
  9291. function dispose() {
  9292. cubemaps = new WeakMap();
  9293. }
  9294. return {
  9295. get: get,
  9296. dispose: dispose
  9297. };
  9298. }
  9299. class OrthographicCamera extends Camera {
  9300. constructor(left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000) {
  9301. super();
  9302. this.type = 'OrthographicCamera';
  9303. this.zoom = 1;
  9304. this.view = null;
  9305. this.left = left;
  9306. this.right = right;
  9307. this.top = top;
  9308. this.bottom = bottom;
  9309. this.near = near;
  9310. this.far = far;
  9311. this.updateProjectionMatrix();
  9312. }
  9313. copy(source, recursive) {
  9314. super.copy(source, recursive);
  9315. this.left = source.left;
  9316. this.right = source.right;
  9317. this.top = source.top;
  9318. this.bottom = source.bottom;
  9319. this.near = source.near;
  9320. this.far = source.far;
  9321. this.zoom = source.zoom;
  9322. this.view = source.view === null ? null : Object.assign({}, source.view);
  9323. return this;
  9324. }
  9325. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  9326. if (this.view === null) {
  9327. this.view = {
  9328. enabled: true,
  9329. fullWidth: 1,
  9330. fullHeight: 1,
  9331. offsetX: 0,
  9332. offsetY: 0,
  9333. width: 1,
  9334. height: 1
  9335. };
  9336. }
  9337. this.view.enabled = true;
  9338. this.view.fullWidth = fullWidth;
  9339. this.view.fullHeight = fullHeight;
  9340. this.view.offsetX = x;
  9341. this.view.offsetY = y;
  9342. this.view.width = width;
  9343. this.view.height = height;
  9344. this.updateProjectionMatrix();
  9345. }
  9346. clearViewOffset() {
  9347. if (this.view !== null) {
  9348. this.view.enabled = false;
  9349. }
  9350. this.updateProjectionMatrix();
  9351. }
  9352. updateProjectionMatrix() {
  9353. const dx = (this.right - this.left) / (2 * this.zoom);
  9354. const dy = (this.top - this.bottom) / (2 * this.zoom);
  9355. const cx = (this.right + this.left) / 2;
  9356. const cy = (this.top + this.bottom) / 2;
  9357. let left = cx - dx;
  9358. let right = cx + dx;
  9359. let top = cy + dy;
  9360. let bottom = cy - dy;
  9361. if (this.view !== null && this.view.enabled) {
  9362. const scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom;
  9363. const scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
  9364. left += scaleW * this.view.offsetX;
  9365. right = left + scaleW * this.view.width;
  9366. top -= scaleH * this.view.offsetY;
  9367. bottom = top - scaleH * this.view.height;
  9368. }
  9369. this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);
  9370. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  9371. }
  9372. toJSON(meta) {
  9373. const data = super.toJSON(meta);
  9374. data.object.zoom = this.zoom;
  9375. data.object.left = this.left;
  9376. data.object.right = this.right;
  9377. data.object.top = this.top;
  9378. data.object.bottom = this.bottom;
  9379. data.object.near = this.near;
  9380. data.object.far = this.far;
  9381. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  9382. return data;
  9383. }
  9384. }
  9385. OrthographicCamera.prototype.isOrthographicCamera = true;
  9386. class RawShaderMaterial extends ShaderMaterial {
  9387. constructor(parameters) {
  9388. super(parameters);
  9389. this.type = 'RawShaderMaterial';
  9390. }
  9391. }
  9392. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  9393. const LOD_MIN = 4;
  9394. const LOD_MAX = 8;
  9395. const SIZE_MAX = Math.pow(2, LOD_MAX); // The standard deviations (radians) associated with the extra mips. These are
  9396. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9397. // geometric shadowing function. These sigma values squared must match the
  9398. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9399. const EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582];
  9400. 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
  9401. // samples and exit early, but not recompile the shader.
  9402. const MAX_SAMPLES = 20;
  9403. const ENCODINGS = {
  9404. [LinearEncoding]: 0,
  9405. [sRGBEncoding]: 1
  9406. };
  9407. const _flatCamera = /*@__PURE__*/new OrthographicCamera();
  9408. const {
  9409. _lodPlanes,
  9410. _sizeLods,
  9411. _sigmas
  9412. } = /*@__PURE__*/_createPlanes();
  9413. const _clearColor = /*@__PURE__*/new Color();
  9414. let _oldTarget = null; // Golden Ratio
  9415. const PHI = (1 + Math.sqrt(5)) / 2;
  9416. const INV_PHI = 1 / PHI; // Vertices of a dodecahedron (except the opposites, which represent the
  9417. // same axis), used as axis directions evenly spread on a sphere.
  9418. 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)];
  9419. /**
  9420. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9421. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9422. * blur to be quickly accessed based on material roughness. It is packed into a
  9423. * special CubeUV format that allows us to perform custom interpolation so that
  9424. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9425. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9426. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9427. * higher roughness levels. In this way we maintain resolution to smoothly
  9428. * interpolate diffuse lighting while limiting sampling computation.
  9429. *
  9430. * Paper: Fast, Accurate Image-Based Lighting
  9431. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9432. */
  9433. class PMREMGenerator {
  9434. constructor(renderer) {
  9435. this._renderer = renderer;
  9436. this._pingPongRenderTarget = null;
  9437. this._blurMaterial = _getBlurShader(MAX_SAMPLES);
  9438. this._equirectShader = null;
  9439. this._cubemapShader = null;
  9440. this._compileMaterial(this._blurMaterial);
  9441. }
  9442. /**
  9443. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9444. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9445. * in radians to be applied to the scene before PMREM generation. Optional near
  9446. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9447. * is placed at the origin).
  9448. */
  9449. fromScene(scene, sigma = 0, near = 0.1, far = 100) {
  9450. _oldTarget = this._renderer.getRenderTarget();
  9451. const cubeUVRenderTarget = this._allocateTargets();
  9452. this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget);
  9453. if (sigma > 0) {
  9454. this._blur(cubeUVRenderTarget, 0, 0, sigma);
  9455. }
  9456. this._applyPMREM(cubeUVRenderTarget);
  9457. this._cleanup(cubeUVRenderTarget);
  9458. return cubeUVRenderTarget;
  9459. }
  9460. /**
  9461. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9462. * or HDR. The ideal input image size is 1k (1024 x 512),
  9463. * as this matches best with the 256 x 256 cubemap output.
  9464. */
  9465. fromEquirectangular(equirectangular) {
  9466. return this._fromTexture(equirectangular);
  9467. }
  9468. /**
  9469. * Generates a PMREM from an cubemap texture, which can be either LDR
  9470. * or HDR. The ideal input cube size is 256 x 256,
  9471. * as this matches best with the 256 x 256 cubemap output.
  9472. */
  9473. fromCubemap(cubemap) {
  9474. return this._fromTexture(cubemap);
  9475. }
  9476. /**
  9477. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9478. * your texture's network fetch for increased concurrency.
  9479. */
  9480. compileCubemapShader() {
  9481. if (this._cubemapShader === null) {
  9482. this._cubemapShader = _getCubemapShader();
  9483. this._compileMaterial(this._cubemapShader);
  9484. }
  9485. }
  9486. /**
  9487. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9488. * your texture's network fetch for increased concurrency.
  9489. */
  9490. compileEquirectangularShader() {
  9491. if (this._equirectShader === null) {
  9492. this._equirectShader = _getEquirectShader();
  9493. this._compileMaterial(this._equirectShader);
  9494. }
  9495. }
  9496. /**
  9497. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9498. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9499. * one of them will cause any others to also become unusable.
  9500. */
  9501. dispose() {
  9502. this._blurMaterial.dispose();
  9503. if (this._cubemapShader !== null) this._cubemapShader.dispose();
  9504. if (this._equirectShader !== null) this._equirectShader.dispose();
  9505. for (let i = 0; i < _lodPlanes.length; i++) {
  9506. _lodPlanes[i].dispose();
  9507. }
  9508. } // private interface
  9509. _cleanup(outputTarget) {
  9510. this._pingPongRenderTarget.dispose();
  9511. this._renderer.setRenderTarget(_oldTarget);
  9512. outputTarget.scissorTest = false;
  9513. _setViewport(outputTarget, 0, 0, outputTarget.width, outputTarget.height);
  9514. }
  9515. _fromTexture(texture) {
  9516. _oldTarget = this._renderer.getRenderTarget();
  9517. const cubeUVRenderTarget = this._allocateTargets(texture);
  9518. this._textureToCubeUV(texture, cubeUVRenderTarget);
  9519. this._applyPMREM(cubeUVRenderTarget);
  9520. this._cleanup(cubeUVRenderTarget);
  9521. return cubeUVRenderTarget;
  9522. }
  9523. _allocateTargets(texture) {
  9524. // warning: null texture is valid
  9525. const params = {
  9526. magFilter: LinearFilter,
  9527. minFilter: LinearFilter,
  9528. generateMipmaps: false,
  9529. type: HalfFloatType,
  9530. format: RGBAFormat,
  9531. encoding: LinearEncoding,
  9532. depthBuffer: false
  9533. };
  9534. const cubeUVRenderTarget = _createRenderTarget(params);
  9535. cubeUVRenderTarget.depthBuffer = texture ? false : true;
  9536. this._pingPongRenderTarget = _createRenderTarget(params);
  9537. return cubeUVRenderTarget;
  9538. }
  9539. _compileMaterial(material) {
  9540. const tmpMesh = new Mesh(_lodPlanes[0], material);
  9541. this._renderer.compile(tmpMesh, _flatCamera);
  9542. }
  9543. _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) {
  9544. const fov = 90;
  9545. const aspect = 1;
  9546. const cubeCamera = new PerspectiveCamera(fov, aspect, near, far);
  9547. const upSign = [1, -1, 1, 1, 1, 1];
  9548. const forwardSign = [1, 1, 1, -1, -1, -1];
  9549. const renderer = this._renderer;
  9550. const originalAutoClear = renderer.autoClear;
  9551. const toneMapping = renderer.toneMapping;
  9552. renderer.getClearColor(_clearColor);
  9553. renderer.toneMapping = NoToneMapping;
  9554. renderer.autoClear = false;
  9555. const backgroundMaterial = new MeshBasicMaterial({
  9556. name: 'PMREM.Background',
  9557. side: BackSide,
  9558. depthWrite: false,
  9559. depthTest: false
  9560. });
  9561. const backgroundBox = new Mesh(new BoxGeometry(), backgroundMaterial);
  9562. let useSolidColor = false;
  9563. const background = scene.background;
  9564. if (background) {
  9565. if (background.isColor) {
  9566. backgroundMaterial.color.copy(background);
  9567. scene.background = null;
  9568. useSolidColor = true;
  9569. }
  9570. } else {
  9571. backgroundMaterial.color.copy(_clearColor);
  9572. useSolidColor = true;
  9573. }
  9574. for (let i = 0; i < 6; i++) {
  9575. const col = i % 3;
  9576. if (col == 0) {
  9577. cubeCamera.up.set(0, upSign[i], 0);
  9578. cubeCamera.lookAt(forwardSign[i], 0, 0);
  9579. } else if (col == 1) {
  9580. cubeCamera.up.set(0, 0, upSign[i]);
  9581. cubeCamera.lookAt(0, forwardSign[i], 0);
  9582. } else {
  9583. cubeCamera.up.set(0, upSign[i], 0);
  9584. cubeCamera.lookAt(0, 0, forwardSign[i]);
  9585. }
  9586. _setViewport(cubeUVRenderTarget, col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX);
  9587. renderer.setRenderTarget(cubeUVRenderTarget);
  9588. if (useSolidColor) {
  9589. renderer.render(backgroundBox, cubeCamera);
  9590. }
  9591. renderer.render(scene, cubeCamera);
  9592. }
  9593. backgroundBox.geometry.dispose();
  9594. backgroundBox.material.dispose();
  9595. renderer.toneMapping = toneMapping;
  9596. renderer.autoClear = originalAutoClear;
  9597. scene.background = background;
  9598. }
  9599. _setEncoding(uniform, texture) {
  9600. if (this._renderer.capabilities.isWebGL2 === true && texture.format === RGBAFormat && texture.type === UnsignedByteType && texture.encoding === sRGBEncoding) {
  9601. uniform.value = ENCODINGS[LinearEncoding];
  9602. } else {
  9603. uniform.value = ENCODINGS[texture.encoding];
  9604. }
  9605. }
  9606. _textureToCubeUV(texture, cubeUVRenderTarget) {
  9607. const renderer = this._renderer;
  9608. const isCubeTexture = texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping;
  9609. if (isCubeTexture) {
  9610. if (this._cubemapShader == null) {
  9611. this._cubemapShader = _getCubemapShader();
  9612. }
  9613. } else {
  9614. if (this._equirectShader == null) {
  9615. this._equirectShader = _getEquirectShader();
  9616. }
  9617. }
  9618. const material = isCubeTexture ? this._cubemapShader : this._equirectShader;
  9619. const mesh = new Mesh(_lodPlanes[0], material);
  9620. const uniforms = material.uniforms;
  9621. uniforms['envMap'].value = texture;
  9622. if (!isCubeTexture) {
  9623. uniforms['texelSize'].value.set(1.0 / texture.image.width, 1.0 / texture.image.height);
  9624. }
  9625. this._setEncoding(uniforms['inputEncoding'], texture);
  9626. _setViewport(cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX);
  9627. renderer.setRenderTarget(cubeUVRenderTarget);
  9628. renderer.render(mesh, _flatCamera);
  9629. }
  9630. _applyPMREM(cubeUVRenderTarget) {
  9631. const renderer = this._renderer;
  9632. const autoClear = renderer.autoClear;
  9633. renderer.autoClear = false;
  9634. for (let i = 1; i < TOTAL_LODS; i++) {
  9635. const sigma = Math.sqrt(_sigmas[i] * _sigmas[i] - _sigmas[i - 1] * _sigmas[i - 1]);
  9636. const poleAxis = _axisDirections[(i - 1) % _axisDirections.length];
  9637. this._blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis);
  9638. }
  9639. renderer.autoClear = autoClear;
  9640. }
  9641. /**
  9642. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  9643. * vertically and horizontally, but this breaks down on a cube. Here we apply
  9644. * the blur latitudinally (around the poles), and then longitudinally (towards
  9645. * the poles) to approximate the orthogonally-separable blur. It is least
  9646. * accurate at the poles, but still does a decent job.
  9647. */
  9648. _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) {
  9649. const pingPongRenderTarget = this._pingPongRenderTarget;
  9650. this._halfBlur(cubeUVRenderTarget, pingPongRenderTarget, lodIn, lodOut, sigma, 'latitudinal', poleAxis);
  9651. this._halfBlur(pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, 'longitudinal', poleAxis);
  9652. }
  9653. _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) {
  9654. const renderer = this._renderer;
  9655. const blurMaterial = this._blurMaterial;
  9656. if (direction !== 'latitudinal' && direction !== 'longitudinal') {
  9657. console.error('blur direction must be either latitudinal or longitudinal!');
  9658. } // Number of standard deviations at which to cut off the discrete approximation.
  9659. const STANDARD_DEVIATIONS = 3;
  9660. const blurMesh = new Mesh(_lodPlanes[lodOut], blurMaterial);
  9661. const blurUniforms = blurMaterial.uniforms;
  9662. const pixels = _sizeLods[lodIn] - 1;
  9663. const radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1);
  9664. const sigmaPixels = sigmaRadians / radiansPerPixel;
  9665. const samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES;
  9666. if (samples > MAX_SAMPLES) {
  9667. console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES}`);
  9668. }
  9669. const weights = [];
  9670. let sum = 0;
  9671. for (let i = 0; i < MAX_SAMPLES; ++i) {
  9672. const x = i / sigmaPixels;
  9673. const weight = Math.exp(-x * x / 2);
  9674. weights.push(weight);
  9675. if (i == 0) {
  9676. sum += weight;
  9677. } else if (i < samples) {
  9678. sum += 2 * weight;
  9679. }
  9680. }
  9681. for (let i = 0; i < weights.length; i++) {
  9682. weights[i] = weights[i] / sum;
  9683. }
  9684. blurUniforms['envMap'].value = targetIn.texture;
  9685. blurUniforms['samples'].value = samples;
  9686. blurUniforms['weights'].value = weights;
  9687. blurUniforms['latitudinal'].value = direction === 'latitudinal';
  9688. if (poleAxis) {
  9689. blurUniforms['poleAxis'].value = poleAxis;
  9690. }
  9691. blurUniforms['dTheta'].value = radiansPerPixel;
  9692. blurUniforms['mipInt'].value = LOD_MAX - lodIn;
  9693. const outputSize = _sizeLods[lodOut];
  9694. const x = 3 * Math.max(0, SIZE_MAX - 2 * outputSize);
  9695. const y = (lodOut === 0 ? 0 : 2 * SIZE_MAX) + 2 * outputSize * (lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0);
  9696. _setViewport(targetOut, x, y, 3 * outputSize, 2 * outputSize);
  9697. renderer.setRenderTarget(targetOut);
  9698. renderer.render(blurMesh, _flatCamera);
  9699. }
  9700. }
  9701. function _createPlanes() {
  9702. const _lodPlanes = [];
  9703. const _sizeLods = [];
  9704. const _sigmas = [];
  9705. let lod = LOD_MAX;
  9706. for (let i = 0; i < TOTAL_LODS; i++) {
  9707. const sizeLod = Math.pow(2, lod);
  9708. _sizeLods.push(sizeLod);
  9709. let sigma = 1.0 / sizeLod;
  9710. if (i > LOD_MAX - LOD_MIN) {
  9711. sigma = EXTRA_LOD_SIGMA[i - LOD_MAX + LOD_MIN - 1];
  9712. } else if (i == 0) {
  9713. sigma = 0;
  9714. }
  9715. _sigmas.push(sigma);
  9716. const texelSize = 1.0 / (sizeLod - 1);
  9717. const min = -texelSize / 2;
  9718. const max = 1 + texelSize / 2;
  9719. const uv1 = [min, min, max, min, max, max, min, min, max, max, min, max];
  9720. const cubeFaces = 6;
  9721. const vertices = 6;
  9722. const positionSize = 3;
  9723. const uvSize = 2;
  9724. const faceIndexSize = 1;
  9725. const position = new Float32Array(positionSize * vertices * cubeFaces);
  9726. const uv = new Float32Array(uvSize * vertices * cubeFaces);
  9727. const faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces);
  9728. for (let face = 0; face < cubeFaces; face++) {
  9729. const x = face % 3 * 2 / 3 - 1;
  9730. const y = face > 2 ? 0 : -1;
  9731. 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];
  9732. position.set(coordinates, positionSize * vertices * face);
  9733. uv.set(uv1, uvSize * vertices * face);
  9734. const fill = [face, face, face, face, face, face];
  9735. faceIndex.set(fill, faceIndexSize * vertices * face);
  9736. }
  9737. const planes = new BufferGeometry();
  9738. planes.setAttribute('position', new BufferAttribute(position, positionSize));
  9739. planes.setAttribute('uv', new BufferAttribute(uv, uvSize));
  9740. planes.setAttribute('faceIndex', new BufferAttribute(faceIndex, faceIndexSize));
  9741. _lodPlanes.push(planes);
  9742. if (lod > LOD_MIN) {
  9743. lod--;
  9744. }
  9745. }
  9746. return {
  9747. _lodPlanes,
  9748. _sizeLods,
  9749. _sigmas
  9750. };
  9751. }
  9752. function _createRenderTarget(params) {
  9753. const cubeUVRenderTarget = new WebGLRenderTarget(3 * SIZE_MAX, 3 * SIZE_MAX, params);
  9754. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  9755. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  9756. cubeUVRenderTarget.scissorTest = true;
  9757. return cubeUVRenderTarget;
  9758. }
  9759. function _setViewport(target, x, y, width, height) {
  9760. target.viewport.set(x, y, width, height);
  9761. target.scissor.set(x, y, width, height);
  9762. }
  9763. function _getBlurShader(maxSamples) {
  9764. const weights = new Float32Array(maxSamples);
  9765. const poleAxis = new Vector3(0, 1, 0);
  9766. const shaderMaterial = new RawShaderMaterial({
  9767. name: 'SphericalGaussianBlur',
  9768. defines: {
  9769. 'n': maxSamples
  9770. },
  9771. uniforms: {
  9772. 'envMap': {
  9773. value: null
  9774. },
  9775. 'samples': {
  9776. value: 1
  9777. },
  9778. 'weights': {
  9779. value: weights
  9780. },
  9781. 'latitudinal': {
  9782. value: false
  9783. },
  9784. 'dTheta': {
  9785. value: 0
  9786. },
  9787. 'mipInt': {
  9788. value: 0
  9789. },
  9790. 'poleAxis': {
  9791. value: poleAxis
  9792. }
  9793. },
  9794. vertexShader: _getCommonVertexShader(),
  9795. fragmentShader:
  9796. /* glsl */
  9797. `
  9798. precision mediump float;
  9799. precision mediump int;
  9800. varying vec3 vOutputDirection;
  9801. uniform sampler2D envMap;
  9802. uniform int samples;
  9803. uniform float weights[ n ];
  9804. uniform bool latitudinal;
  9805. uniform float dTheta;
  9806. uniform float mipInt;
  9807. uniform vec3 poleAxis;
  9808. ${_getEncodings()}
  9809. #define ENVMAP_TYPE_CUBE_UV
  9810. #include <cube_uv_reflection_fragment>
  9811. vec3 getSample( float theta, vec3 axis ) {
  9812. float cosTheta = cos( theta );
  9813. // Rodrigues' axis-angle rotation
  9814. vec3 sampleDirection = vOutputDirection * cosTheta
  9815. + cross( axis, vOutputDirection ) * sin( theta )
  9816. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  9817. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  9818. }
  9819. void main() {
  9820. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  9821. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  9822. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  9823. }
  9824. axis = normalize( axis );
  9825. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9826. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  9827. for ( int i = 1; i < n; i++ ) {
  9828. if ( i >= samples ) {
  9829. break;
  9830. }
  9831. float theta = dTheta * float( i );
  9832. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  9833. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  9834. }
  9835. }
  9836. `,
  9837. blending: NoBlending,
  9838. depthTest: false,
  9839. depthWrite: false
  9840. });
  9841. return shaderMaterial;
  9842. }
  9843. function _getEquirectShader() {
  9844. const texelSize = new Vector2(1, 1);
  9845. const shaderMaterial = new RawShaderMaterial({
  9846. name: 'EquirectangularToCubeUV',
  9847. uniforms: {
  9848. 'envMap': {
  9849. value: null
  9850. },
  9851. 'texelSize': {
  9852. value: texelSize
  9853. },
  9854. 'inputEncoding': {
  9855. value: ENCODINGS[LinearEncoding]
  9856. }
  9857. },
  9858. vertexShader: _getCommonVertexShader(),
  9859. fragmentShader:
  9860. /* glsl */
  9861. `
  9862. precision mediump float;
  9863. precision mediump int;
  9864. varying vec3 vOutputDirection;
  9865. uniform sampler2D envMap;
  9866. uniform vec2 texelSize;
  9867. ${_getEncodings()}
  9868. #include <common>
  9869. void main() {
  9870. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9871. vec3 outputDirection = normalize( vOutputDirection );
  9872. vec2 uv = equirectUv( outputDirection );
  9873. vec2 f = fract( uv / texelSize - 0.5 );
  9874. uv -= f * texelSize;
  9875. vec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9876. uv.x += texelSize.x;
  9877. vec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9878. uv.y += texelSize.y;
  9879. vec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9880. uv.x -= texelSize.x;
  9881. vec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9882. vec3 tm = mix( tl, tr, f.x );
  9883. vec3 bm = mix( bl, br, f.x );
  9884. gl_FragColor.rgb = mix( tm, bm, f.y );
  9885. }
  9886. `,
  9887. blending: NoBlending,
  9888. depthTest: false,
  9889. depthWrite: false
  9890. });
  9891. return shaderMaterial;
  9892. }
  9893. function _getCubemapShader() {
  9894. const shaderMaterial = new RawShaderMaterial({
  9895. name: 'CubemapToCubeUV',
  9896. uniforms: {
  9897. 'envMap': {
  9898. value: null
  9899. },
  9900. 'inputEncoding': {
  9901. value: ENCODINGS[LinearEncoding]
  9902. }
  9903. },
  9904. vertexShader: _getCommonVertexShader(),
  9905. fragmentShader:
  9906. /* glsl */
  9907. `
  9908. precision mediump float;
  9909. precision mediump int;
  9910. varying vec3 vOutputDirection;
  9911. uniform samplerCube envMap;
  9912. ${_getEncodings()}
  9913. void main() {
  9914. gl_FragColor = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) );
  9915. }
  9916. `,
  9917. blending: NoBlending,
  9918. depthTest: false,
  9919. depthWrite: false
  9920. });
  9921. return shaderMaterial;
  9922. }
  9923. function _getCommonVertexShader() {
  9924. return (
  9925. /* glsl */
  9926. `
  9927. precision mediump float;
  9928. precision mediump int;
  9929. attribute vec3 position;
  9930. attribute vec2 uv;
  9931. attribute float faceIndex;
  9932. varying vec3 vOutputDirection;
  9933. // RH coordinate system; PMREM face-indexing convention
  9934. vec3 getDirection( vec2 uv, float face ) {
  9935. uv = 2.0 * uv - 1.0;
  9936. vec3 direction = vec3( uv, 1.0 );
  9937. if ( face == 0.0 ) {
  9938. direction = direction.zyx; // ( 1, v, u ) pos x
  9939. } else if ( face == 1.0 ) {
  9940. direction = direction.xzy;
  9941. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  9942. } else if ( face == 2.0 ) {
  9943. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  9944. } else if ( face == 3.0 ) {
  9945. direction = direction.zyx;
  9946. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  9947. } else if ( face == 4.0 ) {
  9948. direction = direction.xzy;
  9949. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  9950. } else if ( face == 5.0 ) {
  9951. direction.z *= -1.0; // ( u, v, -1 ) neg z
  9952. }
  9953. return direction;
  9954. }
  9955. void main() {
  9956. vOutputDirection = getDirection( uv, faceIndex );
  9957. gl_Position = vec4( position, 1.0 );
  9958. }
  9959. `
  9960. );
  9961. }
  9962. function _getEncodings() {
  9963. return (
  9964. /* glsl */
  9965. `
  9966. uniform int inputEncoding;
  9967. #include <encodings_pars_fragment>
  9968. vec4 inputTexelToLinear( vec4 value ) {
  9969. if ( inputEncoding == 0 ) {
  9970. return value;
  9971. } else {
  9972. return sRGBToLinear( value );
  9973. }
  9974. }
  9975. vec4 envMapTexelToLinear( vec4 color ) {
  9976. return inputTexelToLinear( color );
  9977. }
  9978. `
  9979. );
  9980. }
  9981. function WebGLCubeUVMaps(renderer) {
  9982. let cubeUVmaps = new WeakMap();
  9983. let pmremGenerator = null;
  9984. function get(texture) {
  9985. if (texture && texture.isTexture && texture.isRenderTargetTexture === false) {
  9986. const mapping = texture.mapping;
  9987. const isEquirectMap = mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping;
  9988. const isCubeMap = mapping === CubeReflectionMapping || mapping === CubeRefractionMapping;
  9989. if (isEquirectMap || isCubeMap) {
  9990. // equirect/cube map to cubeUV conversion
  9991. if (cubeUVmaps.has(texture)) {
  9992. return cubeUVmaps.get(texture).texture;
  9993. } else {
  9994. const image = texture.image;
  9995. if (isEquirectMap && image && image.height > 0 || isCubeMap && image && isCubeTextureComplete(image)) {
  9996. const currentRenderTarget = renderer.getRenderTarget();
  9997. if (pmremGenerator === null) pmremGenerator = new PMREMGenerator(renderer);
  9998. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture) : pmremGenerator.fromCubemap(texture);
  9999. cubeUVmaps.set(texture, renderTarget);
  10000. renderer.setRenderTarget(currentRenderTarget);
  10001. texture.addEventListener('dispose', onTextureDispose);
  10002. return renderTarget.texture;
  10003. } else {
  10004. // image not yet ready. try the conversion next frame
  10005. return null;
  10006. }
  10007. }
  10008. }
  10009. }
  10010. return texture;
  10011. }
  10012. function isCubeTextureComplete(image) {
  10013. let count = 0;
  10014. const length = 6;
  10015. for (let i = 0; i < length; i++) {
  10016. if (image[i] !== undefined) count++;
  10017. }
  10018. return count === length;
  10019. }
  10020. function onTextureDispose(event) {
  10021. const texture = event.target;
  10022. texture.removeEventListener('dispose', onTextureDispose);
  10023. const cubemapUV = cubeUVmaps.get(texture);
  10024. if (cubemapUV !== undefined) {
  10025. cubeUVmaps.delete(texture);
  10026. cubemapUV.dispose();
  10027. }
  10028. }
  10029. function dispose() {
  10030. cubeUVmaps = new WeakMap();
  10031. if (pmremGenerator !== null) {
  10032. pmremGenerator.dispose();
  10033. pmremGenerator = null;
  10034. }
  10035. }
  10036. return {
  10037. get: get,
  10038. dispose: dispose
  10039. };
  10040. }
  10041. function WebGLExtensions(gl) {
  10042. const extensions = {};
  10043. function getExtension(name) {
  10044. if (extensions[name] !== undefined) {
  10045. return extensions[name];
  10046. }
  10047. let extension;
  10048. switch (name) {
  10049. case 'WEBGL_depth_texture':
  10050. extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
  10051. break;
  10052. case 'EXT_texture_filter_anisotropic':
  10053. extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
  10054. break;
  10055. case 'WEBGL_compressed_texture_s3tc':
  10056. extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  10057. break;
  10058. case 'WEBGL_compressed_texture_pvrtc':
  10059. extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  10060. break;
  10061. default:
  10062. extension = gl.getExtension(name);
  10063. }
  10064. extensions[name] = extension;
  10065. return extension;
  10066. }
  10067. return {
  10068. has: function (name) {
  10069. return getExtension(name) !== null;
  10070. },
  10071. init: function (capabilities) {
  10072. if (capabilities.isWebGL2) {
  10073. getExtension('EXT_color_buffer_float');
  10074. } else {
  10075. getExtension('WEBGL_depth_texture');
  10076. getExtension('OES_texture_float');
  10077. getExtension('OES_texture_half_float');
  10078. getExtension('OES_texture_half_float_linear');
  10079. getExtension('OES_standard_derivatives');
  10080. getExtension('OES_element_index_uint');
  10081. getExtension('OES_vertex_array_object');
  10082. getExtension('ANGLE_instanced_arrays');
  10083. }
  10084. getExtension('OES_texture_float_linear');
  10085. getExtension('EXT_color_buffer_half_float');
  10086. getExtension('WEBGL_multisampled_render_to_texture');
  10087. },
  10088. get: function (name) {
  10089. const extension = getExtension(name);
  10090. if (extension === null) {
  10091. console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
  10092. }
  10093. return extension;
  10094. }
  10095. };
  10096. }
  10097. function WebGLGeometries(gl, attributes, info, bindingStates) {
  10098. const geometries = {};
  10099. const wireframeAttributes = new WeakMap();
  10100. function onGeometryDispose(event) {
  10101. const geometry = event.target;
  10102. if (geometry.index !== null) {
  10103. attributes.remove(geometry.index);
  10104. }
  10105. for (const name in geometry.attributes) {
  10106. attributes.remove(geometry.attributes[name]);
  10107. }
  10108. geometry.removeEventListener('dispose', onGeometryDispose);
  10109. delete geometries[geometry.id];
  10110. const attribute = wireframeAttributes.get(geometry);
  10111. if (attribute) {
  10112. attributes.remove(attribute);
  10113. wireframeAttributes.delete(geometry);
  10114. }
  10115. bindingStates.releaseStatesOfGeometry(geometry);
  10116. if (geometry.isInstancedBufferGeometry === true) {
  10117. delete geometry._maxInstanceCount;
  10118. } //
  10119. info.memory.geometries--;
  10120. }
  10121. function get(object, geometry) {
  10122. if (geometries[geometry.id] === true) return geometry;
  10123. geometry.addEventListener('dispose', onGeometryDispose);
  10124. geometries[geometry.id] = true;
  10125. info.memory.geometries++;
  10126. return geometry;
  10127. }
  10128. function update(geometry) {
  10129. const geometryAttributes = geometry.attributes; // Updating index buffer in VAO now. See WebGLBindingStates.
  10130. for (const name in geometryAttributes) {
  10131. attributes.update(geometryAttributes[name], gl.ARRAY_BUFFER);
  10132. } // morph targets
  10133. const morphAttributes = geometry.morphAttributes;
  10134. for (const name in morphAttributes) {
  10135. const array = morphAttributes[name];
  10136. for (let i = 0, l = array.length; i < l; i++) {
  10137. attributes.update(array[i], gl.ARRAY_BUFFER);
  10138. }
  10139. }
  10140. }
  10141. function updateWireframeAttribute(geometry) {
  10142. const indices = [];
  10143. const geometryIndex = geometry.index;
  10144. const geometryPosition = geometry.attributes.position;
  10145. let version = 0;
  10146. if (geometryIndex !== null) {
  10147. const array = geometryIndex.array;
  10148. version = geometryIndex.version;
  10149. for (let i = 0, l = array.length; i < l; i += 3) {
  10150. const a = array[i + 0];
  10151. const b = array[i + 1];
  10152. const c = array[i + 2];
  10153. indices.push(a, b, b, c, c, a);
  10154. }
  10155. } else {
  10156. const array = geometryPosition.array;
  10157. version = geometryPosition.version;
  10158. for (let i = 0, l = array.length / 3 - 1; i < l; i += 3) {
  10159. const a = i + 0;
  10160. const b = i + 1;
  10161. const c = i + 2;
  10162. indices.push(a, b, b, c, c, a);
  10163. }
  10164. }
  10165. const attribute = new (arrayMax(indices) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
  10166. attribute.version = version; // Updating index buffer in VAO now. See WebGLBindingStates
  10167. //
  10168. const previousAttribute = wireframeAttributes.get(geometry);
  10169. if (previousAttribute) attributes.remove(previousAttribute); //
  10170. wireframeAttributes.set(geometry, attribute);
  10171. }
  10172. function getWireframeAttribute(geometry) {
  10173. const currentAttribute = wireframeAttributes.get(geometry);
  10174. if (currentAttribute) {
  10175. const geometryIndex = geometry.index;
  10176. if (geometryIndex !== null) {
  10177. // if the attribute is obsolete, create a new one
  10178. if (currentAttribute.version < geometryIndex.version) {
  10179. updateWireframeAttribute(geometry);
  10180. }
  10181. }
  10182. } else {
  10183. updateWireframeAttribute(geometry);
  10184. }
  10185. return wireframeAttributes.get(geometry);
  10186. }
  10187. return {
  10188. get: get,
  10189. update: update,
  10190. getWireframeAttribute: getWireframeAttribute
  10191. };
  10192. }
  10193. function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
  10194. const isWebGL2 = capabilities.isWebGL2;
  10195. let mode;
  10196. function setMode(value) {
  10197. mode = value;
  10198. }
  10199. let type, bytesPerElement;
  10200. function setIndex(value) {
  10201. type = value.type;
  10202. bytesPerElement = value.bytesPerElement;
  10203. }
  10204. function render(start, count) {
  10205. gl.drawElements(mode, count, type, start * bytesPerElement);
  10206. info.update(count, mode, 1);
  10207. }
  10208. function renderInstances(start, count, primcount) {
  10209. if (primcount === 0) return;
  10210. let extension, methodName;
  10211. if (isWebGL2) {
  10212. extension = gl;
  10213. methodName = 'drawElementsInstanced';
  10214. } else {
  10215. extension = extensions.get('ANGLE_instanced_arrays');
  10216. methodName = 'drawElementsInstancedANGLE';
  10217. if (extension === null) {
  10218. console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  10219. return;
  10220. }
  10221. }
  10222. extension[methodName](mode, count, type, start * bytesPerElement, primcount);
  10223. info.update(count, mode, primcount);
  10224. } //
  10225. this.setMode = setMode;
  10226. this.setIndex = setIndex;
  10227. this.render = render;
  10228. this.renderInstances = renderInstances;
  10229. }
  10230. function WebGLInfo(gl) {
  10231. const memory = {
  10232. geometries: 0,
  10233. textures: 0
  10234. };
  10235. const render = {
  10236. frame: 0,
  10237. calls: 0,
  10238. triangles: 0,
  10239. points: 0,
  10240. lines: 0
  10241. };
  10242. function update(count, mode, instanceCount) {
  10243. render.calls++;
  10244. switch (mode) {
  10245. case gl.TRIANGLES:
  10246. render.triangles += instanceCount * (count / 3);
  10247. break;
  10248. case gl.LINES:
  10249. render.lines += instanceCount * (count / 2);
  10250. break;
  10251. case gl.LINE_STRIP:
  10252. render.lines += instanceCount * (count - 1);
  10253. break;
  10254. case gl.LINE_LOOP:
  10255. render.lines += instanceCount * count;
  10256. break;
  10257. case gl.POINTS:
  10258. render.points += instanceCount * count;
  10259. break;
  10260. default:
  10261. console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
  10262. break;
  10263. }
  10264. }
  10265. function reset() {
  10266. render.frame++;
  10267. render.calls = 0;
  10268. render.triangles = 0;
  10269. render.points = 0;
  10270. render.lines = 0;
  10271. }
  10272. return {
  10273. memory: memory,
  10274. render: render,
  10275. programs: null,
  10276. autoReset: true,
  10277. reset: reset,
  10278. update: update
  10279. };
  10280. }
  10281. class DataTexture2DArray extends Texture {
  10282. constructor(data = null, width = 1, height = 1, depth = 1) {
  10283. super(null);
  10284. this.image = {
  10285. data,
  10286. width,
  10287. height,
  10288. depth
  10289. };
  10290. this.magFilter = NearestFilter;
  10291. this.minFilter = NearestFilter;
  10292. this.wrapR = ClampToEdgeWrapping;
  10293. this.generateMipmaps = false;
  10294. this.flipY = false;
  10295. this.unpackAlignment = 1;
  10296. }
  10297. }
  10298. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  10299. function numericalSort(a, b) {
  10300. return a[0] - b[0];
  10301. }
  10302. function absNumericalSort(a, b) {
  10303. return Math.abs(b[1]) - Math.abs(a[1]);
  10304. }
  10305. function denormalize(morph, attribute) {
  10306. let denominator = 1;
  10307. const array = attribute.isInterleavedBufferAttribute ? attribute.data.array : attribute.array;
  10308. if (array instanceof Int8Array) denominator = 127;else if (array instanceof Int16Array) denominator = 32767;else if (array instanceof Int32Array) denominator = 2147483647;else console.error('THREE.WebGLMorphtargets: Unsupported morph attribute data type: ', array);
  10309. morph.divideScalar(denominator);
  10310. }
  10311. function WebGLMorphtargets(gl, capabilities, textures) {
  10312. const influencesList = {};
  10313. const morphInfluences = new Float32Array(8);
  10314. const morphTextures = new WeakMap();
  10315. const morph = new Vector3();
  10316. const workInfluences = [];
  10317. for (let i = 0; i < 8; i++) {
  10318. workInfluences[i] = [i, 0];
  10319. }
  10320. function update(object, geometry, material, program) {
  10321. const objectInfluences = object.morphTargetInfluences;
  10322. if (capabilities.isWebGL2 === true) {
  10323. // instead of using attributes, the WebGL 2 code path encodes morph targets
  10324. // into an array of data textures. Each layer represents a single morph target.
  10325. const numberOfMorphTargets = geometry.morphAttributes.position.length;
  10326. let entry = morphTextures.get(geometry);
  10327. if (entry === undefined || entry.count !== numberOfMorphTargets) {
  10328. if (entry !== undefined) entry.texture.dispose();
  10329. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10330. const morphTargets = geometry.morphAttributes.position;
  10331. const morphNormals = geometry.morphAttributes.normal || [];
  10332. const numberOfVertices = geometry.attributes.position.count;
  10333. const numberOfVertexData = hasMorphNormals === true ? 2 : 1; // (v,n) vs. (v)
  10334. let width = numberOfVertices * numberOfVertexData;
  10335. let height = 1;
  10336. if (width > capabilities.maxTextureSize) {
  10337. height = Math.ceil(width / capabilities.maxTextureSize);
  10338. width = capabilities.maxTextureSize;
  10339. }
  10340. const buffer = new Float32Array(width * height * 4 * numberOfMorphTargets);
  10341. const texture = new DataTexture2DArray(buffer, width, height, numberOfMorphTargets);
  10342. texture.format = RGBAFormat; // using RGBA since RGB might be emulated (and is thus slower)
  10343. texture.type = FloatType;
  10344. texture.needsUpdate = true; // fill buffer
  10345. const vertexDataStride = numberOfVertexData * 4;
  10346. for (let i = 0; i < numberOfMorphTargets; i++) {
  10347. const morphTarget = morphTargets[i];
  10348. const morphNormal = morphNormals[i];
  10349. const offset = width * height * 4 * i;
  10350. for (let j = 0; j < morphTarget.count; j++) {
  10351. morph.fromBufferAttribute(morphTarget, j);
  10352. if (morphTarget.normalized === true) denormalize(morph, morphTarget);
  10353. const stride = j * vertexDataStride;
  10354. buffer[offset + stride + 0] = morph.x;
  10355. buffer[offset + stride + 1] = morph.y;
  10356. buffer[offset + stride + 2] = morph.z;
  10357. buffer[offset + stride + 3] = 0;
  10358. if (hasMorphNormals === true) {
  10359. morph.fromBufferAttribute(morphNormal, j);
  10360. if (morphNormal.normalized === true) denormalize(morph, morphNormal);
  10361. buffer[offset + stride + 4] = morph.x;
  10362. buffer[offset + stride + 5] = morph.y;
  10363. buffer[offset + stride + 6] = morph.z;
  10364. buffer[offset + stride + 7] = 0;
  10365. }
  10366. }
  10367. }
  10368. entry = {
  10369. count: numberOfMorphTargets,
  10370. texture: texture,
  10371. size: new Vector2(width, height)
  10372. };
  10373. morphTextures.set(geometry, entry);
  10374. } //
  10375. let morphInfluencesSum = 0;
  10376. for (let i = 0; i < objectInfluences.length; i++) {
  10377. morphInfluencesSum += objectInfluences[i];
  10378. }
  10379. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10380. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  10381. program.getUniforms().setValue(gl, 'morphTargetInfluences', objectInfluences);
  10382. program.getUniforms().setValue(gl, 'morphTargetsTexture', entry.texture, textures);
  10383. program.getUniforms().setValue(gl, 'morphTargetsTextureSize', entry.size);
  10384. } else {
  10385. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10386. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10387. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10388. let influences = influencesList[geometry.id];
  10389. if (influences === undefined || influences.length !== length) {
  10390. // initialise list
  10391. influences = [];
  10392. for (let i = 0; i < length; i++) {
  10393. influences[i] = [i, 0];
  10394. }
  10395. influencesList[geometry.id] = influences;
  10396. } // Collect influences
  10397. for (let i = 0; i < length; i++) {
  10398. const influence = influences[i];
  10399. influence[0] = i;
  10400. influence[1] = objectInfluences[i];
  10401. }
  10402. influences.sort(absNumericalSort);
  10403. for (let i = 0; i < 8; i++) {
  10404. if (i < length && influences[i][1]) {
  10405. workInfluences[i][0] = influences[i][0];
  10406. workInfluences[i][1] = influences[i][1];
  10407. } else {
  10408. workInfluences[i][0] = Number.MAX_SAFE_INTEGER;
  10409. workInfluences[i][1] = 0;
  10410. }
  10411. }
  10412. workInfluences.sort(numericalSort);
  10413. const morphTargets = geometry.morphAttributes.position;
  10414. const morphNormals = geometry.morphAttributes.normal;
  10415. let morphInfluencesSum = 0;
  10416. for (let i = 0; i < 8; i++) {
  10417. const influence = workInfluences[i];
  10418. const index = influence[0];
  10419. const value = influence[1];
  10420. if (index !== Number.MAX_SAFE_INTEGER && value) {
  10421. if (morphTargets && geometry.getAttribute('morphTarget' + i) !== morphTargets[index]) {
  10422. geometry.setAttribute('morphTarget' + i, morphTargets[index]);
  10423. }
  10424. if (morphNormals && geometry.getAttribute('morphNormal' + i) !== morphNormals[index]) {
  10425. geometry.setAttribute('morphNormal' + i, morphNormals[index]);
  10426. }
  10427. morphInfluences[i] = value;
  10428. morphInfluencesSum += value;
  10429. } else {
  10430. if (morphTargets && geometry.hasAttribute('morphTarget' + i) === true) {
  10431. geometry.deleteAttribute('morphTarget' + i);
  10432. }
  10433. if (morphNormals && geometry.hasAttribute('morphNormal' + i) === true) {
  10434. geometry.deleteAttribute('morphNormal' + i);
  10435. }
  10436. morphInfluences[i] = 0;
  10437. }
  10438. } // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10439. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10440. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10441. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10442. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  10443. program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
  10444. }
  10445. }
  10446. return {
  10447. update: update
  10448. };
  10449. }
  10450. function WebGLObjects(gl, geometries, attributes, info) {
  10451. let updateMap = new WeakMap();
  10452. function update(object) {
  10453. const frame = info.render.frame;
  10454. const geometry = object.geometry;
  10455. const buffergeometry = geometries.get(object, geometry); // Update once per frame
  10456. if (updateMap.get(buffergeometry) !== frame) {
  10457. geometries.update(buffergeometry);
  10458. updateMap.set(buffergeometry, frame);
  10459. }
  10460. if (object.isInstancedMesh) {
  10461. if (object.hasEventListener('dispose', onInstancedMeshDispose) === false) {
  10462. object.addEventListener('dispose', onInstancedMeshDispose);
  10463. }
  10464. attributes.update(object.instanceMatrix, gl.ARRAY_BUFFER);
  10465. if (object.instanceColor !== null) {
  10466. attributes.update(object.instanceColor, gl.ARRAY_BUFFER);
  10467. }
  10468. }
  10469. return buffergeometry;
  10470. }
  10471. function dispose() {
  10472. updateMap = new WeakMap();
  10473. }
  10474. function onInstancedMeshDispose(event) {
  10475. const instancedMesh = event.target;
  10476. instancedMesh.removeEventListener('dispose', onInstancedMeshDispose);
  10477. attributes.remove(instancedMesh.instanceMatrix);
  10478. if (instancedMesh.instanceColor !== null) attributes.remove(instancedMesh.instanceColor);
  10479. }
  10480. return {
  10481. update: update,
  10482. dispose: dispose
  10483. };
  10484. }
  10485. class DataTexture3D extends Texture {
  10486. constructor(data = null, width = 1, height = 1, depth = 1) {
  10487. // We're going to add .setXXX() methods for setting properties later.
  10488. // Users can still set in DataTexture3D directly.
  10489. //
  10490. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  10491. // texture.anisotropy = 16;
  10492. //
  10493. // See #14839
  10494. super(null);
  10495. this.image = {
  10496. data,
  10497. width,
  10498. height,
  10499. depth
  10500. };
  10501. this.magFilter = NearestFilter;
  10502. this.minFilter = NearestFilter;
  10503. this.wrapR = ClampToEdgeWrapping;
  10504. this.generateMipmaps = false;
  10505. this.flipY = false;
  10506. this.unpackAlignment = 1;
  10507. }
  10508. }
  10509. DataTexture3D.prototype.isDataTexture3D = true;
  10510. /**
  10511. * Uniforms of a program.
  10512. * Those form a tree structure with a special top-level container for the root,
  10513. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10514. *
  10515. *
  10516. * Properties of inner nodes including the top-level container:
  10517. *
  10518. * .seq - array of nested uniforms
  10519. * .map - nested uniforms by name
  10520. *
  10521. *
  10522. * Methods of all nodes except the top-level container:
  10523. *
  10524. * .setValue( gl, value, [textures] )
  10525. *
  10526. * uploads a uniform value(s)
  10527. * the 'textures' parameter is needed for sampler uniforms
  10528. *
  10529. *
  10530. * Static methods of the top-level container (textures factorizations):
  10531. *
  10532. * .upload( gl, seq, values, textures )
  10533. *
  10534. * sets uniforms in 'seq' to 'values[id].value'
  10535. *
  10536. * .seqWithValue( seq, values ) : filteredSeq
  10537. *
  10538. * filters 'seq' entries with corresponding entry in values
  10539. *
  10540. *
  10541. * Methods of the top-level container (textures factorizations):
  10542. *
  10543. * .setValue( gl, name, value, textures )
  10544. *
  10545. * sets uniform with name 'name' to 'value'
  10546. *
  10547. * .setOptional( gl, obj, prop )
  10548. *
  10549. * like .set for an optional property of the object
  10550. *
  10551. */
  10552. const emptyTexture = new Texture();
  10553. const emptyTexture2dArray = new DataTexture2DArray();
  10554. const emptyTexture3d = new DataTexture3D();
  10555. const emptyCubeTexture = new CubeTexture(); // --- Utilities ---
  10556. // Array Caches (provide typed arrays for temporary by size)
  10557. const arrayCacheF32 = [];
  10558. const arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms
  10559. const mat4array = new Float32Array(16);
  10560. const mat3array = new Float32Array(9);
  10561. const mat2array = new Float32Array(4); // Flattening for arrays of vectors and matrices
  10562. function flatten(array, nBlocks, blockSize) {
  10563. const firstElem = array[0];
  10564. if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )
  10565. // see http://jacksondunstan.com/articles/983
  10566. const n = nBlocks * blockSize;
  10567. let r = arrayCacheF32[n];
  10568. if (r === undefined) {
  10569. r = new Float32Array(n);
  10570. arrayCacheF32[n] = r;
  10571. }
  10572. if (nBlocks !== 0) {
  10573. firstElem.toArray(r, 0);
  10574. for (let i = 1, offset = 0; i !== nBlocks; ++i) {
  10575. offset += blockSize;
  10576. array[i].toArray(r, offset);
  10577. }
  10578. }
  10579. return r;
  10580. }
  10581. function arraysEqual(a, b) {
  10582. if (a.length !== b.length) return false;
  10583. for (let i = 0, l = a.length; i < l; i++) {
  10584. if (a[i] !== b[i]) return false;
  10585. }
  10586. return true;
  10587. }
  10588. function copyArray(a, b) {
  10589. for (let i = 0, l = b.length; i < l; i++) {
  10590. a[i] = b[i];
  10591. }
  10592. } // Texture unit allocation
  10593. function allocTexUnits(textures, n) {
  10594. let r = arrayCacheI32[n];
  10595. if (r === undefined) {
  10596. r = new Int32Array(n);
  10597. arrayCacheI32[n] = r;
  10598. }
  10599. for (let i = 0; i !== n; ++i) {
  10600. r[i] = textures.allocateTextureUnit();
  10601. }
  10602. return r;
  10603. } // --- Setters ---
  10604. // Note: Defining these methods externally, because they come in a bunch
  10605. // and this way their names minify.
  10606. // Single scalar
  10607. function setValueV1f(gl, v) {
  10608. const cache = this.cache;
  10609. if (cache[0] === v) return;
  10610. gl.uniform1f(this.addr, v);
  10611. cache[0] = v;
  10612. } // Single float vector (from flat array or THREE.VectorN)
  10613. function setValueV2f(gl, v) {
  10614. const cache = this.cache;
  10615. if (v.x !== undefined) {
  10616. if (cache[0] !== v.x || cache[1] !== v.y) {
  10617. gl.uniform2f(this.addr, v.x, v.y);
  10618. cache[0] = v.x;
  10619. cache[1] = v.y;
  10620. }
  10621. } else {
  10622. if (arraysEqual(cache, v)) return;
  10623. gl.uniform2fv(this.addr, v);
  10624. copyArray(cache, v);
  10625. }
  10626. }
  10627. function setValueV3f(gl, v) {
  10628. const cache = this.cache;
  10629. if (v.x !== undefined) {
  10630. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  10631. gl.uniform3f(this.addr, v.x, v.y, v.z);
  10632. cache[0] = v.x;
  10633. cache[1] = v.y;
  10634. cache[2] = v.z;
  10635. }
  10636. } else if (v.r !== undefined) {
  10637. if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
  10638. gl.uniform3f(this.addr, v.r, v.g, v.b);
  10639. cache[0] = v.r;
  10640. cache[1] = v.g;
  10641. cache[2] = v.b;
  10642. }
  10643. } else {
  10644. if (arraysEqual(cache, v)) return;
  10645. gl.uniform3fv(this.addr, v);
  10646. copyArray(cache, v);
  10647. }
  10648. }
  10649. function setValueV4f(gl, v) {
  10650. const cache = this.cache;
  10651. if (v.x !== undefined) {
  10652. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  10653. gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
  10654. cache[0] = v.x;
  10655. cache[1] = v.y;
  10656. cache[2] = v.z;
  10657. cache[3] = v.w;
  10658. }
  10659. } else {
  10660. if (arraysEqual(cache, v)) return;
  10661. gl.uniform4fv(this.addr, v);
  10662. copyArray(cache, v);
  10663. }
  10664. } // Single matrix (from flat array or THREE.MatrixN)
  10665. function setValueM2(gl, v) {
  10666. const cache = this.cache;
  10667. const elements = v.elements;
  10668. if (elements === undefined) {
  10669. if (arraysEqual(cache, v)) return;
  10670. gl.uniformMatrix2fv(this.addr, false, v);
  10671. copyArray(cache, v);
  10672. } else {
  10673. if (arraysEqual(cache, elements)) return;
  10674. mat2array.set(elements);
  10675. gl.uniformMatrix2fv(this.addr, false, mat2array);
  10676. copyArray(cache, elements);
  10677. }
  10678. }
  10679. function setValueM3(gl, v) {
  10680. const cache = this.cache;
  10681. const elements = v.elements;
  10682. if (elements === undefined) {
  10683. if (arraysEqual(cache, v)) return;
  10684. gl.uniformMatrix3fv(this.addr, false, v);
  10685. copyArray(cache, v);
  10686. } else {
  10687. if (arraysEqual(cache, elements)) return;
  10688. mat3array.set(elements);
  10689. gl.uniformMatrix3fv(this.addr, false, mat3array);
  10690. copyArray(cache, elements);
  10691. }
  10692. }
  10693. function setValueM4(gl, v) {
  10694. const cache = this.cache;
  10695. const elements = v.elements;
  10696. if (elements === undefined) {
  10697. if (arraysEqual(cache, v)) return;
  10698. gl.uniformMatrix4fv(this.addr, false, v);
  10699. copyArray(cache, v);
  10700. } else {
  10701. if (arraysEqual(cache, elements)) return;
  10702. mat4array.set(elements);
  10703. gl.uniformMatrix4fv(this.addr, false, mat4array);
  10704. copyArray(cache, elements);
  10705. }
  10706. } // Single integer / boolean
  10707. function setValueV1i(gl, v) {
  10708. const cache = this.cache;
  10709. if (cache[0] === v) return;
  10710. gl.uniform1i(this.addr, v);
  10711. cache[0] = v;
  10712. } // Single integer / boolean vector (from flat array)
  10713. function setValueV2i(gl, v) {
  10714. const cache = this.cache;
  10715. if (arraysEqual(cache, v)) return;
  10716. gl.uniform2iv(this.addr, v);
  10717. copyArray(cache, v);
  10718. }
  10719. function setValueV3i(gl, v) {
  10720. const cache = this.cache;
  10721. if (arraysEqual(cache, v)) return;
  10722. gl.uniform3iv(this.addr, v);
  10723. copyArray(cache, v);
  10724. }
  10725. function setValueV4i(gl, v) {
  10726. const cache = this.cache;
  10727. if (arraysEqual(cache, v)) return;
  10728. gl.uniform4iv(this.addr, v);
  10729. copyArray(cache, v);
  10730. } // Single unsigned integer
  10731. function setValueV1ui(gl, v) {
  10732. const cache = this.cache;
  10733. if (cache[0] === v) return;
  10734. gl.uniform1ui(this.addr, v);
  10735. cache[0] = v;
  10736. } // Single unsigned integer vector (from flat array)
  10737. function setValueV2ui(gl, v) {
  10738. const cache = this.cache;
  10739. if (arraysEqual(cache, v)) return;
  10740. gl.uniform2uiv(this.addr, v);
  10741. copyArray(cache, v);
  10742. }
  10743. function setValueV3ui(gl, v) {
  10744. const cache = this.cache;
  10745. if (arraysEqual(cache, v)) return;
  10746. gl.uniform3uiv(this.addr, v);
  10747. copyArray(cache, v);
  10748. }
  10749. function setValueV4ui(gl, v) {
  10750. const cache = this.cache;
  10751. if (arraysEqual(cache, v)) return;
  10752. gl.uniform4uiv(this.addr, v);
  10753. copyArray(cache, v);
  10754. } // Single texture (2D / Cube)
  10755. function setValueT1(gl, v, textures) {
  10756. const cache = this.cache;
  10757. const unit = textures.allocateTextureUnit();
  10758. if (cache[0] !== unit) {
  10759. gl.uniform1i(this.addr, unit);
  10760. cache[0] = unit;
  10761. }
  10762. textures.safeSetTexture2D(v || emptyTexture, unit);
  10763. }
  10764. function setValueT3D1(gl, v, textures) {
  10765. const cache = this.cache;
  10766. const unit = textures.allocateTextureUnit();
  10767. if (cache[0] !== unit) {
  10768. gl.uniform1i(this.addr, unit);
  10769. cache[0] = unit;
  10770. }
  10771. textures.setTexture3D(v || emptyTexture3d, unit);
  10772. }
  10773. function setValueT6(gl, v, textures) {
  10774. const cache = this.cache;
  10775. const unit = textures.allocateTextureUnit();
  10776. if (cache[0] !== unit) {
  10777. gl.uniform1i(this.addr, unit);
  10778. cache[0] = unit;
  10779. }
  10780. textures.safeSetTextureCube(v || emptyCubeTexture, unit);
  10781. }
  10782. function setValueT2DArray1(gl, v, textures) {
  10783. const cache = this.cache;
  10784. const unit = textures.allocateTextureUnit();
  10785. if (cache[0] !== unit) {
  10786. gl.uniform1i(this.addr, unit);
  10787. cache[0] = unit;
  10788. }
  10789. textures.setTexture2DArray(v || emptyTexture2dArray, unit);
  10790. } // Helper to pick the right setter for the singular case
  10791. function getSingularSetter(type) {
  10792. switch (type) {
  10793. case 0x1406:
  10794. return setValueV1f;
  10795. // FLOAT
  10796. case 0x8b50:
  10797. return setValueV2f;
  10798. // _VEC2
  10799. case 0x8b51:
  10800. return setValueV3f;
  10801. // _VEC3
  10802. case 0x8b52:
  10803. return setValueV4f;
  10804. // _VEC4
  10805. case 0x8b5a:
  10806. return setValueM2;
  10807. // _MAT2
  10808. case 0x8b5b:
  10809. return setValueM3;
  10810. // _MAT3
  10811. case 0x8b5c:
  10812. return setValueM4;
  10813. // _MAT4
  10814. case 0x1404:
  10815. case 0x8b56:
  10816. return setValueV1i;
  10817. // INT, BOOL
  10818. case 0x8b53:
  10819. case 0x8b57:
  10820. return setValueV2i;
  10821. // _VEC2
  10822. case 0x8b54:
  10823. case 0x8b58:
  10824. return setValueV3i;
  10825. // _VEC3
  10826. case 0x8b55:
  10827. case 0x8b59:
  10828. return setValueV4i;
  10829. // _VEC4
  10830. case 0x1405:
  10831. return setValueV1ui;
  10832. // UINT
  10833. case 0x8dc6:
  10834. return setValueV2ui;
  10835. // _VEC2
  10836. case 0x8dc7:
  10837. return setValueV3ui;
  10838. // _VEC3
  10839. case 0x8dc8:
  10840. return setValueV4ui;
  10841. // _VEC4
  10842. case 0x8b5e: // SAMPLER_2D
  10843. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10844. case 0x8dca: // INT_SAMPLER_2D
  10845. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10846. case 0x8b62:
  10847. // SAMPLER_2D_SHADOW
  10848. return setValueT1;
  10849. case 0x8b5f: // SAMPLER_3D
  10850. case 0x8dcb: // INT_SAMPLER_3D
  10851. case 0x8dd3:
  10852. // UNSIGNED_INT_SAMPLER_3D
  10853. return setValueT3D1;
  10854. case 0x8b60: // SAMPLER_CUBE
  10855. case 0x8dcc: // INT_SAMPLER_CUBE
  10856. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10857. case 0x8dc5:
  10858. // SAMPLER_CUBE_SHADOW
  10859. return setValueT6;
  10860. case 0x8dc1: // SAMPLER_2D_ARRAY
  10861. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10862. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10863. case 0x8dc4:
  10864. // SAMPLER_2D_ARRAY_SHADOW
  10865. return setValueT2DArray1;
  10866. }
  10867. } // Array of scalars
  10868. function setValueV1fArray(gl, v) {
  10869. gl.uniform1fv(this.addr, v);
  10870. } // Array of vectors (from flat array or array of THREE.VectorN)
  10871. function setValueV2fArray(gl, v) {
  10872. const data = flatten(v, this.size, 2);
  10873. gl.uniform2fv(this.addr, data);
  10874. }
  10875. function setValueV3fArray(gl, v) {
  10876. const data = flatten(v, this.size, 3);
  10877. gl.uniform3fv(this.addr, data);
  10878. }
  10879. function setValueV4fArray(gl, v) {
  10880. const data = flatten(v, this.size, 4);
  10881. gl.uniform4fv(this.addr, data);
  10882. } // Array of matrices (from flat array or array of THREE.MatrixN)
  10883. function setValueM2Array(gl, v) {
  10884. const data = flatten(v, this.size, 4);
  10885. gl.uniformMatrix2fv(this.addr, false, data);
  10886. }
  10887. function setValueM3Array(gl, v) {
  10888. const data = flatten(v, this.size, 9);
  10889. gl.uniformMatrix3fv(this.addr, false, data);
  10890. }
  10891. function setValueM4Array(gl, v) {
  10892. const data = flatten(v, this.size, 16);
  10893. gl.uniformMatrix4fv(this.addr, false, data);
  10894. } // Array of integer / boolean
  10895. function setValueV1iArray(gl, v) {
  10896. gl.uniform1iv(this.addr, v);
  10897. } // Array of integer / boolean vectors (from flat array)
  10898. function setValueV2iArray(gl, v) {
  10899. gl.uniform2iv(this.addr, v);
  10900. }
  10901. function setValueV3iArray(gl, v) {
  10902. gl.uniform3iv(this.addr, v);
  10903. }
  10904. function setValueV4iArray(gl, v) {
  10905. gl.uniform4iv(this.addr, v);
  10906. } // Array of unsigned integer
  10907. function setValueV1uiArray(gl, v) {
  10908. gl.uniform1uiv(this.addr, v);
  10909. } // Array of unsigned integer vectors (from flat array)
  10910. function setValueV2uiArray(gl, v) {
  10911. gl.uniform2uiv(this.addr, v);
  10912. }
  10913. function setValueV3uiArray(gl, v) {
  10914. gl.uniform3uiv(this.addr, v);
  10915. }
  10916. function setValueV4uiArray(gl, v) {
  10917. gl.uniform4uiv(this.addr, v);
  10918. } // Array of textures (2D / 3D / Cube / 2DArray)
  10919. function setValueT1Array(gl, v, textures) {
  10920. const n = v.length;
  10921. const units = allocTexUnits(textures, n);
  10922. gl.uniform1iv(this.addr, units);
  10923. for (let i = 0; i !== n; ++i) {
  10924. textures.safeSetTexture2D(v[i] || emptyTexture, units[i]);
  10925. }
  10926. }
  10927. function setValueT3DArray(gl, v, textures) {
  10928. const n = v.length;
  10929. const units = allocTexUnits(textures, n);
  10930. gl.uniform1iv(this.addr, units);
  10931. for (let i = 0; i !== n; ++i) {
  10932. textures.setTexture3D(v[i] || emptyTexture3d, units[i]);
  10933. }
  10934. }
  10935. function setValueT6Array(gl, v, textures) {
  10936. const n = v.length;
  10937. const units = allocTexUnits(textures, n);
  10938. gl.uniform1iv(this.addr, units);
  10939. for (let i = 0; i !== n; ++i) {
  10940. textures.safeSetTextureCube(v[i] || emptyCubeTexture, units[i]);
  10941. }
  10942. }
  10943. function setValueT2DArrayArray(gl, v, textures) {
  10944. const n = v.length;
  10945. const units = allocTexUnits(textures, n);
  10946. gl.uniform1iv(this.addr, units);
  10947. for (let i = 0; i !== n; ++i) {
  10948. textures.setTexture2DArray(v[i] || emptyTexture2dArray, units[i]);
  10949. }
  10950. } // Helper to pick the right setter for a pure (bottom-level) array
  10951. function getPureArraySetter(type) {
  10952. switch (type) {
  10953. case 0x1406:
  10954. return setValueV1fArray;
  10955. // FLOAT
  10956. case 0x8b50:
  10957. return setValueV2fArray;
  10958. // _VEC2
  10959. case 0x8b51:
  10960. return setValueV3fArray;
  10961. // _VEC3
  10962. case 0x8b52:
  10963. return setValueV4fArray;
  10964. // _VEC4
  10965. case 0x8b5a:
  10966. return setValueM2Array;
  10967. // _MAT2
  10968. case 0x8b5b:
  10969. return setValueM3Array;
  10970. // _MAT3
  10971. case 0x8b5c:
  10972. return setValueM4Array;
  10973. // _MAT4
  10974. case 0x1404:
  10975. case 0x8b56:
  10976. return setValueV1iArray;
  10977. // INT, BOOL
  10978. case 0x8b53:
  10979. case 0x8b57:
  10980. return setValueV2iArray;
  10981. // _VEC2
  10982. case 0x8b54:
  10983. case 0x8b58:
  10984. return setValueV3iArray;
  10985. // _VEC3
  10986. case 0x8b55:
  10987. case 0x8b59:
  10988. return setValueV4iArray;
  10989. // _VEC4
  10990. case 0x1405:
  10991. return setValueV1uiArray;
  10992. // UINT
  10993. case 0x8dc6:
  10994. return setValueV2uiArray;
  10995. // _VEC2
  10996. case 0x8dc7:
  10997. return setValueV3uiArray;
  10998. // _VEC3
  10999. case 0x8dc8:
  11000. return setValueV4uiArray;
  11001. // _VEC4
  11002. case 0x8b5e: // SAMPLER_2D
  11003. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11004. case 0x8dca: // INT_SAMPLER_2D
  11005. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11006. case 0x8b62:
  11007. // SAMPLER_2D_SHADOW
  11008. return setValueT1Array;
  11009. case 0x8b5f: // SAMPLER_3D
  11010. case 0x8dcb: // INT_SAMPLER_3D
  11011. case 0x8dd3:
  11012. // UNSIGNED_INT_SAMPLER_3D
  11013. return setValueT3DArray;
  11014. case 0x8b60: // SAMPLER_CUBE
  11015. case 0x8dcc: // INT_SAMPLER_CUBE
  11016. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11017. case 0x8dc5:
  11018. // SAMPLER_CUBE_SHADOW
  11019. return setValueT6Array;
  11020. case 0x8dc1: // SAMPLER_2D_ARRAY
  11021. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11022. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11023. case 0x8dc4:
  11024. // SAMPLER_2D_ARRAY_SHADOW
  11025. return setValueT2DArrayArray;
  11026. }
  11027. } // --- Uniform Classes ---
  11028. function SingleUniform(id, activeInfo, addr) {
  11029. this.id = id;
  11030. this.addr = addr;
  11031. this.cache = [];
  11032. this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  11033. }
  11034. function PureArrayUniform(id, activeInfo, addr) {
  11035. this.id = id;
  11036. this.addr = addr;
  11037. this.cache = [];
  11038. this.size = activeInfo.size;
  11039. this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  11040. }
  11041. PureArrayUniform.prototype.updateCache = function (data) {
  11042. const cache = this.cache;
  11043. if (data instanceof Float32Array && cache.length !== data.length) {
  11044. this.cache = new Float32Array(data.length);
  11045. }
  11046. copyArray(cache, data);
  11047. };
  11048. function StructuredUniform(id) {
  11049. this.id = id;
  11050. this.seq = [];
  11051. this.map = {};
  11052. }
  11053. StructuredUniform.prototype.setValue = function (gl, value, textures) {
  11054. const seq = this.seq;
  11055. for (let i = 0, n = seq.length; i !== n; ++i) {
  11056. const u = seq[i];
  11057. u.setValue(gl, value[u.id], textures);
  11058. }
  11059. }; // --- Top-level ---
  11060. // Parser - builds up the property tree from the path strings
  11061. const RePathPart = /(\w+)(\])?(\[|\.)?/g; // extracts
  11062. // - the identifier (member name or array index)
  11063. // - followed by an optional right bracket (found when array index)
  11064. // - followed by an optional left bracket or dot (type of subscript)
  11065. //
  11066. // Note: These portions can be read in a non-overlapping fashion and
  11067. // allow straightforward parsing of the hierarchy that WebGL encodes
  11068. // in the uniform names.
  11069. function addUniform(container, uniformObject) {
  11070. container.seq.push(uniformObject);
  11071. container.map[uniformObject.id] = uniformObject;
  11072. }
  11073. function parseUniform(activeInfo, addr, container) {
  11074. const path = activeInfo.name,
  11075. pathLength = path.length; // reset RegExp object, because of the early exit of a previous run
  11076. RePathPart.lastIndex = 0;
  11077. while (true) {
  11078. const match = RePathPart.exec(path),
  11079. matchEnd = RePathPart.lastIndex;
  11080. let id = match[1];
  11081. const idIsIndex = match[2] === ']',
  11082. subscript = match[3];
  11083. if (idIsIndex) id = id | 0; // convert to integer
  11084. if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
  11085. // bare name or "pure" bottom-level array "[0]" suffix
  11086. addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
  11087. break;
  11088. } else {
  11089. // step into inner node / create it in case it doesn't exist
  11090. const map = container.map;
  11091. let next = map[id];
  11092. if (next === undefined) {
  11093. next = new StructuredUniform(id);
  11094. addUniform(container, next);
  11095. }
  11096. container = next;
  11097. }
  11098. }
  11099. } // Root Container
  11100. function WebGLUniforms(gl, program) {
  11101. this.seq = [];
  11102. this.map = {};
  11103. const n = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  11104. for (let i = 0; i < n; ++i) {
  11105. const info = gl.getActiveUniform(program, i),
  11106. addr = gl.getUniformLocation(program, info.name);
  11107. parseUniform(info, addr, this);
  11108. }
  11109. }
  11110. WebGLUniforms.prototype.setValue = function (gl, name, value, textures) {
  11111. const u = this.map[name];
  11112. if (u !== undefined) u.setValue(gl, value, textures);
  11113. };
  11114. WebGLUniforms.prototype.setOptional = function (gl, object, name) {
  11115. const v = object[name];
  11116. if (v !== undefined) this.setValue(gl, name, v);
  11117. }; // Static interface
  11118. WebGLUniforms.upload = function (gl, seq, values, textures) {
  11119. for (let i = 0, n = seq.length; i !== n; ++i) {
  11120. const u = seq[i],
  11121. v = values[u.id];
  11122. if (v.needsUpdate !== false) {
  11123. // note: always updating when .needsUpdate is undefined
  11124. u.setValue(gl, v.value, textures);
  11125. }
  11126. }
  11127. };
  11128. WebGLUniforms.seqWithValue = function (seq, values) {
  11129. const r = [];
  11130. for (let i = 0, n = seq.length; i !== n; ++i) {
  11131. const u = seq[i];
  11132. if (u.id in values) r.push(u);
  11133. }
  11134. return r;
  11135. };
  11136. function WebGLShader(gl, type, string) {
  11137. const shader = gl.createShader(type);
  11138. gl.shaderSource(shader, string);
  11139. gl.compileShader(shader);
  11140. return shader;
  11141. }
  11142. let programIdCount = 0;
  11143. function addLineNumbers(string) {
  11144. const lines = string.split('\n');
  11145. for (let i = 0; i < lines.length; i++) {
  11146. lines[i] = i + 1 + ': ' + lines[i];
  11147. }
  11148. return lines.join('\n');
  11149. }
  11150. function getEncodingComponents(encoding) {
  11151. switch (encoding) {
  11152. case LinearEncoding:
  11153. return ['Linear', '( value )'];
  11154. case sRGBEncoding:
  11155. return ['sRGB', '( value )'];
  11156. default:
  11157. console.warn('THREE.WebGLProgram: Unsupported encoding:', encoding);
  11158. return ['Linear', '( value )'];
  11159. }
  11160. }
  11161. function getShaderErrors(gl, shader, type) {
  11162. const status = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  11163. const errors = gl.getShaderInfoLog(shader).trim();
  11164. if (status && errors === '') return ''; // --enable-privileged-webgl-extension
  11165. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  11166. return type.toUpperCase() + '\n\n' + errors + '\n\n' + addLineNumbers(gl.getShaderSource(shader));
  11167. }
  11168. function getTexelDecodingFunction(functionName, encoding) {
  11169. const components = getEncodingComponents(encoding);
  11170. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[0] + 'ToLinear' + components[1] + '; }';
  11171. }
  11172. function getTexelEncodingFunction(functionName, encoding) {
  11173. const components = getEncodingComponents(encoding);
  11174. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
  11175. }
  11176. function getToneMappingFunction(functionName, toneMapping) {
  11177. let toneMappingName;
  11178. switch (toneMapping) {
  11179. case LinearToneMapping:
  11180. toneMappingName = 'Linear';
  11181. break;
  11182. case ReinhardToneMapping:
  11183. toneMappingName = 'Reinhard';
  11184. break;
  11185. case CineonToneMapping:
  11186. toneMappingName = 'OptimizedCineon';
  11187. break;
  11188. case ACESFilmicToneMapping:
  11189. toneMappingName = 'ACESFilmic';
  11190. break;
  11191. case CustomToneMapping:
  11192. toneMappingName = 'Custom';
  11193. break;
  11194. default:
  11195. console.warn('THREE.WebGLProgram: Unsupported toneMapping:', toneMapping);
  11196. toneMappingName = 'Linear';
  11197. }
  11198. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  11199. }
  11200. function generateExtensions(parameters) {
  11201. const chunks = [parameters.extensionDerivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ? '#extension GL_OES_standard_derivatives : enable' : '', (parameters.extensionFragDepth || parameters.logarithmicDepthBuffer) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '', parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ? '#extension GL_EXT_draw_buffers : require' : '', (parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''];
  11202. return chunks.filter(filterEmptyLine).join('\n');
  11203. }
  11204. function generateDefines(defines) {
  11205. const chunks = [];
  11206. for (const name in defines) {
  11207. const value = defines[name];
  11208. if (value === false) continue;
  11209. chunks.push('#define ' + name + ' ' + value);
  11210. }
  11211. return chunks.join('\n');
  11212. }
  11213. function fetchAttributeLocations(gl, program) {
  11214. const attributes = {};
  11215. const n = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
  11216. for (let i = 0; i < n; i++) {
  11217. const info = gl.getActiveAttrib(program, i);
  11218. const name = info.name;
  11219. let locationSize = 1;
  11220. if (info.type === gl.FLOAT_MAT2) locationSize = 2;
  11221. if (info.type === gl.FLOAT_MAT3) locationSize = 3;
  11222. if (info.type === gl.FLOAT_MAT4) locationSize = 4; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11223. attributes[name] = {
  11224. type: info.type,
  11225. location: gl.getAttribLocation(program, name),
  11226. locationSize: locationSize
  11227. };
  11228. }
  11229. return attributes;
  11230. }
  11231. function filterEmptyLine(string) {
  11232. return string !== '';
  11233. }
  11234. function replaceLightNums(string, parameters) {
  11235. 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);
  11236. }
  11237. function replaceClippingPlaneNums(string, parameters) {
  11238. return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
  11239. } // Resolve Includes
  11240. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11241. function resolveIncludes(string) {
  11242. return string.replace(includePattern, includeReplacer);
  11243. }
  11244. function includeReplacer(match, include) {
  11245. const string = ShaderChunk[include];
  11246. if (string === undefined) {
  11247. throw new Error('Can not resolve #include <' + include + '>');
  11248. }
  11249. return resolveIncludes(string);
  11250. } // Unroll Loops
  11251. const deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  11252. 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;
  11253. function unrollLoops(string) {
  11254. return string.replace(unrollLoopPattern, loopReplacer).replace(deprecatedUnrollLoopPattern, deprecatedLoopReplacer);
  11255. }
  11256. function deprecatedLoopReplacer(match, start, end, snippet) {
  11257. console.warn('WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.');
  11258. return loopReplacer(match, start, end, snippet);
  11259. }
  11260. function loopReplacer(match, start, end, snippet) {
  11261. let string = '';
  11262. for (let i = parseInt(start); i < parseInt(end); i++) {
  11263. string += snippet.replace(/\[\s*i\s*\]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);
  11264. }
  11265. return string;
  11266. } //
  11267. function generatePrecision(parameters) {
  11268. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  11269. if (parameters.precision === 'highp') {
  11270. precisionstring += '\n#define HIGH_PRECISION';
  11271. } else if (parameters.precision === 'mediump') {
  11272. precisionstring += '\n#define MEDIUM_PRECISION';
  11273. } else if (parameters.precision === 'lowp') {
  11274. precisionstring += '\n#define LOW_PRECISION';
  11275. }
  11276. return precisionstring;
  11277. }
  11278. function generateShadowMapTypeDefine(parameters) {
  11279. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11280. if (parameters.shadowMapType === PCFShadowMap) {
  11281. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11282. } else if (parameters.shadowMapType === PCFSoftShadowMap) {
  11283. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11284. } else if (parameters.shadowMapType === VSMShadowMap) {
  11285. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11286. }
  11287. return shadowMapTypeDefine;
  11288. }
  11289. function generateEnvMapTypeDefine(parameters) {
  11290. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11291. if (parameters.envMap) {
  11292. switch (parameters.envMapMode) {
  11293. case CubeReflectionMapping:
  11294. case CubeRefractionMapping:
  11295. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11296. break;
  11297. case CubeUVReflectionMapping:
  11298. case CubeUVRefractionMapping:
  11299. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11300. break;
  11301. }
  11302. }
  11303. return envMapTypeDefine;
  11304. }
  11305. function generateEnvMapModeDefine(parameters) {
  11306. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11307. if (parameters.envMap) {
  11308. switch (parameters.envMapMode) {
  11309. case CubeRefractionMapping:
  11310. case CubeUVRefractionMapping:
  11311. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11312. break;
  11313. }
  11314. }
  11315. return envMapModeDefine;
  11316. }
  11317. function generateEnvMapBlendingDefine(parameters) {
  11318. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11319. if (parameters.envMap) {
  11320. switch (parameters.combine) {
  11321. case MultiplyOperation:
  11322. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11323. break;
  11324. case MixOperation:
  11325. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11326. break;
  11327. case AddOperation:
  11328. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11329. break;
  11330. }
  11331. }
  11332. return envMapBlendingDefine;
  11333. }
  11334. function WebGLProgram(renderer, cacheKey, parameters, bindingStates) {
  11335. // TODO Send this event to Three.js DevTools
  11336. // console.log( 'WebGLProgram', cacheKey );
  11337. const gl = renderer.getContext();
  11338. const defines = parameters.defines;
  11339. let vertexShader = parameters.vertexShader;
  11340. let fragmentShader = parameters.fragmentShader;
  11341. const shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
  11342. const envMapTypeDefine = generateEnvMapTypeDefine(parameters);
  11343. const envMapModeDefine = generateEnvMapModeDefine(parameters);
  11344. const envMapBlendingDefine = generateEnvMapBlendingDefine(parameters);
  11345. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions(parameters);
  11346. const customDefines = generateDefines(defines);
  11347. const program = gl.createProgram();
  11348. let prefixVertex, prefixFragment;
  11349. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  11350. if (parameters.isRawShaderMaterial) {
  11351. prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
  11352. if (prefixVertex.length > 0) {
  11353. prefixVertex += '\n';
  11354. }
  11355. prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
  11356. if (prefixFragment.length > 0) {
  11357. prefixFragment += '\n';
  11358. }
  11359. } else {
  11360. 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 MAX_BONES ' + parameters.maxBones, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '', parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '', 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.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '', parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '', 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.morphTargets && parameters.isWebGL2 ? '#define MORPHTARGETS_TEXTURE' : '', parameters.morphTargets && parameters.isWebGL2 ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '', 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', '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )', ' 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');
  11361. prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.matcap ? '#define USE_MATCAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapTypeDefine : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.envMap ? '#define ' + envMapBlendingDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoat ? '#define USE_CLEARCOAT' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '', parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.alphaTest ? '#define USE_ALPHATEST' : '', parameters.sheen ? '#define USE_SHEEN' : '', parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '', parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '', 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
  11362. parameters.toneMapping !== NoToneMapping ? getToneMappingFunction('toneMapping', parameters.toneMapping) : '', parameters.dithering ? '#define DITHERING' : '', parameters.format === RGBFormat ? '#define OPAQUE' : '', ShaderChunk['encodings_pars_fragment'], // this code is required here because it is used by the various encoding/decoding function defined below
  11363. 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.specularColorMap ? getTexelDecodingFunction('specularColorMapTexelToLinear', parameters.specularColorMapEncoding) : '', parameters.sheenColorMap ? getTexelDecodingFunction('sheenColorMapTexelToLinear', parameters.sheenColorMapEncoding) : '', parameters.lightMap ? getTexelDecodingFunction('lightMapTexelToLinear', parameters.lightMapEncoding) : '', getTexelEncodingFunction('linearToOutputTexel', parameters.outputEncoding), parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', '\n'].filter(filterEmptyLine).join('\n');
  11364. }
  11365. vertexShader = resolveIncludes(vertexShader);
  11366. vertexShader = replaceLightNums(vertexShader, parameters);
  11367. vertexShader = replaceClippingPlaneNums(vertexShader, parameters);
  11368. fragmentShader = resolveIncludes(fragmentShader);
  11369. fragmentShader = replaceLightNums(fragmentShader, parameters);
  11370. fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);
  11371. vertexShader = unrollLoops(vertexShader);
  11372. fragmentShader = unrollLoops(fragmentShader);
  11373. if (parameters.isWebGL2 && parameters.isRawShaderMaterial !== true) {
  11374. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11375. versionString = '#version 300 es\n';
  11376. prefixVertex = ['precision mediump sampler2DArray;', '#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;
  11377. prefixFragment = ['#define varying in', parameters.glslVersion === GLSL3 ? '' : 'layout(location = 0) 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;
  11378. }
  11379. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11380. const fragmentGlsl = versionString + prefixFragment + fragmentShader; // console.log( '*VERTEX*', vertexGlsl );
  11381. // console.log( '*FRAGMENT*', fragmentGlsl );
  11382. const glVertexShader = WebGLShader(gl, gl.VERTEX_SHADER, vertexGlsl);
  11383. const glFragmentShader = WebGLShader(gl, gl.FRAGMENT_SHADER, fragmentGlsl);
  11384. gl.attachShader(program, glVertexShader);
  11385. gl.attachShader(program, glFragmentShader); // Force a particular attribute to index 0.
  11386. if (parameters.index0AttributeName !== undefined) {
  11387. gl.bindAttribLocation(program, 0, parameters.index0AttributeName);
  11388. } else if (parameters.morphTargets === true) {
  11389. // programs with morphTargets displace position out of attribute 0
  11390. gl.bindAttribLocation(program, 0, 'position');
  11391. }
  11392. gl.linkProgram(program); // check for link errors
  11393. if (renderer.debug.checkShaderErrors) {
  11394. const programLog = gl.getProgramInfoLog(program).trim();
  11395. const vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
  11396. const fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
  11397. let runnable = true;
  11398. let haveDiagnostics = true;
  11399. if (gl.getProgramParameter(program, gl.LINK_STATUS) === false) {
  11400. runnable = false;
  11401. const vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
  11402. const fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
  11403. console.error('THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' + 'VALIDATE_STATUS ' + gl.getProgramParameter(program, gl.VALIDATE_STATUS) + '\n\n' + 'Program Info Log: ' + programLog + '\n' + vertexErrors + '\n' + fragmentErrors);
  11404. } else if (programLog !== '') {
  11405. console.warn('THREE.WebGLProgram: Program Info Log:', programLog);
  11406. } else if (vertexLog === '' || fragmentLog === '') {
  11407. haveDiagnostics = false;
  11408. }
  11409. if (haveDiagnostics) {
  11410. this.diagnostics = {
  11411. runnable: runnable,
  11412. programLog: programLog,
  11413. vertexShader: {
  11414. log: vertexLog,
  11415. prefix: prefixVertex
  11416. },
  11417. fragmentShader: {
  11418. log: fragmentLog,
  11419. prefix: prefixFragment
  11420. }
  11421. };
  11422. }
  11423. } // Clean up
  11424. // Crashes in iOS9 and iOS10. #18402
  11425. // gl.detachShader( program, glVertexShader );
  11426. // gl.detachShader( program, glFragmentShader );
  11427. gl.deleteShader(glVertexShader);
  11428. gl.deleteShader(glFragmentShader); // set up caching for uniform locations
  11429. let cachedUniforms;
  11430. this.getUniforms = function () {
  11431. if (cachedUniforms === undefined) {
  11432. cachedUniforms = new WebGLUniforms(gl, program);
  11433. }
  11434. return cachedUniforms;
  11435. }; // set up caching for attribute locations
  11436. let cachedAttributes;
  11437. this.getAttributes = function () {
  11438. if (cachedAttributes === undefined) {
  11439. cachedAttributes = fetchAttributeLocations(gl, program);
  11440. }
  11441. return cachedAttributes;
  11442. }; // free resource
  11443. this.destroy = function () {
  11444. bindingStates.releaseStatesOfProgram(this);
  11445. gl.deleteProgram(program);
  11446. this.program = undefined;
  11447. }; //
  11448. this.name = parameters.shaderName;
  11449. this.id = programIdCount++;
  11450. this.cacheKey = cacheKey;
  11451. this.usedTimes = 1;
  11452. this.program = program;
  11453. this.vertexShader = glVertexShader;
  11454. this.fragmentShader = glFragmentShader;
  11455. return this;
  11456. }
  11457. let _id = 0;
  11458. class WebGLShaderCache {
  11459. constructor() {
  11460. this.shaderCache = new Map();
  11461. this.materialCache = new Map();
  11462. }
  11463. update(material) {
  11464. const vertexShader = material.vertexShader;
  11465. const fragmentShader = material.fragmentShader;
  11466. const vertexShaderStage = this._getShaderStage(vertexShader);
  11467. const fragmentShaderStage = this._getShaderStage(fragmentShader);
  11468. const materialShaders = this._getShaderCacheForMaterial(material);
  11469. if (materialShaders.has(vertexShaderStage) === false) {
  11470. materialShaders.add(vertexShaderStage);
  11471. vertexShaderStage.usedTimes++;
  11472. }
  11473. if (materialShaders.has(fragmentShaderStage) === false) {
  11474. materialShaders.add(fragmentShaderStage);
  11475. fragmentShaderStage.usedTimes++;
  11476. }
  11477. return this;
  11478. }
  11479. remove(material) {
  11480. const materialShaders = this.materialCache.get(material);
  11481. for (const shaderStage of materialShaders) {
  11482. shaderStage.usedTimes--;
  11483. if (shaderStage.usedTimes === 0) this.shaderCache.delete(shaderStage);
  11484. }
  11485. this.materialCache.delete(material);
  11486. return this;
  11487. }
  11488. getVertexShaderID(material) {
  11489. return this._getShaderStage(material.vertexShader).id;
  11490. }
  11491. getFragmentShaderID(material) {
  11492. return this._getShaderStage(material.fragmentShader).id;
  11493. }
  11494. dispose() {
  11495. this.shaderCache.clear();
  11496. this.materialCache.clear();
  11497. }
  11498. _getShaderCacheForMaterial(material) {
  11499. const cache = this.materialCache;
  11500. if (cache.has(material) === false) {
  11501. cache.set(material, new Set());
  11502. }
  11503. return cache.get(material);
  11504. }
  11505. _getShaderStage(code) {
  11506. const cache = this.shaderCache;
  11507. if (cache.has(code) === false) {
  11508. const stage = new WebGLShaderStage();
  11509. cache.set(code, stage);
  11510. }
  11511. return cache.get(code);
  11512. }
  11513. }
  11514. class WebGLShaderStage {
  11515. constructor() {
  11516. this.id = _id++;
  11517. this.usedTimes = 0;
  11518. }
  11519. }
  11520. function WebGLPrograms(renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping) {
  11521. const _programLayers = new Layers();
  11522. const _customShaders = new WebGLShaderCache();
  11523. const programs = [];
  11524. const isWebGL2 = capabilities.isWebGL2;
  11525. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11526. const floatVertexTextures = capabilities.floatVertexTextures;
  11527. const maxVertexUniforms = capabilities.maxVertexUniforms;
  11528. const vertexTextures = capabilities.vertexTextures;
  11529. let precision = capabilities.precision;
  11530. const shaderIDs = {
  11531. MeshDepthMaterial: 'depth',
  11532. MeshDistanceMaterial: 'distanceRGBA',
  11533. MeshNormalMaterial: 'normal',
  11534. MeshBasicMaterial: 'basic',
  11535. MeshLambertMaterial: 'lambert',
  11536. MeshPhongMaterial: 'phong',
  11537. MeshToonMaterial: 'toon',
  11538. MeshStandardMaterial: 'physical',
  11539. MeshPhysicalMaterial: 'physical',
  11540. MeshMatcapMaterial: 'matcap',
  11541. LineBasicMaterial: 'basic',
  11542. LineDashedMaterial: 'dashed',
  11543. PointsMaterial: 'points',
  11544. ShadowMaterial: 'shadow',
  11545. SpriteMaterial: 'sprite'
  11546. };
  11547. function getMaxBones(object) {
  11548. const skeleton = object.skeleton;
  11549. const bones = skeleton.bones;
  11550. if (floatVertexTextures) {
  11551. return 1024;
  11552. } else {
  11553. // default for when object is not specified
  11554. // ( for example when prebuilding shader to be used with multiple objects )
  11555. //
  11556. // - leave some extra space for other uniforms
  11557. // - limit here is ANGLE's 254 max uniform vectors
  11558. // (up to 54 should be safe)
  11559. const nVertexUniforms = maxVertexUniforms;
  11560. const nVertexMatrices = Math.floor((nVertexUniforms - 20) / 4);
  11561. const maxBones = Math.min(nVertexMatrices, bones.length);
  11562. if (maxBones < bones.length) {
  11563. console.warn('THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.');
  11564. return 0;
  11565. }
  11566. return maxBones;
  11567. }
  11568. }
  11569. function getTextureEncodingFromMap(map) {
  11570. let encoding;
  11571. if (map && map.isTexture) {
  11572. encoding = map.encoding;
  11573. } else if (map && map.isWebGLRenderTarget) {
  11574. console.warn('THREE.WebGLPrograms.getTextureEncodingFromMap: don\'t use render targets as textures. Use their .texture property instead.');
  11575. encoding = map.texture.encoding;
  11576. } else {
  11577. encoding = LinearEncoding;
  11578. }
  11579. if (isWebGL2 && map && map.isTexture && map.format === RGBAFormat && map.type === UnsignedByteType && map.encoding === sRGBEncoding) {
  11580. encoding = LinearEncoding; // disable inline decode for sRGB textures in WebGL 2
  11581. }
  11582. return encoding;
  11583. }
  11584. function getParameters(material, lights, shadows, scene, object) {
  11585. const fog = scene.fog;
  11586. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  11587. const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment);
  11588. const shaderID = shaderIDs[material.type]; // heuristics to create shader parameters according to lights in the scene
  11589. // (not to blow over maxLights budget)
  11590. const maxBones = object.isSkinnedMesh ? getMaxBones(object) : 0;
  11591. if (material.precision !== null) {
  11592. precision = capabilities.getMaxPrecision(material.precision);
  11593. if (precision !== material.precision) {
  11594. console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
  11595. }
  11596. }
  11597. let vertexShader, fragmentShader;
  11598. let customVertexShaderID, customFragmentShaderID;
  11599. if (shaderID) {
  11600. const shader = ShaderLib[shaderID];
  11601. vertexShader = shader.vertexShader;
  11602. fragmentShader = shader.fragmentShader;
  11603. } else {
  11604. vertexShader = material.vertexShader;
  11605. fragmentShader = material.fragmentShader;
  11606. _customShaders.update(material);
  11607. customVertexShaderID = _customShaders.getVertexShaderID(material);
  11608. customFragmentShaderID = _customShaders.getFragmentShaderID(material);
  11609. }
  11610. const currentRenderTarget = renderer.getRenderTarget();
  11611. const useAlphaTest = material.alphaTest > 0;
  11612. const useClearcoat = material.clearcoat > 0;
  11613. const parameters = {
  11614. isWebGL2: isWebGL2,
  11615. shaderID: shaderID,
  11616. shaderName: material.type,
  11617. vertexShader: vertexShader,
  11618. fragmentShader: fragmentShader,
  11619. defines: material.defines,
  11620. customVertexShaderID: customVertexShaderID,
  11621. customFragmentShaderID: customFragmentShaderID,
  11622. isRawShaderMaterial: material.isRawShaderMaterial === true,
  11623. glslVersion: material.glslVersion,
  11624. precision: precision,
  11625. instancing: object.isInstancedMesh === true,
  11626. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  11627. supportsVertexTextures: vertexTextures,
  11628. outputEncoding: currentRenderTarget !== null ? getTextureEncodingFromMap(currentRenderTarget.texture) : renderer.outputEncoding,
  11629. map: !!material.map,
  11630. mapEncoding: getTextureEncodingFromMap(material.map),
  11631. matcap: !!material.matcap,
  11632. matcapEncoding: getTextureEncodingFromMap(material.matcap),
  11633. envMap: !!envMap,
  11634. envMapMode: envMap && envMap.mapping,
  11635. envMapEncoding: getTextureEncodingFromMap(envMap),
  11636. envMapCubeUV: !!envMap && (envMap.mapping === CubeUVReflectionMapping || envMap.mapping === CubeUVRefractionMapping),
  11637. lightMap: !!material.lightMap,
  11638. lightMapEncoding: getTextureEncodingFromMap(material.lightMap),
  11639. aoMap: !!material.aoMap,
  11640. emissiveMap: !!material.emissiveMap,
  11641. emissiveMapEncoding: getTextureEncodingFromMap(material.emissiveMap),
  11642. bumpMap: !!material.bumpMap,
  11643. normalMap: !!material.normalMap,
  11644. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  11645. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  11646. clearcoat: useClearcoat,
  11647. clearcoatMap: useClearcoat && !!material.clearcoatMap,
  11648. clearcoatRoughnessMap: useClearcoat && !!material.clearcoatRoughnessMap,
  11649. clearcoatNormalMap: useClearcoat && !!material.clearcoatNormalMap,
  11650. displacementMap: !!material.displacementMap,
  11651. roughnessMap: !!material.roughnessMap,
  11652. metalnessMap: !!material.metalnessMap,
  11653. specularMap: !!material.specularMap,
  11654. specularIntensityMap: !!material.specularIntensityMap,
  11655. specularColorMap: !!material.specularColorMap,
  11656. specularColorMapEncoding: getTextureEncodingFromMap(material.specularColorMap),
  11657. alphaMap: !!material.alphaMap,
  11658. alphaTest: useAlphaTest,
  11659. gradientMap: !!material.gradientMap,
  11660. sheen: material.sheen > 0,
  11661. sheenColorMap: !!material.sheenColorMap,
  11662. sheenColorMapEncoding: getTextureEncodingFromMap(material.sheenColorMap),
  11663. sheenRoughnessMap: !!material.sheenRoughnessMap,
  11664. transmission: material.transmission > 0,
  11665. transmissionMap: !!material.transmissionMap,
  11666. thicknessMap: !!material.thicknessMap,
  11667. combine: material.combine,
  11668. vertexTangents: !!material.normalMap && !!object.geometry && !!object.geometry.attributes.tangent,
  11669. vertexColors: material.vertexColors,
  11670. vertexAlphas: material.vertexColors === true && !!object.geometry && !!object.geometry.attributes.color && object.geometry.attributes.color.itemSize === 4,
  11671. vertexUvs: !!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatMap || !!material.clearcoatRoughnessMap || !!material.clearcoatNormalMap || !!material.displacementMap || !!material.transmissionMap || !!material.thicknessMap || !!material.specularIntensityMap || !!material.specularColorMap || !!material.sheenColorMap || !!material.sheenRoughnessMap,
  11672. uvsVertexOnly: !(!!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatNormalMap || material.transmission > 0 || !!material.transmissionMap || !!material.thicknessMap || !!material.specularIntensityMap || !!material.specularColorMap || material.sheen > 0 || !!material.sheenColorMap || !!material.sheenRoughnessMap) && !!material.displacementMap,
  11673. fog: !!fog,
  11674. useFog: material.fog,
  11675. fogExp2: fog && fog.isFogExp2,
  11676. flatShading: !!material.flatShading,
  11677. sizeAttenuation: material.sizeAttenuation,
  11678. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11679. skinning: object.isSkinnedMesh === true && maxBones > 0,
  11680. maxBones: maxBones,
  11681. useVertexTexture: floatVertexTextures,
  11682. morphTargets: !!object.geometry && !!object.geometry.morphAttributes.position,
  11683. morphNormals: !!object.geometry && !!object.geometry.morphAttributes.normal,
  11684. morphTargetsCount: !!object.geometry && !!object.geometry.morphAttributes.position ? object.geometry.morphAttributes.position.length : 0,
  11685. numDirLights: lights.directional.length,
  11686. numPointLights: lights.point.length,
  11687. numSpotLights: lights.spot.length,
  11688. numRectAreaLights: lights.rectArea.length,
  11689. numHemiLights: lights.hemi.length,
  11690. numDirLightShadows: lights.directionalShadowMap.length,
  11691. numPointLightShadows: lights.pointShadowMap.length,
  11692. numSpotLightShadows: lights.spotShadowMap.length,
  11693. numClippingPlanes: clipping.numPlanes,
  11694. numClipIntersection: clipping.numIntersection,
  11695. format: material.format,
  11696. dithering: material.dithering,
  11697. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  11698. shadowMapType: renderer.shadowMap.type,
  11699. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  11700. physicallyCorrectLights: renderer.physicallyCorrectLights,
  11701. premultipliedAlpha: material.premultipliedAlpha,
  11702. doubleSided: material.side === DoubleSide,
  11703. flipSided: material.side === BackSide,
  11704. depthPacking: material.depthPacking !== undefined ? material.depthPacking : false,
  11705. index0AttributeName: material.index0AttributeName,
  11706. extensionDerivatives: material.extensions && material.extensions.derivatives,
  11707. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  11708. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  11709. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  11710. rendererExtensionFragDepth: isWebGL2 || extensions.has('EXT_frag_depth'),
  11711. rendererExtensionDrawBuffers: isWebGL2 || extensions.has('WEBGL_draw_buffers'),
  11712. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has('EXT_shader_texture_lod'),
  11713. customProgramCacheKey: material.customProgramCacheKey()
  11714. };
  11715. return parameters;
  11716. }
  11717. function getProgramCacheKey(parameters) {
  11718. const array = [];
  11719. if (parameters.shaderID) {
  11720. array.push(parameters.shaderID);
  11721. } else {
  11722. array.push(parameters.customVertexShaderID);
  11723. array.push(parameters.customFragmentShaderID);
  11724. }
  11725. if (parameters.defines !== undefined) {
  11726. for (const name in parameters.defines) {
  11727. array.push(name);
  11728. array.push(parameters.defines[name]);
  11729. }
  11730. }
  11731. if (parameters.isRawShaderMaterial === false) {
  11732. getProgramCacheKeyParameters(array, parameters);
  11733. getProgramCacheKeyBooleans(array, parameters);
  11734. array.push(renderer.outputEncoding);
  11735. }
  11736. array.push(parameters.customProgramCacheKey);
  11737. return array.join();
  11738. }
  11739. function getProgramCacheKeyParameters(array, parameters) {
  11740. array.push(parameters.precision);
  11741. array.push(parameters.outputEncoding);
  11742. array.push(parameters.mapEncoding);
  11743. array.push(parameters.matcapEncoding);
  11744. array.push(parameters.envMapMode);
  11745. array.push(parameters.envMapEncoding);
  11746. array.push(parameters.lightMapEncoding);
  11747. array.push(parameters.emissiveMapEncoding);
  11748. array.push(parameters.combine);
  11749. array.push(parameters.vertexUvs);
  11750. array.push(parameters.fogExp2);
  11751. array.push(parameters.sizeAttenuation);
  11752. array.push(parameters.maxBones);
  11753. array.push(parameters.morphTargetsCount);
  11754. array.push(parameters.numDirLights);
  11755. array.push(parameters.numPointLights);
  11756. array.push(parameters.numSpotLights);
  11757. array.push(parameters.numHemiLights);
  11758. array.push(parameters.numRectAreaLights);
  11759. array.push(parameters.numDirLightShadows);
  11760. array.push(parameters.numPointLightShadows);
  11761. array.push(parameters.numSpotLightShadows);
  11762. array.push(parameters.shadowMapType);
  11763. array.push(parameters.toneMapping);
  11764. array.push(parameters.numClippingPlanes);
  11765. array.push(parameters.numClipIntersection);
  11766. array.push(parameters.format);
  11767. array.push(parameters.specularColorMapEncoding);
  11768. array.push(parameters.sheenColorMapEncoding);
  11769. }
  11770. function getProgramCacheKeyBooleans(array, parameters) {
  11771. _programLayers.disableAll();
  11772. if (parameters.isWebGL2) _programLayers.enable(0);
  11773. if (parameters.supportsVertexTextures) _programLayers.enable(1);
  11774. if (parameters.instancing) _programLayers.enable(2);
  11775. if (parameters.instancingColor) _programLayers.enable(3);
  11776. if (parameters.map) _programLayers.enable(4);
  11777. if (parameters.matcap) _programLayers.enable(5);
  11778. if (parameters.envMap) _programLayers.enable(6);
  11779. if (parameters.envMapCubeUV) _programLayers.enable(7);
  11780. if (parameters.lightMap) _programLayers.enable(8);
  11781. if (parameters.aoMap) _programLayers.enable(9);
  11782. if (parameters.emissiveMap) _programLayers.enable(10);
  11783. if (parameters.bumpMap) _programLayers.enable(11);
  11784. if (parameters.normalMap) _programLayers.enable(12);
  11785. if (parameters.objectSpaceNormalMap) _programLayers.enable(13);
  11786. if (parameters.tangentSpaceNormalMap) _programLayers.enable(14);
  11787. if (parameters.clearcoat) _programLayers.enable(15);
  11788. if (parameters.clearcoatMap) _programLayers.enable(16);
  11789. if (parameters.clearcoatRoughnessMap) _programLayers.enable(17);
  11790. if (parameters.clearcoatNormalMap) _programLayers.enable(18);
  11791. if (parameters.displacementMap) _programLayers.enable(19);
  11792. if (parameters.specularMap) _programLayers.enable(20);
  11793. if (parameters.roughnessMap) _programLayers.enable(21);
  11794. if (parameters.metalnessMap) _programLayers.enable(22);
  11795. if (parameters.gradientMap) _programLayers.enable(23);
  11796. if (parameters.alphaMap) _programLayers.enable(24);
  11797. if (parameters.alphaTest) _programLayers.enable(25);
  11798. if (parameters.vertexColors) _programLayers.enable(26);
  11799. if (parameters.vertexAlphas) _programLayers.enable(27);
  11800. if (parameters.vertexUvs) _programLayers.enable(28);
  11801. if (parameters.vertexTangents) _programLayers.enable(29);
  11802. if (parameters.uvsVertexOnly) _programLayers.enable(30);
  11803. if (parameters.fog) _programLayers.enable(31);
  11804. array.push(_programLayers.mask);
  11805. _programLayers.disableAll();
  11806. if (parameters.useFog) _programLayers.enable(0);
  11807. if (parameters.flatShading) _programLayers.enable(1);
  11808. if (parameters.logarithmicDepthBuffer) _programLayers.enable(2);
  11809. if (parameters.skinning) _programLayers.enable(3);
  11810. if (parameters.useVertexTexture) _programLayers.enable(4);
  11811. if (parameters.morphTargets) _programLayers.enable(5);
  11812. if (parameters.morphNormals) _programLayers.enable(6);
  11813. if (parameters.premultipliedAlpha) _programLayers.enable(7);
  11814. if (parameters.shadowMapEnabled) _programLayers.enable(8);
  11815. if (parameters.physicallyCorrectLights) _programLayers.enable(9);
  11816. if (parameters.doubleSided) _programLayers.enable(10);
  11817. if (parameters.flipSided) _programLayers.enable(11);
  11818. if (parameters.depthPacking) _programLayers.enable(12);
  11819. if (parameters.dithering) _programLayers.enable(13);
  11820. if (parameters.specularIntensityMap) _programLayers.enable(14);
  11821. if (parameters.specularColorMap) _programLayers.enable(15);
  11822. if (parameters.transmission) _programLayers.enable(16);
  11823. if (parameters.transmissionMap) _programLayers.enable(17);
  11824. if (parameters.thicknessMap) _programLayers.enable(18);
  11825. if (parameters.sheen) _programLayers.enable(19);
  11826. if (parameters.sheenColorMap) _programLayers.enable(20);
  11827. if (parameters.sheenRoughnessMap) _programLayers.enable(21);
  11828. array.push(_programLayers.mask);
  11829. }
  11830. function getUniforms(material) {
  11831. const shaderID = shaderIDs[material.type];
  11832. let uniforms;
  11833. if (shaderID) {
  11834. const shader = ShaderLib[shaderID];
  11835. uniforms = UniformsUtils.clone(shader.uniforms);
  11836. } else {
  11837. uniforms = material.uniforms;
  11838. }
  11839. return uniforms;
  11840. }
  11841. function acquireProgram(parameters, cacheKey) {
  11842. let program; // Check if code has been already compiled
  11843. for (let p = 0, pl = programs.length; p < pl; p++) {
  11844. const preexistingProgram = programs[p];
  11845. if (preexistingProgram.cacheKey === cacheKey) {
  11846. program = preexistingProgram;
  11847. ++program.usedTimes;
  11848. break;
  11849. }
  11850. }
  11851. if (program === undefined) {
  11852. program = new WebGLProgram(renderer, cacheKey, parameters, bindingStates);
  11853. programs.push(program);
  11854. }
  11855. return program;
  11856. }
  11857. function releaseProgram(program) {
  11858. if (--program.usedTimes === 0) {
  11859. // Remove from unordered set
  11860. const i = programs.indexOf(program);
  11861. programs[i] = programs[programs.length - 1];
  11862. programs.pop(); // Free WebGL resources
  11863. program.destroy();
  11864. }
  11865. }
  11866. function releaseShaderCache(material) {
  11867. _customShaders.remove(material);
  11868. }
  11869. function dispose() {
  11870. _customShaders.dispose();
  11871. }
  11872. return {
  11873. getParameters: getParameters,
  11874. getProgramCacheKey: getProgramCacheKey,
  11875. getUniforms: getUniforms,
  11876. acquireProgram: acquireProgram,
  11877. releaseProgram: releaseProgram,
  11878. releaseShaderCache: releaseShaderCache,
  11879. // Exposed for resource monitoring & error feedback via renderer.info:
  11880. programs: programs,
  11881. dispose: dispose
  11882. };
  11883. }
  11884. function WebGLProperties() {
  11885. let properties = new WeakMap();
  11886. function get(object) {
  11887. let map = properties.get(object);
  11888. if (map === undefined) {
  11889. map = {};
  11890. properties.set(object, map);
  11891. }
  11892. return map;
  11893. }
  11894. function remove(object) {
  11895. properties.delete(object);
  11896. }
  11897. function update(object, key, value) {
  11898. properties.get(object)[key] = value;
  11899. }
  11900. function dispose() {
  11901. properties = new WeakMap();
  11902. }
  11903. return {
  11904. get: get,
  11905. remove: remove,
  11906. update: update,
  11907. dispose: dispose
  11908. };
  11909. }
  11910. function painterSortStable(a, b) {
  11911. if (a.groupOrder !== b.groupOrder) {
  11912. return a.groupOrder - b.groupOrder;
  11913. } else if (a.renderOrder !== b.renderOrder) {
  11914. return a.renderOrder - b.renderOrder;
  11915. } else if (a.material.id !== b.material.id) {
  11916. return a.material.id - b.material.id;
  11917. } else if (a.z !== b.z) {
  11918. return a.z - b.z;
  11919. } else {
  11920. return a.id - b.id;
  11921. }
  11922. }
  11923. function reversePainterSortStable(a, b) {
  11924. if (a.groupOrder !== b.groupOrder) {
  11925. return a.groupOrder - b.groupOrder;
  11926. } else if (a.renderOrder !== b.renderOrder) {
  11927. return a.renderOrder - b.renderOrder;
  11928. } else if (a.z !== b.z) {
  11929. return b.z - a.z;
  11930. } else {
  11931. return a.id - b.id;
  11932. }
  11933. }
  11934. function WebGLRenderList() {
  11935. const renderItems = [];
  11936. let renderItemsIndex = 0;
  11937. const opaque = [];
  11938. const transmissive = [];
  11939. const transparent = [];
  11940. function init() {
  11941. renderItemsIndex = 0;
  11942. opaque.length = 0;
  11943. transmissive.length = 0;
  11944. transparent.length = 0;
  11945. }
  11946. function getNextRenderItem(object, geometry, material, groupOrder, z, group) {
  11947. let renderItem = renderItems[renderItemsIndex];
  11948. if (renderItem === undefined) {
  11949. renderItem = {
  11950. id: object.id,
  11951. object: object,
  11952. geometry: geometry,
  11953. material: material,
  11954. groupOrder: groupOrder,
  11955. renderOrder: object.renderOrder,
  11956. z: z,
  11957. group: group
  11958. };
  11959. renderItems[renderItemsIndex] = renderItem;
  11960. } else {
  11961. renderItem.id = object.id;
  11962. renderItem.object = object;
  11963. renderItem.geometry = geometry;
  11964. renderItem.material = material;
  11965. renderItem.groupOrder = groupOrder;
  11966. renderItem.renderOrder = object.renderOrder;
  11967. renderItem.z = z;
  11968. renderItem.group = group;
  11969. }
  11970. renderItemsIndex++;
  11971. return renderItem;
  11972. }
  11973. function push(object, geometry, material, groupOrder, z, group) {
  11974. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  11975. if (material.transmission > 0.0) {
  11976. transmissive.push(renderItem);
  11977. } else if (material.transparent === true) {
  11978. transparent.push(renderItem);
  11979. } else {
  11980. opaque.push(renderItem);
  11981. }
  11982. }
  11983. function unshift(object, geometry, material, groupOrder, z, group) {
  11984. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  11985. if (material.transmission > 0.0) {
  11986. transmissive.unshift(renderItem);
  11987. } else if (material.transparent === true) {
  11988. transparent.unshift(renderItem);
  11989. } else {
  11990. opaque.unshift(renderItem);
  11991. }
  11992. }
  11993. function sort(customOpaqueSort, customTransparentSort) {
  11994. if (opaque.length > 1) opaque.sort(customOpaqueSort || painterSortStable);
  11995. if (transmissive.length > 1) transmissive.sort(customTransparentSort || reversePainterSortStable);
  11996. if (transparent.length > 1) transparent.sort(customTransparentSort || reversePainterSortStable);
  11997. }
  11998. function finish() {
  11999. // Clear references from inactive renderItems in the list
  12000. for (let i = renderItemsIndex, il = renderItems.length; i < il; i++) {
  12001. const renderItem = renderItems[i];
  12002. if (renderItem.id === null) break;
  12003. renderItem.id = null;
  12004. renderItem.object = null;
  12005. renderItem.geometry = null;
  12006. renderItem.material = null;
  12007. renderItem.group = null;
  12008. }
  12009. }
  12010. return {
  12011. opaque: opaque,
  12012. transmissive: transmissive,
  12013. transparent: transparent,
  12014. init: init,
  12015. push: push,
  12016. unshift: unshift,
  12017. finish: finish,
  12018. sort: sort
  12019. };
  12020. }
  12021. function WebGLRenderLists() {
  12022. let lists = new WeakMap();
  12023. function get(scene, renderCallDepth) {
  12024. let list;
  12025. if (lists.has(scene) === false) {
  12026. list = new WebGLRenderList();
  12027. lists.set(scene, [list]);
  12028. } else {
  12029. if (renderCallDepth >= lists.get(scene).length) {
  12030. list = new WebGLRenderList();
  12031. lists.get(scene).push(list);
  12032. } else {
  12033. list = lists.get(scene)[renderCallDepth];
  12034. }
  12035. }
  12036. return list;
  12037. }
  12038. function dispose() {
  12039. lists = new WeakMap();
  12040. }
  12041. return {
  12042. get: get,
  12043. dispose: dispose
  12044. };
  12045. }
  12046. function UniformsCache() {
  12047. const lights = {};
  12048. return {
  12049. get: function (light) {
  12050. if (lights[light.id] !== undefined) {
  12051. return lights[light.id];
  12052. }
  12053. let uniforms;
  12054. switch (light.type) {
  12055. case 'DirectionalLight':
  12056. uniforms = {
  12057. direction: new Vector3(),
  12058. color: new Color()
  12059. };
  12060. break;
  12061. case 'SpotLight':
  12062. uniforms = {
  12063. position: new Vector3(),
  12064. direction: new Vector3(),
  12065. color: new Color(),
  12066. distance: 0,
  12067. coneCos: 0,
  12068. penumbraCos: 0,
  12069. decay: 0
  12070. };
  12071. break;
  12072. case 'PointLight':
  12073. uniforms = {
  12074. position: new Vector3(),
  12075. color: new Color(),
  12076. distance: 0,
  12077. decay: 0
  12078. };
  12079. break;
  12080. case 'HemisphereLight':
  12081. uniforms = {
  12082. direction: new Vector3(),
  12083. skyColor: new Color(),
  12084. groundColor: new Color()
  12085. };
  12086. break;
  12087. case 'RectAreaLight':
  12088. uniforms = {
  12089. color: new Color(),
  12090. position: new Vector3(),
  12091. halfWidth: new Vector3(),
  12092. halfHeight: new Vector3()
  12093. };
  12094. break;
  12095. }
  12096. lights[light.id] = uniforms;
  12097. return uniforms;
  12098. }
  12099. };
  12100. }
  12101. function ShadowUniformsCache() {
  12102. const lights = {};
  12103. return {
  12104. get: function (light) {
  12105. if (lights[light.id] !== undefined) {
  12106. return lights[light.id];
  12107. }
  12108. let uniforms;
  12109. switch (light.type) {
  12110. case 'DirectionalLight':
  12111. uniforms = {
  12112. shadowBias: 0,
  12113. shadowNormalBias: 0,
  12114. shadowRadius: 1,
  12115. shadowMapSize: new Vector2()
  12116. };
  12117. break;
  12118. case 'SpotLight':
  12119. uniforms = {
  12120. shadowBias: 0,
  12121. shadowNormalBias: 0,
  12122. shadowRadius: 1,
  12123. shadowMapSize: new Vector2()
  12124. };
  12125. break;
  12126. case 'PointLight':
  12127. uniforms = {
  12128. shadowBias: 0,
  12129. shadowNormalBias: 0,
  12130. shadowRadius: 1,
  12131. shadowMapSize: new Vector2(),
  12132. shadowCameraNear: 1,
  12133. shadowCameraFar: 1000
  12134. };
  12135. break;
  12136. // TODO (abelnation): set RectAreaLight shadow uniforms
  12137. }
  12138. lights[light.id] = uniforms;
  12139. return uniforms;
  12140. }
  12141. };
  12142. }
  12143. let nextVersion = 0;
  12144. function shadowCastingLightsFirst(lightA, lightB) {
  12145. return (lightB.castShadow ? 1 : 0) - (lightA.castShadow ? 1 : 0);
  12146. }
  12147. function WebGLLights(extensions, capabilities) {
  12148. const cache = new UniformsCache();
  12149. const shadowCache = ShadowUniformsCache();
  12150. const state = {
  12151. version: 0,
  12152. hash: {
  12153. directionalLength: -1,
  12154. pointLength: -1,
  12155. spotLength: -1,
  12156. rectAreaLength: -1,
  12157. hemiLength: -1,
  12158. numDirectionalShadows: -1,
  12159. numPointShadows: -1,
  12160. numSpotShadows: -1
  12161. },
  12162. ambient: [0, 0, 0],
  12163. probe: [],
  12164. directional: [],
  12165. directionalShadow: [],
  12166. directionalShadowMap: [],
  12167. directionalShadowMatrix: [],
  12168. spot: [],
  12169. spotShadow: [],
  12170. spotShadowMap: [],
  12171. spotShadowMatrix: [],
  12172. rectArea: [],
  12173. rectAreaLTC1: null,
  12174. rectAreaLTC2: null,
  12175. point: [],
  12176. pointShadow: [],
  12177. pointShadowMap: [],
  12178. pointShadowMatrix: [],
  12179. hemi: []
  12180. };
  12181. for (let i = 0; i < 9; i++) state.probe.push(new Vector3());
  12182. const vector3 = new Vector3();
  12183. const matrix4 = new Matrix4();
  12184. const matrix42 = new Matrix4();
  12185. function setup(lights, physicallyCorrectLights) {
  12186. let r = 0,
  12187. g = 0,
  12188. b = 0;
  12189. for (let i = 0; i < 9; i++) state.probe[i].set(0, 0, 0);
  12190. let directionalLength = 0;
  12191. let pointLength = 0;
  12192. let spotLength = 0;
  12193. let rectAreaLength = 0;
  12194. let hemiLength = 0;
  12195. let numDirectionalShadows = 0;
  12196. let numPointShadows = 0;
  12197. let numSpotShadows = 0;
  12198. lights.sort(shadowCastingLightsFirst); // artist-friendly light intensity scaling factor
  12199. const scaleFactor = physicallyCorrectLights !== true ? Math.PI : 1;
  12200. for (let i = 0, l = lights.length; i < l; i++) {
  12201. const light = lights[i];
  12202. const color = light.color;
  12203. const intensity = light.intensity;
  12204. const distance = light.distance;
  12205. const shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
  12206. if (light.isAmbientLight) {
  12207. r += color.r * intensity * scaleFactor;
  12208. g += color.g * intensity * scaleFactor;
  12209. b += color.b * intensity * scaleFactor;
  12210. } else if (light.isLightProbe) {
  12211. for (let j = 0; j < 9; j++) {
  12212. state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
  12213. }
  12214. } else if (light.isDirectionalLight) {
  12215. const uniforms = cache.get(light);
  12216. uniforms.color.copy(light.color).multiplyScalar(light.intensity * scaleFactor);
  12217. if (light.castShadow) {
  12218. const shadow = light.shadow;
  12219. const shadowUniforms = shadowCache.get(light);
  12220. shadowUniforms.shadowBias = shadow.bias;
  12221. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12222. shadowUniforms.shadowRadius = shadow.radius;
  12223. shadowUniforms.shadowMapSize = shadow.mapSize;
  12224. state.directionalShadow[directionalLength] = shadowUniforms;
  12225. state.directionalShadowMap[directionalLength] = shadowMap;
  12226. state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
  12227. numDirectionalShadows++;
  12228. }
  12229. state.directional[directionalLength] = uniforms;
  12230. directionalLength++;
  12231. } else if (light.isSpotLight) {
  12232. const uniforms = cache.get(light);
  12233. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12234. uniforms.color.copy(color).multiplyScalar(intensity * scaleFactor);
  12235. uniforms.distance = distance;
  12236. uniforms.coneCos = Math.cos(light.angle);
  12237. uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
  12238. uniforms.decay = light.decay;
  12239. if (light.castShadow) {
  12240. const shadow = light.shadow;
  12241. const shadowUniforms = shadowCache.get(light);
  12242. shadowUniforms.shadowBias = shadow.bias;
  12243. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12244. shadowUniforms.shadowRadius = shadow.radius;
  12245. shadowUniforms.shadowMapSize = shadow.mapSize;
  12246. state.spotShadow[spotLength] = shadowUniforms;
  12247. state.spotShadowMap[spotLength] = shadowMap;
  12248. state.spotShadowMatrix[spotLength] = light.shadow.matrix;
  12249. numSpotShadows++;
  12250. }
  12251. state.spot[spotLength] = uniforms;
  12252. spotLength++;
  12253. } else if (light.isRectAreaLight) {
  12254. const uniforms = cache.get(light); // (a) intensity is the total visible light emitted
  12255. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  12256. // (b) intensity is the brightness of the light
  12257. uniforms.color.copy(color).multiplyScalar(intensity);
  12258. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  12259. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  12260. state.rectArea[rectAreaLength] = uniforms;
  12261. rectAreaLength++;
  12262. } else if (light.isPointLight) {
  12263. const uniforms = cache.get(light);
  12264. uniforms.color.copy(light.color).multiplyScalar(light.intensity * scaleFactor);
  12265. uniforms.distance = light.distance;
  12266. uniforms.decay = light.decay;
  12267. if (light.castShadow) {
  12268. const shadow = light.shadow;
  12269. const shadowUniforms = shadowCache.get(light);
  12270. shadowUniforms.shadowBias = shadow.bias;
  12271. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12272. shadowUniforms.shadowRadius = shadow.radius;
  12273. shadowUniforms.shadowMapSize = shadow.mapSize;
  12274. shadowUniforms.shadowCameraNear = shadow.camera.near;
  12275. shadowUniforms.shadowCameraFar = shadow.camera.far;
  12276. state.pointShadow[pointLength] = shadowUniforms;
  12277. state.pointShadowMap[pointLength] = shadowMap;
  12278. state.pointShadowMatrix[pointLength] = light.shadow.matrix;
  12279. numPointShadows++;
  12280. }
  12281. state.point[pointLength] = uniforms;
  12282. pointLength++;
  12283. } else if (light.isHemisphereLight) {
  12284. const uniforms = cache.get(light);
  12285. uniforms.skyColor.copy(light.color).multiplyScalar(intensity * scaleFactor);
  12286. uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity * scaleFactor);
  12287. state.hemi[hemiLength] = uniforms;
  12288. hemiLength++;
  12289. }
  12290. }
  12291. if (rectAreaLength > 0) {
  12292. if (capabilities.isWebGL2) {
  12293. // WebGL 2
  12294. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12295. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12296. } else {
  12297. // WebGL 1
  12298. if (extensions.has('OES_texture_float_linear') === true) {
  12299. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12300. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12301. } else if (extensions.has('OES_texture_half_float_linear') === true) {
  12302. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  12303. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  12304. } else {
  12305. console.error('THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.');
  12306. }
  12307. }
  12308. }
  12309. state.ambient[0] = r;
  12310. state.ambient[1] = g;
  12311. state.ambient[2] = b;
  12312. const hash = state.hash;
  12313. 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) {
  12314. state.directional.length = directionalLength;
  12315. state.spot.length = spotLength;
  12316. state.rectArea.length = rectAreaLength;
  12317. state.point.length = pointLength;
  12318. state.hemi.length = hemiLength;
  12319. state.directionalShadow.length = numDirectionalShadows;
  12320. state.directionalShadowMap.length = numDirectionalShadows;
  12321. state.pointShadow.length = numPointShadows;
  12322. state.pointShadowMap.length = numPointShadows;
  12323. state.spotShadow.length = numSpotShadows;
  12324. state.spotShadowMap.length = numSpotShadows;
  12325. state.directionalShadowMatrix.length = numDirectionalShadows;
  12326. state.pointShadowMatrix.length = numPointShadows;
  12327. state.spotShadowMatrix.length = numSpotShadows;
  12328. hash.directionalLength = directionalLength;
  12329. hash.pointLength = pointLength;
  12330. hash.spotLength = spotLength;
  12331. hash.rectAreaLength = rectAreaLength;
  12332. hash.hemiLength = hemiLength;
  12333. hash.numDirectionalShadows = numDirectionalShadows;
  12334. hash.numPointShadows = numPointShadows;
  12335. hash.numSpotShadows = numSpotShadows;
  12336. state.version = nextVersion++;
  12337. }
  12338. }
  12339. function setupView(lights, camera) {
  12340. let directionalLength = 0;
  12341. let pointLength = 0;
  12342. let spotLength = 0;
  12343. let rectAreaLength = 0;
  12344. let hemiLength = 0;
  12345. const viewMatrix = camera.matrixWorldInverse;
  12346. for (let i = 0, l = lights.length; i < l; i++) {
  12347. const light = lights[i];
  12348. if (light.isDirectionalLight) {
  12349. const uniforms = state.directional[directionalLength];
  12350. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12351. vector3.setFromMatrixPosition(light.target.matrixWorld);
  12352. uniforms.direction.sub(vector3);
  12353. uniforms.direction.transformDirection(viewMatrix);
  12354. directionalLength++;
  12355. } else if (light.isSpotLight) {
  12356. const uniforms = state.spot[spotLength];
  12357. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12358. uniforms.position.applyMatrix4(viewMatrix);
  12359. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12360. vector3.setFromMatrixPosition(light.target.matrixWorld);
  12361. uniforms.direction.sub(vector3);
  12362. uniforms.direction.transformDirection(viewMatrix);
  12363. spotLength++;
  12364. } else if (light.isRectAreaLight) {
  12365. const uniforms = state.rectArea[rectAreaLength];
  12366. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12367. uniforms.position.applyMatrix4(viewMatrix); // extract local rotation of light to derive width/height half vectors
  12368. matrix42.identity();
  12369. matrix4.copy(light.matrixWorld);
  12370. matrix4.premultiply(viewMatrix);
  12371. matrix42.extractRotation(matrix4);
  12372. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  12373. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  12374. uniforms.halfWidth.applyMatrix4(matrix42);
  12375. uniforms.halfHeight.applyMatrix4(matrix42);
  12376. rectAreaLength++;
  12377. } else if (light.isPointLight) {
  12378. const uniforms = state.point[pointLength];
  12379. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12380. uniforms.position.applyMatrix4(viewMatrix);
  12381. pointLength++;
  12382. } else if (light.isHemisphereLight) {
  12383. const uniforms = state.hemi[hemiLength];
  12384. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12385. uniforms.direction.transformDirection(viewMatrix);
  12386. uniforms.direction.normalize();
  12387. hemiLength++;
  12388. }
  12389. }
  12390. }
  12391. return {
  12392. setup: setup,
  12393. setupView: setupView,
  12394. state: state
  12395. };
  12396. }
  12397. function WebGLRenderState(extensions, capabilities) {
  12398. const lights = new WebGLLights(extensions, capabilities);
  12399. const lightsArray = [];
  12400. const shadowsArray = [];
  12401. function init() {
  12402. lightsArray.length = 0;
  12403. shadowsArray.length = 0;
  12404. }
  12405. function pushLight(light) {
  12406. lightsArray.push(light);
  12407. }
  12408. function pushShadow(shadowLight) {
  12409. shadowsArray.push(shadowLight);
  12410. }
  12411. function setupLights(physicallyCorrectLights) {
  12412. lights.setup(lightsArray, physicallyCorrectLights);
  12413. }
  12414. function setupLightsView(camera) {
  12415. lights.setupView(lightsArray, camera);
  12416. }
  12417. const state = {
  12418. lightsArray: lightsArray,
  12419. shadowsArray: shadowsArray,
  12420. lights: lights
  12421. };
  12422. return {
  12423. init: init,
  12424. state: state,
  12425. setupLights: setupLights,
  12426. setupLightsView: setupLightsView,
  12427. pushLight: pushLight,
  12428. pushShadow: pushShadow
  12429. };
  12430. }
  12431. function WebGLRenderStates(extensions, capabilities) {
  12432. let renderStates = new WeakMap();
  12433. function get(scene, renderCallDepth = 0) {
  12434. let renderState;
  12435. if (renderStates.has(scene) === false) {
  12436. renderState = new WebGLRenderState(extensions, capabilities);
  12437. renderStates.set(scene, [renderState]);
  12438. } else {
  12439. if (renderCallDepth >= renderStates.get(scene).length) {
  12440. renderState = new WebGLRenderState(extensions, capabilities);
  12441. renderStates.get(scene).push(renderState);
  12442. } else {
  12443. renderState = renderStates.get(scene)[renderCallDepth];
  12444. }
  12445. }
  12446. return renderState;
  12447. }
  12448. function dispose() {
  12449. renderStates = new WeakMap();
  12450. }
  12451. return {
  12452. get: get,
  12453. dispose: dispose
  12454. };
  12455. }
  12456. /**
  12457. * parameters = {
  12458. *
  12459. * opacity: <float>,
  12460. *
  12461. * map: new THREE.Texture( <Image> ),
  12462. *
  12463. * alphaMap: new THREE.Texture( <Image> ),
  12464. *
  12465. * displacementMap: new THREE.Texture( <Image> ),
  12466. * displacementScale: <float>,
  12467. * displacementBias: <float>,
  12468. *
  12469. * wireframe: <boolean>,
  12470. * wireframeLinewidth: <float>
  12471. * }
  12472. */
  12473. class MeshDepthMaterial extends Material {
  12474. constructor(parameters) {
  12475. super();
  12476. this.type = 'MeshDepthMaterial';
  12477. this.depthPacking = BasicDepthPacking;
  12478. this.map = null;
  12479. this.alphaMap = null;
  12480. this.displacementMap = null;
  12481. this.displacementScale = 1;
  12482. this.displacementBias = 0;
  12483. this.wireframe = false;
  12484. this.wireframeLinewidth = 1;
  12485. this.fog = false;
  12486. this.setValues(parameters);
  12487. }
  12488. copy(source) {
  12489. super.copy(source);
  12490. this.depthPacking = source.depthPacking;
  12491. this.map = source.map;
  12492. this.alphaMap = source.alphaMap;
  12493. this.displacementMap = source.displacementMap;
  12494. this.displacementScale = source.displacementScale;
  12495. this.displacementBias = source.displacementBias;
  12496. this.wireframe = source.wireframe;
  12497. this.wireframeLinewidth = source.wireframeLinewidth;
  12498. return this;
  12499. }
  12500. }
  12501. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  12502. /**
  12503. * parameters = {
  12504. *
  12505. * referencePosition: <float>,
  12506. * nearDistance: <float>,
  12507. * farDistance: <float>,
  12508. *
  12509. * map: new THREE.Texture( <Image> ),
  12510. *
  12511. * alphaMap: new THREE.Texture( <Image> ),
  12512. *
  12513. * displacementMap: new THREE.Texture( <Image> ),
  12514. * displacementScale: <float>,
  12515. * displacementBias: <float>
  12516. *
  12517. * }
  12518. */
  12519. class MeshDistanceMaterial extends Material {
  12520. constructor(parameters) {
  12521. super();
  12522. this.type = 'MeshDistanceMaterial';
  12523. this.referencePosition = new Vector3();
  12524. this.nearDistance = 1;
  12525. this.farDistance = 1000;
  12526. this.map = null;
  12527. this.alphaMap = null;
  12528. this.displacementMap = null;
  12529. this.displacementScale = 1;
  12530. this.displacementBias = 0;
  12531. this.fog = false;
  12532. this.setValues(parameters);
  12533. }
  12534. copy(source) {
  12535. super.copy(source);
  12536. this.referencePosition.copy(source.referencePosition);
  12537. this.nearDistance = source.nearDistance;
  12538. this.farDistance = source.farDistance;
  12539. this.map = source.map;
  12540. this.alphaMap = source.alphaMap;
  12541. this.displacementMap = source.displacementMap;
  12542. this.displacementScale = source.displacementScale;
  12543. this.displacementBias = source.displacementBias;
  12544. return this;
  12545. }
  12546. }
  12547. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  12548. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12549. const fragment = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n\tconst float samples = float( VSM_SAMPLES );\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";
  12550. function WebGLShadowMap(_renderer, _objects, _capabilities) {
  12551. let _frustum = new Frustum();
  12552. const _shadowMapSize = new Vector2(),
  12553. _viewportSize = new Vector2(),
  12554. _viewport = new Vector4(),
  12555. _depthMaterial = new MeshDepthMaterial({
  12556. depthPacking: RGBADepthPacking
  12557. }),
  12558. _distanceMaterial = new MeshDistanceMaterial(),
  12559. _materialCache = {},
  12560. _maxTextureSize = _capabilities.maxTextureSize;
  12561. const shadowSide = {
  12562. 0: BackSide,
  12563. 1: FrontSide,
  12564. 2: DoubleSide
  12565. };
  12566. const shadowMaterialVertical = new ShaderMaterial({
  12567. defines: {
  12568. VSM_SAMPLES: 8
  12569. },
  12570. uniforms: {
  12571. shadow_pass: {
  12572. value: null
  12573. },
  12574. resolution: {
  12575. value: new Vector2()
  12576. },
  12577. radius: {
  12578. value: 4.0
  12579. }
  12580. },
  12581. vertexShader: vertex,
  12582. fragmentShader: fragment
  12583. });
  12584. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  12585. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  12586. const fullScreenTri = new BufferGeometry();
  12587. fullScreenTri.setAttribute('position', new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));
  12588. const fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical);
  12589. const scope = this;
  12590. this.enabled = false;
  12591. this.autoUpdate = true;
  12592. this.needsUpdate = false;
  12593. this.type = PCFShadowMap;
  12594. this.render = function (lights, scene, camera) {
  12595. if (scope.enabled === false) return;
  12596. if (scope.autoUpdate === false && scope.needsUpdate === false) return;
  12597. if (lights.length === 0) return;
  12598. const currentRenderTarget = _renderer.getRenderTarget();
  12599. const activeCubeFace = _renderer.getActiveCubeFace();
  12600. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12601. const _state = _renderer.state; // Set GL state for depth map.
  12602. _state.setBlending(NoBlending);
  12603. _state.buffers.color.setClear(1, 1, 1, 1);
  12604. _state.buffers.depth.setTest(true);
  12605. _state.setScissorTest(false); // render depth map
  12606. for (let i = 0, il = lights.length; i < il; i++) {
  12607. const light = lights[i];
  12608. const shadow = light.shadow;
  12609. if (shadow === undefined) {
  12610. console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');
  12611. continue;
  12612. }
  12613. if (shadow.autoUpdate === false && shadow.needsUpdate === false) continue;
  12614. _shadowMapSize.copy(shadow.mapSize);
  12615. const shadowFrameExtents = shadow.getFrameExtents();
  12616. _shadowMapSize.multiply(shadowFrameExtents);
  12617. _viewportSize.copy(shadow.mapSize);
  12618. if (_shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize) {
  12619. if (_shadowMapSize.x > _maxTextureSize) {
  12620. _viewportSize.x = Math.floor(_maxTextureSize / shadowFrameExtents.x);
  12621. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12622. shadow.mapSize.x = _viewportSize.x;
  12623. }
  12624. if (_shadowMapSize.y > _maxTextureSize) {
  12625. _viewportSize.y = Math.floor(_maxTextureSize / shadowFrameExtents.y);
  12626. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  12627. shadow.mapSize.y = _viewportSize.y;
  12628. }
  12629. }
  12630. if (shadow.map === null && !shadow.isPointLightShadow && this.type === VSMShadowMap) {
  12631. const pars = {
  12632. minFilter: LinearFilter,
  12633. magFilter: LinearFilter,
  12634. format: RGBAFormat
  12635. };
  12636. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12637. shadow.map.texture.name = light.name + '.shadowMap';
  12638. shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12639. shadow.camera.updateProjectionMatrix();
  12640. }
  12641. if (shadow.map === null) {
  12642. const pars = {
  12643. minFilter: NearestFilter,
  12644. magFilter: NearestFilter,
  12645. format: RGBAFormat
  12646. };
  12647. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12648. shadow.map.texture.name = light.name + '.shadowMap';
  12649. shadow.camera.updateProjectionMatrix();
  12650. }
  12651. _renderer.setRenderTarget(shadow.map);
  12652. _renderer.clear();
  12653. const viewportCount = shadow.getViewportCount();
  12654. for (let vp = 0; vp < viewportCount; vp++) {
  12655. const viewport = shadow.getViewport(vp);
  12656. _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
  12657. _state.viewport(_viewport);
  12658. shadow.updateMatrices(light, vp);
  12659. _frustum = shadow.getFrustum();
  12660. renderObject(scene, camera, shadow.camera, light, this.type);
  12661. } // do blur pass for VSM
  12662. if (!shadow.isPointLightShadow && this.type === VSMShadowMap) {
  12663. VSMPass(shadow, camera);
  12664. }
  12665. shadow.needsUpdate = false;
  12666. }
  12667. scope.needsUpdate = false;
  12668. _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
  12669. };
  12670. function VSMPass(shadow, camera) {
  12671. const geometry = _objects.update(fullScreenMesh);
  12672. if (shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples) {
  12673. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  12674. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  12675. shadowMaterialVertical.needsUpdate = true;
  12676. shadowMaterialHorizontal.needsUpdate = true;
  12677. } // vertical pass
  12678. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  12679. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  12680. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  12681. _renderer.setRenderTarget(shadow.mapPass);
  12682. _renderer.clear();
  12683. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); // horizontal pass
  12684. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  12685. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  12686. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  12687. _renderer.setRenderTarget(shadow.map);
  12688. _renderer.clear();
  12689. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null);
  12690. }
  12691. function getDepthMaterial(object, geometry, material, light, shadowCameraNear, shadowCameraFar, type) {
  12692. let result = null;
  12693. const customMaterial = light.isPointLight === true ? object.customDistanceMaterial : object.customDepthMaterial;
  12694. if (customMaterial !== undefined) {
  12695. result = customMaterial;
  12696. } else {
  12697. result = light.isPointLight === true ? _distanceMaterial : _depthMaterial;
  12698. }
  12699. if (_renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0 || material.displacementMap && material.displacementScale !== 0 || material.alphaMap && material.alphaTest > 0) {
  12700. // in this case we need a unique material instance reflecting the
  12701. // appropriate state
  12702. const keyA = result.uuid,
  12703. keyB = material.uuid;
  12704. let materialsForVariant = _materialCache[keyA];
  12705. if (materialsForVariant === undefined) {
  12706. materialsForVariant = {};
  12707. _materialCache[keyA] = materialsForVariant;
  12708. }
  12709. let cachedMaterial = materialsForVariant[keyB];
  12710. if (cachedMaterial === undefined) {
  12711. cachedMaterial = result.clone();
  12712. materialsForVariant[keyB] = cachedMaterial;
  12713. }
  12714. result = cachedMaterial;
  12715. }
  12716. result.visible = material.visible;
  12717. result.wireframe = material.wireframe;
  12718. if (type === VSMShadowMap) {
  12719. result.side = material.shadowSide !== null ? material.shadowSide : material.side;
  12720. } else {
  12721. result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side];
  12722. }
  12723. result.alphaMap = material.alphaMap;
  12724. result.alphaTest = material.alphaTest;
  12725. result.clipShadows = material.clipShadows;
  12726. result.clippingPlanes = material.clippingPlanes;
  12727. result.clipIntersection = material.clipIntersection;
  12728. result.displacementMap = material.displacementMap;
  12729. result.displacementScale = material.displacementScale;
  12730. result.displacementBias = material.displacementBias;
  12731. result.wireframeLinewidth = material.wireframeLinewidth;
  12732. result.linewidth = material.linewidth;
  12733. if (light.isPointLight === true && result.isMeshDistanceMaterial === true) {
  12734. result.referencePosition.setFromMatrixPosition(light.matrixWorld);
  12735. result.nearDistance = shadowCameraNear;
  12736. result.farDistance = shadowCameraFar;
  12737. }
  12738. return result;
  12739. }
  12740. function renderObject(object, camera, shadowCamera, light, type) {
  12741. if (object.visible === false) return;
  12742. const visible = object.layers.test(camera.layers);
  12743. if (visible && (object.isMesh || object.isLine || object.isPoints)) {
  12744. if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {
  12745. object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
  12746. const geometry = _objects.update(object);
  12747. const material = object.material;
  12748. if (Array.isArray(material)) {
  12749. const groups = geometry.groups;
  12750. for (let k = 0, kl = groups.length; k < kl; k++) {
  12751. const group = groups[k];
  12752. const groupMaterial = material[group.materialIndex];
  12753. if (groupMaterial && groupMaterial.visible) {
  12754. const depthMaterial = getDepthMaterial(object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
  12755. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
  12756. }
  12757. }
  12758. } else if (material.visible) {
  12759. const depthMaterial = getDepthMaterial(object, geometry, material, light, shadowCamera.near, shadowCamera.far, type);
  12760. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null);
  12761. }
  12762. }
  12763. }
  12764. const children = object.children;
  12765. for (let i = 0, l = children.length; i < l; i++) {
  12766. renderObject(children[i], camera, shadowCamera, light, type);
  12767. }
  12768. }
  12769. }
  12770. function WebGLState(gl, extensions, capabilities) {
  12771. const isWebGL2 = capabilities.isWebGL2;
  12772. function ColorBuffer() {
  12773. let locked = false;
  12774. const color = new Vector4();
  12775. let currentColorMask = null;
  12776. const currentColorClear = new Vector4(0, 0, 0, 0);
  12777. return {
  12778. setMask: function (colorMask) {
  12779. if (currentColorMask !== colorMask && !locked) {
  12780. gl.colorMask(colorMask, colorMask, colorMask, colorMask);
  12781. currentColorMask = colorMask;
  12782. }
  12783. },
  12784. setLocked: function (lock) {
  12785. locked = lock;
  12786. },
  12787. setClear: function (r, g, b, a, premultipliedAlpha) {
  12788. if (premultipliedAlpha === true) {
  12789. r *= a;
  12790. g *= a;
  12791. b *= a;
  12792. }
  12793. color.set(r, g, b, a);
  12794. if (currentColorClear.equals(color) === false) {
  12795. gl.clearColor(r, g, b, a);
  12796. currentColorClear.copy(color);
  12797. }
  12798. },
  12799. reset: function () {
  12800. locked = false;
  12801. currentColorMask = null;
  12802. currentColorClear.set(-1, 0, 0, 0); // set to invalid state
  12803. }
  12804. };
  12805. }
  12806. function DepthBuffer() {
  12807. let locked = false;
  12808. let currentDepthMask = null;
  12809. let currentDepthFunc = null;
  12810. let currentDepthClear = null;
  12811. return {
  12812. setTest: function (depthTest) {
  12813. if (depthTest) {
  12814. enable(gl.DEPTH_TEST);
  12815. } else {
  12816. disable(gl.DEPTH_TEST);
  12817. }
  12818. },
  12819. setMask: function (depthMask) {
  12820. if (currentDepthMask !== depthMask && !locked) {
  12821. gl.depthMask(depthMask);
  12822. currentDepthMask = depthMask;
  12823. }
  12824. },
  12825. setFunc: function (depthFunc) {
  12826. if (currentDepthFunc !== depthFunc) {
  12827. if (depthFunc) {
  12828. switch (depthFunc) {
  12829. case NeverDepth:
  12830. gl.depthFunc(gl.NEVER);
  12831. break;
  12832. case AlwaysDepth:
  12833. gl.depthFunc(gl.ALWAYS);
  12834. break;
  12835. case LessDepth:
  12836. gl.depthFunc(gl.LESS);
  12837. break;
  12838. case LessEqualDepth:
  12839. gl.depthFunc(gl.LEQUAL);
  12840. break;
  12841. case EqualDepth:
  12842. gl.depthFunc(gl.EQUAL);
  12843. break;
  12844. case GreaterEqualDepth:
  12845. gl.depthFunc(gl.GEQUAL);
  12846. break;
  12847. case GreaterDepth:
  12848. gl.depthFunc(gl.GREATER);
  12849. break;
  12850. case NotEqualDepth:
  12851. gl.depthFunc(gl.NOTEQUAL);
  12852. break;
  12853. default:
  12854. gl.depthFunc(gl.LEQUAL);
  12855. }
  12856. } else {
  12857. gl.depthFunc(gl.LEQUAL);
  12858. }
  12859. currentDepthFunc = depthFunc;
  12860. }
  12861. },
  12862. setLocked: function (lock) {
  12863. locked = lock;
  12864. },
  12865. setClear: function (depth) {
  12866. if (currentDepthClear !== depth) {
  12867. gl.clearDepth(depth);
  12868. currentDepthClear = depth;
  12869. }
  12870. },
  12871. reset: function () {
  12872. locked = false;
  12873. currentDepthMask = null;
  12874. currentDepthFunc = null;
  12875. currentDepthClear = null;
  12876. }
  12877. };
  12878. }
  12879. function StencilBuffer() {
  12880. let locked = false;
  12881. let currentStencilMask = null;
  12882. let currentStencilFunc = null;
  12883. let currentStencilRef = null;
  12884. let currentStencilFuncMask = null;
  12885. let currentStencilFail = null;
  12886. let currentStencilZFail = null;
  12887. let currentStencilZPass = null;
  12888. let currentStencilClear = null;
  12889. return {
  12890. setTest: function (stencilTest) {
  12891. if (!locked) {
  12892. if (stencilTest) {
  12893. enable(gl.STENCIL_TEST);
  12894. } else {
  12895. disable(gl.STENCIL_TEST);
  12896. }
  12897. }
  12898. },
  12899. setMask: function (stencilMask) {
  12900. if (currentStencilMask !== stencilMask && !locked) {
  12901. gl.stencilMask(stencilMask);
  12902. currentStencilMask = stencilMask;
  12903. }
  12904. },
  12905. setFunc: function (stencilFunc, stencilRef, stencilMask) {
  12906. if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
  12907. gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
  12908. currentStencilFunc = stencilFunc;
  12909. currentStencilRef = stencilRef;
  12910. currentStencilFuncMask = stencilMask;
  12911. }
  12912. },
  12913. setOp: function (stencilFail, stencilZFail, stencilZPass) {
  12914. if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
  12915. gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
  12916. currentStencilFail = stencilFail;
  12917. currentStencilZFail = stencilZFail;
  12918. currentStencilZPass = stencilZPass;
  12919. }
  12920. },
  12921. setLocked: function (lock) {
  12922. locked = lock;
  12923. },
  12924. setClear: function (stencil) {
  12925. if (currentStencilClear !== stencil) {
  12926. gl.clearStencil(stencil);
  12927. currentStencilClear = stencil;
  12928. }
  12929. },
  12930. reset: function () {
  12931. locked = false;
  12932. currentStencilMask = null;
  12933. currentStencilFunc = null;
  12934. currentStencilRef = null;
  12935. currentStencilFuncMask = null;
  12936. currentStencilFail = null;
  12937. currentStencilZFail = null;
  12938. currentStencilZPass = null;
  12939. currentStencilClear = null;
  12940. }
  12941. };
  12942. } //
  12943. const colorBuffer = new ColorBuffer();
  12944. const depthBuffer = new DepthBuffer();
  12945. const stencilBuffer = new StencilBuffer();
  12946. let enabledCapabilities = {};
  12947. let currentBoundFramebuffers = {};
  12948. let currentProgram = null;
  12949. let currentBlendingEnabled = false;
  12950. let currentBlending = null;
  12951. let currentBlendEquation = null;
  12952. let currentBlendSrc = null;
  12953. let currentBlendDst = null;
  12954. let currentBlendEquationAlpha = null;
  12955. let currentBlendSrcAlpha = null;
  12956. let currentBlendDstAlpha = null;
  12957. let currentPremultipledAlpha = false;
  12958. let currentFlipSided = null;
  12959. let currentCullFace = null;
  12960. let currentLineWidth = null;
  12961. let currentPolygonOffsetFactor = null;
  12962. let currentPolygonOffsetUnits = null;
  12963. const maxTextures = gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12964. let lineWidthAvailable = false;
  12965. let version = 0;
  12966. const glVersion = gl.getParameter(gl.VERSION);
  12967. if (glVersion.indexOf('WebGL') !== -1) {
  12968. version = parseFloat(/^WebGL (\d)/.exec(glVersion)[1]);
  12969. lineWidthAvailable = version >= 1.0;
  12970. } else if (glVersion.indexOf('OpenGL ES') !== -1) {
  12971. version = parseFloat(/^OpenGL ES (\d)/.exec(glVersion)[1]);
  12972. lineWidthAvailable = version >= 2.0;
  12973. }
  12974. let currentTextureSlot = null;
  12975. let currentBoundTextures = {};
  12976. const scissorParam = gl.getParameter(gl.SCISSOR_BOX);
  12977. const viewportParam = gl.getParameter(gl.VIEWPORT);
  12978. const currentScissor = new Vector4().fromArray(scissorParam);
  12979. const currentViewport = new Vector4().fromArray(viewportParam);
  12980. function createTexture(type, target, count) {
  12981. const data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.
  12982. const texture = gl.createTexture();
  12983. gl.bindTexture(type, texture);
  12984. gl.texParameteri(type, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12985. gl.texParameteri(type, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12986. for (let i = 0; i < count; i++) {
  12987. gl.texImage2D(target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
  12988. }
  12989. return texture;
  12990. }
  12991. const emptyTextures = {};
  12992. emptyTextures[gl.TEXTURE_2D] = createTexture(gl.TEXTURE_2D, gl.TEXTURE_2D, 1);
  12993. emptyTextures[gl.TEXTURE_CUBE_MAP] = createTexture(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6); // init
  12994. colorBuffer.setClear(0, 0, 0, 1);
  12995. depthBuffer.setClear(1);
  12996. stencilBuffer.setClear(0);
  12997. enable(gl.DEPTH_TEST);
  12998. depthBuffer.setFunc(LessEqualDepth);
  12999. setFlipSided(false);
  13000. setCullFace(CullFaceBack);
  13001. enable(gl.CULL_FACE);
  13002. setBlending(NoBlending); //
  13003. function enable(id) {
  13004. if (enabledCapabilities[id] !== true) {
  13005. gl.enable(id);
  13006. enabledCapabilities[id] = true;
  13007. }
  13008. }
  13009. function disable(id) {
  13010. if (enabledCapabilities[id] !== false) {
  13011. gl.disable(id);
  13012. enabledCapabilities[id] = false;
  13013. }
  13014. }
  13015. function bindFramebuffer(target, framebuffer) {
  13016. if (currentBoundFramebuffers[target] !== framebuffer) {
  13017. gl.bindFramebuffer(target, framebuffer);
  13018. currentBoundFramebuffers[target] = framebuffer;
  13019. if (isWebGL2) {
  13020. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  13021. if (target === gl.DRAW_FRAMEBUFFER) {
  13022. currentBoundFramebuffers[gl.FRAMEBUFFER] = framebuffer;
  13023. }
  13024. if (target === gl.FRAMEBUFFER) {
  13025. currentBoundFramebuffers[gl.DRAW_FRAMEBUFFER] = framebuffer;
  13026. }
  13027. }
  13028. return true;
  13029. }
  13030. return false;
  13031. }
  13032. function useProgram(program) {
  13033. if (currentProgram !== program) {
  13034. gl.useProgram(program);
  13035. currentProgram = program;
  13036. return true;
  13037. }
  13038. return false;
  13039. }
  13040. const equationToGL = {
  13041. [AddEquation]: gl.FUNC_ADD,
  13042. [SubtractEquation]: gl.FUNC_SUBTRACT,
  13043. [ReverseSubtractEquation]: gl.FUNC_REVERSE_SUBTRACT
  13044. };
  13045. if (isWebGL2) {
  13046. equationToGL[MinEquation] = gl.MIN;
  13047. equationToGL[MaxEquation] = gl.MAX;
  13048. } else {
  13049. const extension = extensions.get('EXT_blend_minmax');
  13050. if (extension !== null) {
  13051. equationToGL[MinEquation] = extension.MIN_EXT;
  13052. equationToGL[MaxEquation] = extension.MAX_EXT;
  13053. }
  13054. }
  13055. const factorToGL = {
  13056. [ZeroFactor]: gl.ZERO,
  13057. [OneFactor]: gl.ONE,
  13058. [SrcColorFactor]: gl.SRC_COLOR,
  13059. [SrcAlphaFactor]: gl.SRC_ALPHA,
  13060. [SrcAlphaSaturateFactor]: gl.SRC_ALPHA_SATURATE,
  13061. [DstColorFactor]: gl.DST_COLOR,
  13062. [DstAlphaFactor]: gl.DST_ALPHA,
  13063. [OneMinusSrcColorFactor]: gl.ONE_MINUS_SRC_COLOR,
  13064. [OneMinusSrcAlphaFactor]: gl.ONE_MINUS_SRC_ALPHA,
  13065. [OneMinusDstColorFactor]: gl.ONE_MINUS_DST_COLOR,
  13066. [OneMinusDstAlphaFactor]: gl.ONE_MINUS_DST_ALPHA
  13067. };
  13068. function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
  13069. if (blending === NoBlending) {
  13070. if (currentBlendingEnabled === true) {
  13071. disable(gl.BLEND);
  13072. currentBlendingEnabled = false;
  13073. }
  13074. return;
  13075. }
  13076. if (currentBlendingEnabled === false) {
  13077. enable(gl.BLEND);
  13078. currentBlendingEnabled = true;
  13079. }
  13080. if (blending !== CustomBlending) {
  13081. if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
  13082. if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
  13083. gl.blendEquation(gl.FUNC_ADD);
  13084. currentBlendEquation = AddEquation;
  13085. currentBlendEquationAlpha = AddEquation;
  13086. }
  13087. if (premultipliedAlpha) {
  13088. switch (blending) {
  13089. case NormalBlending:
  13090. gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  13091. break;
  13092. case AdditiveBlending:
  13093. gl.blendFunc(gl.ONE, gl.ONE);
  13094. break;
  13095. case SubtractiveBlending:
  13096. gl.blendFuncSeparate(gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA);
  13097. break;
  13098. case MultiplyBlending:
  13099. gl.blendFuncSeparate(gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA);
  13100. break;
  13101. default:
  13102. console.error('THREE.WebGLState: Invalid blending: ', blending);
  13103. break;
  13104. }
  13105. } else {
  13106. switch (blending) {
  13107. case NormalBlending:
  13108. gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  13109. break;
  13110. case AdditiveBlending:
  13111. gl.blendFunc(gl.SRC_ALPHA, gl.ONE);
  13112. break;
  13113. case SubtractiveBlending:
  13114. gl.blendFunc(gl.ZERO, gl.ONE_MINUS_SRC_COLOR);
  13115. break;
  13116. case MultiplyBlending:
  13117. gl.blendFunc(gl.ZERO, gl.SRC_COLOR);
  13118. break;
  13119. default:
  13120. console.error('THREE.WebGLState: Invalid blending: ', blending);
  13121. break;
  13122. }
  13123. }
  13124. currentBlendSrc = null;
  13125. currentBlendDst = null;
  13126. currentBlendSrcAlpha = null;
  13127. currentBlendDstAlpha = null;
  13128. currentBlending = blending;
  13129. currentPremultipledAlpha = premultipliedAlpha;
  13130. }
  13131. return;
  13132. } // custom blending
  13133. blendEquationAlpha = blendEquationAlpha || blendEquation;
  13134. blendSrcAlpha = blendSrcAlpha || blendSrc;
  13135. blendDstAlpha = blendDstAlpha || blendDst;
  13136. if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
  13137. gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]);
  13138. currentBlendEquation = blendEquation;
  13139. currentBlendEquationAlpha = blendEquationAlpha;
  13140. }
  13141. if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
  13142. gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]);
  13143. currentBlendSrc = blendSrc;
  13144. currentBlendDst = blendDst;
  13145. currentBlendSrcAlpha = blendSrcAlpha;
  13146. currentBlendDstAlpha = blendDstAlpha;
  13147. }
  13148. currentBlending = blending;
  13149. currentPremultipledAlpha = null;
  13150. }
  13151. function setMaterial(material, frontFaceCW) {
  13152. material.side === DoubleSide ? disable(gl.CULL_FACE) : enable(gl.CULL_FACE);
  13153. let flipSided = material.side === BackSide;
  13154. if (frontFaceCW) flipSided = !flipSided;
  13155. setFlipSided(flipSided);
  13156. 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);
  13157. depthBuffer.setFunc(material.depthFunc);
  13158. depthBuffer.setTest(material.depthTest);
  13159. depthBuffer.setMask(material.depthWrite);
  13160. colorBuffer.setMask(material.colorWrite);
  13161. const stencilWrite = material.stencilWrite;
  13162. stencilBuffer.setTest(stencilWrite);
  13163. if (stencilWrite) {
  13164. stencilBuffer.setMask(material.stencilWriteMask);
  13165. stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
  13166. stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
  13167. }
  13168. setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
  13169. material.alphaToCoverage === true ? enable(gl.SAMPLE_ALPHA_TO_COVERAGE) : disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  13170. } //
  13171. function setFlipSided(flipSided) {
  13172. if (currentFlipSided !== flipSided) {
  13173. if (flipSided) {
  13174. gl.frontFace(gl.CW);
  13175. } else {
  13176. gl.frontFace(gl.CCW);
  13177. }
  13178. currentFlipSided = flipSided;
  13179. }
  13180. }
  13181. function setCullFace(cullFace) {
  13182. if (cullFace !== CullFaceNone) {
  13183. enable(gl.CULL_FACE);
  13184. if (cullFace !== currentCullFace) {
  13185. if (cullFace === CullFaceBack) {
  13186. gl.cullFace(gl.BACK);
  13187. } else if (cullFace === CullFaceFront) {
  13188. gl.cullFace(gl.FRONT);
  13189. } else {
  13190. gl.cullFace(gl.FRONT_AND_BACK);
  13191. }
  13192. }
  13193. } else {
  13194. disable(gl.CULL_FACE);
  13195. }
  13196. currentCullFace = cullFace;
  13197. }
  13198. function setLineWidth(width) {
  13199. if (width !== currentLineWidth) {
  13200. if (lineWidthAvailable) gl.lineWidth(width);
  13201. currentLineWidth = width;
  13202. }
  13203. }
  13204. function setPolygonOffset(polygonOffset, factor, units) {
  13205. if (polygonOffset) {
  13206. enable(gl.POLYGON_OFFSET_FILL);
  13207. if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
  13208. gl.polygonOffset(factor, units);
  13209. currentPolygonOffsetFactor = factor;
  13210. currentPolygonOffsetUnits = units;
  13211. }
  13212. } else {
  13213. disable(gl.POLYGON_OFFSET_FILL);
  13214. }
  13215. }
  13216. function setScissorTest(scissorTest) {
  13217. if (scissorTest) {
  13218. enable(gl.SCISSOR_TEST);
  13219. } else {
  13220. disable(gl.SCISSOR_TEST);
  13221. }
  13222. } // texture
  13223. function activeTexture(webglSlot) {
  13224. if (webglSlot === undefined) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  13225. if (currentTextureSlot !== webglSlot) {
  13226. gl.activeTexture(webglSlot);
  13227. currentTextureSlot = webglSlot;
  13228. }
  13229. }
  13230. function bindTexture(webglType, webglTexture) {
  13231. if (currentTextureSlot === null) {
  13232. activeTexture();
  13233. }
  13234. let boundTexture = currentBoundTextures[currentTextureSlot];
  13235. if (boundTexture === undefined) {
  13236. boundTexture = {
  13237. type: undefined,
  13238. texture: undefined
  13239. };
  13240. currentBoundTextures[currentTextureSlot] = boundTexture;
  13241. }
  13242. if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
  13243. gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
  13244. boundTexture.type = webglType;
  13245. boundTexture.texture = webglTexture;
  13246. }
  13247. }
  13248. function unbindTexture() {
  13249. const boundTexture = currentBoundTextures[currentTextureSlot];
  13250. if (boundTexture !== undefined && boundTexture.type !== undefined) {
  13251. gl.bindTexture(boundTexture.type, null);
  13252. boundTexture.type = undefined;
  13253. boundTexture.texture = undefined;
  13254. }
  13255. }
  13256. function compressedTexImage2D() {
  13257. try {
  13258. gl.compressedTexImage2D.apply(gl, arguments);
  13259. } catch (error) {
  13260. console.error('THREE.WebGLState:', error);
  13261. }
  13262. }
  13263. function texSubImage2D() {
  13264. try {
  13265. gl.texSubImage2D.apply(gl, arguments);
  13266. } catch (error) {
  13267. console.error('THREE.WebGLState:', error);
  13268. }
  13269. }
  13270. function texSubImage3D() {
  13271. try {
  13272. gl.texSubImage3D.apply(gl, arguments);
  13273. } catch (error) {
  13274. console.error('THREE.WebGLState:', error);
  13275. }
  13276. }
  13277. function compressedTexSubImage2D() {
  13278. try {
  13279. gl.compressedTexSubImage2D.apply(gl, arguments);
  13280. } catch (error) {
  13281. console.error('THREE.WebGLState:', error);
  13282. }
  13283. }
  13284. function texStorage2D() {
  13285. try {
  13286. gl.texStorage2D.apply(gl, arguments);
  13287. } catch (error) {
  13288. console.error('THREE.WebGLState:', error);
  13289. }
  13290. }
  13291. function texStorage3D() {
  13292. try {
  13293. gl.texStorage3D.apply(gl, arguments);
  13294. } catch (error) {
  13295. console.error('THREE.WebGLState:', error);
  13296. }
  13297. }
  13298. function texImage2D() {
  13299. try {
  13300. gl.texImage2D.apply(gl, arguments);
  13301. } catch (error) {
  13302. console.error('THREE.WebGLState:', error);
  13303. }
  13304. }
  13305. function texImage3D() {
  13306. try {
  13307. gl.texImage3D.apply(gl, arguments);
  13308. } catch (error) {
  13309. console.error('THREE.WebGLState:', error);
  13310. }
  13311. } //
  13312. function scissor(scissor) {
  13313. if (currentScissor.equals(scissor) === false) {
  13314. gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
  13315. currentScissor.copy(scissor);
  13316. }
  13317. }
  13318. function viewport(viewport) {
  13319. if (currentViewport.equals(viewport) === false) {
  13320. gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
  13321. currentViewport.copy(viewport);
  13322. }
  13323. } //
  13324. function reset() {
  13325. // reset state
  13326. gl.disable(gl.BLEND);
  13327. gl.disable(gl.CULL_FACE);
  13328. gl.disable(gl.DEPTH_TEST);
  13329. gl.disable(gl.POLYGON_OFFSET_FILL);
  13330. gl.disable(gl.SCISSOR_TEST);
  13331. gl.disable(gl.STENCIL_TEST);
  13332. gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  13333. gl.blendEquation(gl.FUNC_ADD);
  13334. gl.blendFunc(gl.ONE, gl.ZERO);
  13335. gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ZERO);
  13336. gl.colorMask(true, true, true, true);
  13337. gl.clearColor(0, 0, 0, 0);
  13338. gl.depthMask(true);
  13339. gl.depthFunc(gl.LESS);
  13340. gl.clearDepth(1);
  13341. gl.stencilMask(0xffffffff);
  13342. gl.stencilFunc(gl.ALWAYS, 0, 0xffffffff);
  13343. gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
  13344. gl.clearStencil(0);
  13345. gl.cullFace(gl.BACK);
  13346. gl.frontFace(gl.CCW);
  13347. gl.polygonOffset(0, 0);
  13348. gl.activeTexture(gl.TEXTURE0);
  13349. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13350. if (isWebGL2 === true) {
  13351. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);
  13352. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
  13353. }
  13354. gl.useProgram(null);
  13355. gl.lineWidth(1);
  13356. gl.scissor(0, 0, gl.canvas.width, gl.canvas.height);
  13357. gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); // reset internals
  13358. enabledCapabilities = {};
  13359. currentTextureSlot = null;
  13360. currentBoundTextures = {};
  13361. currentBoundFramebuffers = {};
  13362. currentProgram = null;
  13363. currentBlendingEnabled = false;
  13364. currentBlending = null;
  13365. currentBlendEquation = null;
  13366. currentBlendSrc = null;
  13367. currentBlendDst = null;
  13368. currentBlendEquationAlpha = null;
  13369. currentBlendSrcAlpha = null;
  13370. currentBlendDstAlpha = null;
  13371. currentPremultipledAlpha = false;
  13372. currentFlipSided = null;
  13373. currentCullFace = null;
  13374. currentLineWidth = null;
  13375. currentPolygonOffsetFactor = null;
  13376. currentPolygonOffsetUnits = null;
  13377. currentScissor.set(0, 0, gl.canvas.width, gl.canvas.height);
  13378. currentViewport.set(0, 0, gl.canvas.width, gl.canvas.height);
  13379. colorBuffer.reset();
  13380. depthBuffer.reset();
  13381. stencilBuffer.reset();
  13382. }
  13383. return {
  13384. buffers: {
  13385. color: colorBuffer,
  13386. depth: depthBuffer,
  13387. stencil: stencilBuffer
  13388. },
  13389. enable: enable,
  13390. disable: disable,
  13391. bindFramebuffer: bindFramebuffer,
  13392. useProgram: useProgram,
  13393. setBlending: setBlending,
  13394. setMaterial: setMaterial,
  13395. setFlipSided: setFlipSided,
  13396. setCullFace: setCullFace,
  13397. setLineWidth: setLineWidth,
  13398. setPolygonOffset: setPolygonOffset,
  13399. setScissorTest: setScissorTest,
  13400. activeTexture: activeTexture,
  13401. bindTexture: bindTexture,
  13402. unbindTexture: unbindTexture,
  13403. compressedTexImage2D: compressedTexImage2D,
  13404. texImage2D: texImage2D,
  13405. texImage3D: texImage3D,
  13406. texStorage2D: texStorage2D,
  13407. texStorage3D: texStorage3D,
  13408. texSubImage2D: texSubImage2D,
  13409. texSubImage3D: texSubImage3D,
  13410. compressedTexSubImage2D: compressedTexSubImage2D,
  13411. scissor: scissor,
  13412. viewport: viewport,
  13413. reset: reset
  13414. };
  13415. }
  13416. function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
  13417. const isWebGL2 = capabilities.isWebGL2;
  13418. const maxTextures = capabilities.maxTextures;
  13419. const maxCubemapSize = capabilities.maxCubemapSize;
  13420. const maxTextureSize = capabilities.maxTextureSize;
  13421. const maxSamples = capabilities.maxSamples;
  13422. const hasMultisampledRenderToTexture = extensions.has('WEBGL_multisampled_render_to_texture');
  13423. const MultisampledRenderToTextureExtension = hasMultisampledRenderToTexture ? extensions.get('WEBGL_multisampled_render_to_texture') : undefined;
  13424. const _videoTextures = new WeakMap();
  13425. let _canvas; // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  13426. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  13427. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  13428. let useOffscreenCanvas = false;
  13429. try {
  13430. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && new OffscreenCanvas(1, 1).getContext('2d') !== null;
  13431. } catch (err) {// Ignore any errors
  13432. }
  13433. function createCanvas(width, height) {
  13434. // Use OffscreenCanvas when available. Specially needed in web workers
  13435. return useOffscreenCanvas ? new OffscreenCanvas(width, height) : createElementNS('canvas');
  13436. }
  13437. function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
  13438. let scale = 1; // handle case if texture exceeds max size
  13439. if (image.width > maxSize || image.height > maxSize) {
  13440. scale = maxSize / Math.max(image.width, image.height);
  13441. } // only perform resize if necessary
  13442. if (scale < 1 || needsPowerOfTwo === true) {
  13443. // only perform resize for certain image types
  13444. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  13445. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  13446. const width = floor(scale * image.width);
  13447. const height = floor(scale * image.height);
  13448. if (_canvas === undefined) _canvas = createCanvas(width, height); // cube textures can't reuse the same canvas
  13449. const canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
  13450. canvas.width = width;
  13451. canvas.height = height;
  13452. const context = canvas.getContext('2d');
  13453. context.drawImage(image, 0, 0, width, height);
  13454. console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
  13455. return canvas;
  13456. } else {
  13457. if ('data' in image) {
  13458. console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
  13459. }
  13460. return image;
  13461. }
  13462. }
  13463. return image;
  13464. }
  13465. function isPowerOfTwo$1(image) {
  13466. return isPowerOfTwo(image.width) && isPowerOfTwo(image.height);
  13467. }
  13468. function textureNeedsPowerOfTwo(texture) {
  13469. if (isWebGL2) return false;
  13470. return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13471. }
  13472. function textureNeedsGenerateMipmaps(texture, supportsMips) {
  13473. return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13474. }
  13475. function generateMipmap(target) {
  13476. _gl.generateMipmap(target);
  13477. }
  13478. function getInternalFormat(internalFormatName, glFormat, glType, encoding) {
  13479. if (isWebGL2 === false) return glFormat;
  13480. if (internalFormatName !== null) {
  13481. if (_gl[internalFormatName] !== undefined) return _gl[internalFormatName];
  13482. console.warn('THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'');
  13483. }
  13484. let internalFormat = glFormat;
  13485. if (glFormat === _gl.RED) {
  13486. if (glType === _gl.FLOAT) internalFormat = _gl.R32F;
  13487. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.R16F;
  13488. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.R8;
  13489. }
  13490. if (glFormat === _gl.RGB) {
  13491. if (glType === _gl.FLOAT) internalFormat = _gl.RGB32F;
  13492. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGB16F;
  13493. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RGB8;
  13494. }
  13495. if (glFormat === _gl.RGBA) {
  13496. if (glType === _gl.FLOAT) internalFormat = _gl.RGBA32F;
  13497. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGBA16F;
  13498. if (glType === _gl.UNSIGNED_BYTE) internalFormat = encoding === sRGBEncoding ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  13499. }
  13500. if (internalFormat === _gl.R16F || internalFormat === _gl.R32F || internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F) {
  13501. extensions.get('EXT_color_buffer_float');
  13502. }
  13503. return internalFormat;
  13504. }
  13505. function getMipLevels(texture, image, supportsMips) {
  13506. if (textureNeedsGenerateMipmaps(texture, supportsMips) === true || texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  13507. return Math.log2(Math.max(image.width, image.height)) + 1;
  13508. } else if (texture.mipmaps !== undefined && texture.mipmaps.length > 0) {
  13509. // user-defined mipmaps
  13510. return texture.mipmaps.length;
  13511. } else if (texture.isCompressedTexture && Array.isArray(texture.image)) {
  13512. return image.mipmaps.length;
  13513. } else {
  13514. // texture without mipmaps (only base level)
  13515. return 1;
  13516. }
  13517. } // Fallback filters for non-power-of-2 textures
  13518. function filterFallback(f) {
  13519. if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
  13520. return _gl.NEAREST;
  13521. }
  13522. return _gl.LINEAR;
  13523. } //
  13524. function onTextureDispose(event) {
  13525. const texture = event.target;
  13526. texture.removeEventListener('dispose', onTextureDispose);
  13527. deallocateTexture(texture);
  13528. if (texture.isVideoTexture) {
  13529. _videoTextures.delete(texture);
  13530. }
  13531. info.memory.textures--;
  13532. }
  13533. function onRenderTargetDispose(event) {
  13534. const renderTarget = event.target;
  13535. renderTarget.removeEventListener('dispose', onRenderTargetDispose);
  13536. deallocateRenderTarget(renderTarget);
  13537. } //
  13538. function deallocateTexture(texture) {
  13539. const textureProperties = properties.get(texture);
  13540. if (textureProperties.__webglInit === undefined) return;
  13541. _gl.deleteTexture(textureProperties.__webglTexture);
  13542. properties.remove(texture);
  13543. }
  13544. function deallocateRenderTarget(renderTarget) {
  13545. const texture = renderTarget.texture;
  13546. const renderTargetProperties = properties.get(renderTarget);
  13547. const textureProperties = properties.get(texture);
  13548. if (!renderTarget) return;
  13549. if (textureProperties.__webglTexture !== undefined) {
  13550. _gl.deleteTexture(textureProperties.__webglTexture);
  13551. info.memory.textures--;
  13552. }
  13553. if (renderTarget.depthTexture) {
  13554. renderTarget.depthTexture.dispose();
  13555. }
  13556. if (renderTarget.isWebGLCubeRenderTarget) {
  13557. for (let i = 0; i < 6; i++) {
  13558. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
  13559. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
  13560. }
  13561. } else {
  13562. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
  13563. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
  13564. if (renderTargetProperties.__webglMultisampledFramebuffer) _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer);
  13565. if (renderTargetProperties.__webglColorRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer);
  13566. if (renderTargetProperties.__webglDepthRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer);
  13567. }
  13568. if (renderTarget.isWebGLMultipleRenderTargets) {
  13569. for (let i = 0, il = texture.length; i < il; i++) {
  13570. const attachmentProperties = properties.get(texture[i]);
  13571. if (attachmentProperties.__webglTexture) {
  13572. _gl.deleteTexture(attachmentProperties.__webglTexture);
  13573. info.memory.textures--;
  13574. }
  13575. properties.remove(texture[i]);
  13576. }
  13577. }
  13578. properties.remove(texture);
  13579. properties.remove(renderTarget);
  13580. } //
  13581. let textureUnits = 0;
  13582. function resetTextureUnits() {
  13583. textureUnits = 0;
  13584. }
  13585. function allocateTextureUnit() {
  13586. const textureUnit = textureUnits;
  13587. if (textureUnit >= maxTextures) {
  13588. console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures);
  13589. }
  13590. textureUnits += 1;
  13591. return textureUnit;
  13592. } //
  13593. function setTexture2D(texture, slot) {
  13594. const textureProperties = properties.get(texture);
  13595. if (texture.isVideoTexture) updateVideoTexture(texture);
  13596. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13597. const image = texture.image;
  13598. if (image === undefined) {
  13599. console.warn('THREE.WebGLRenderer: Texture marked for update but image is undefined');
  13600. } else if (image.complete === false) {
  13601. console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
  13602. } else {
  13603. uploadTexture(textureProperties, texture, slot);
  13604. return;
  13605. }
  13606. }
  13607. state.activeTexture(_gl.TEXTURE0 + slot);
  13608. state.bindTexture(_gl.TEXTURE_2D, textureProperties.__webglTexture);
  13609. }
  13610. function setTexture2DArray(texture, slot) {
  13611. const textureProperties = properties.get(texture);
  13612. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13613. uploadTexture(textureProperties, texture, slot);
  13614. return;
  13615. }
  13616. state.activeTexture(_gl.TEXTURE0 + slot);
  13617. state.bindTexture(_gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture);
  13618. }
  13619. function setTexture3D(texture, slot) {
  13620. const textureProperties = properties.get(texture);
  13621. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13622. uploadTexture(textureProperties, texture, slot);
  13623. return;
  13624. }
  13625. state.activeTexture(_gl.TEXTURE0 + slot);
  13626. state.bindTexture(_gl.TEXTURE_3D, textureProperties.__webglTexture);
  13627. }
  13628. function setTextureCube(texture, slot) {
  13629. const textureProperties = properties.get(texture);
  13630. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13631. uploadCubeTexture(textureProperties, texture, slot);
  13632. return;
  13633. }
  13634. state.activeTexture(_gl.TEXTURE0 + slot);
  13635. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  13636. }
  13637. const wrappingToGL = {
  13638. [RepeatWrapping]: _gl.REPEAT,
  13639. [ClampToEdgeWrapping]: _gl.CLAMP_TO_EDGE,
  13640. [MirroredRepeatWrapping]: _gl.MIRRORED_REPEAT
  13641. };
  13642. const filterToGL = {
  13643. [NearestFilter]: _gl.NEAREST,
  13644. [NearestMipmapNearestFilter]: _gl.NEAREST_MIPMAP_NEAREST,
  13645. [NearestMipmapLinearFilter]: _gl.NEAREST_MIPMAP_LINEAR,
  13646. [LinearFilter]: _gl.LINEAR,
  13647. [LinearMipmapNearestFilter]: _gl.LINEAR_MIPMAP_NEAREST,
  13648. [LinearMipmapLinearFilter]: _gl.LINEAR_MIPMAP_LINEAR
  13649. };
  13650. function setTextureParameters(textureType, texture, supportsMips) {
  13651. if (supportsMips) {
  13652. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[texture.wrapS]);
  13653. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[texture.wrapT]);
  13654. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  13655. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[texture.wrapR]);
  13656. }
  13657. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[texture.magFilter]);
  13658. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[texture.minFilter]);
  13659. } else {
  13660. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE);
  13661. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE);
  13662. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  13663. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, _gl.CLAMP_TO_EDGE);
  13664. }
  13665. if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
  13666. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
  13667. }
  13668. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterFallback(texture.magFilter));
  13669. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterFallback(texture.minFilter));
  13670. if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  13671. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
  13672. }
  13673. }
  13674. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  13675. const extension = extensions.get('EXT_texture_filter_anisotropic');
  13676. if (texture.type === FloatType && extensions.has('OES_texture_float_linear') === false) return; // verify extension for WebGL 1 and WebGL 2
  13677. if (isWebGL2 === false && texture.type === HalfFloatType && extensions.has('OES_texture_half_float_linear') === false) return; // verify extension for WebGL 1 only
  13678. if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
  13679. _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
  13680. properties.get(texture).__currentAnisotropy = texture.anisotropy;
  13681. }
  13682. }
  13683. }
  13684. function initTexture(textureProperties, texture) {
  13685. if (textureProperties.__webglInit === undefined) {
  13686. textureProperties.__webglInit = true;
  13687. texture.addEventListener('dispose', onTextureDispose);
  13688. textureProperties.__webglTexture = _gl.createTexture();
  13689. info.memory.textures++;
  13690. }
  13691. }
  13692. function uploadTexture(textureProperties, texture, slot) {
  13693. let textureType = _gl.TEXTURE_2D;
  13694. if (texture.isDataTexture2DArray) textureType = _gl.TEXTURE_2D_ARRAY;
  13695. if (texture.isDataTexture3D) textureType = _gl.TEXTURE_3D;
  13696. initTexture(textureProperties, texture);
  13697. state.activeTexture(_gl.TEXTURE0 + slot);
  13698. state.bindTexture(textureType, textureProperties.__webglTexture);
  13699. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  13700. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  13701. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  13702. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  13703. const needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo$1(texture.image) === false;
  13704. const image = resizeImage(texture.image, needsPowerOfTwo, false, maxTextureSize);
  13705. const supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  13706. glFormat = utils.convert(texture.format);
  13707. let glType = utils.convert(texture.type),
  13708. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  13709. setTextureParameters(textureType, texture, supportsMips);
  13710. let mipmap;
  13711. const mipmaps = texture.mipmaps;
  13712. const useTexStorage = isWebGL2 && texture.isVideoTexture !== true;
  13713. const allocateMemory = textureProperties.__version === undefined;
  13714. const levels = getMipLevels(texture, image, supportsMips);
  13715. if (texture.isDepthTexture) {
  13716. // populate depth texture with dummy data
  13717. glInternalFormat = _gl.DEPTH_COMPONENT;
  13718. if (isWebGL2) {
  13719. if (texture.type === FloatType) {
  13720. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  13721. } else if (texture.type === UnsignedIntType) {
  13722. glInternalFormat = _gl.DEPTH_COMPONENT24;
  13723. } else if (texture.type === UnsignedInt248Type) {
  13724. glInternalFormat = _gl.DEPTH24_STENCIL8;
  13725. } else {
  13726. glInternalFormat = _gl.DEPTH_COMPONENT16; // WebGL2 requires sized internalformat for glTexImage2D
  13727. }
  13728. } else {
  13729. if (texture.type === FloatType) {
  13730. console.error('WebGLRenderer: Floating point depth texture requires WebGL2.');
  13731. }
  13732. } // validation checks for WebGL 1
  13733. if (texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  13734. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13735. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  13736. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13737. if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
  13738. console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
  13739. texture.type = UnsignedShortType;
  13740. glType = utils.convert(texture.type);
  13741. }
  13742. }
  13743. if (texture.format === DepthStencilFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  13744. // Depth stencil textures need the DEPTH_STENCIL internal format
  13745. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13746. glInternalFormat = _gl.DEPTH_STENCIL; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13747. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  13748. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13749. if (texture.type !== UnsignedInt248Type) {
  13750. console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
  13751. texture.type = UnsignedInt248Type;
  13752. glType = utils.convert(texture.type);
  13753. }
  13754. } //
  13755. if (useTexStorage && allocateMemory) {
  13756. state.texStorage2D(_gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height);
  13757. } else {
  13758. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  13759. }
  13760. } else if (texture.isDataTexture) {
  13761. // use manually created mipmaps if available
  13762. // if there are no manual mipmaps
  13763. // set 0 level mipmap and then use GL to generate other mipmap levels
  13764. if (mipmaps.length > 0 && supportsMips) {
  13765. if (useTexStorage && allocateMemory) {
  13766. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height);
  13767. }
  13768. for (let i = 0, il = mipmaps.length; i < il; i++) {
  13769. mipmap = mipmaps[i];
  13770. if (useTexStorage) {
  13771. state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data);
  13772. } else {
  13773. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13774. }
  13775. }
  13776. texture.generateMipmaps = false;
  13777. } else {
  13778. if (useTexStorage) {
  13779. if (allocateMemory) {
  13780. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height);
  13781. }
  13782. state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data);
  13783. } else {
  13784. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
  13785. }
  13786. }
  13787. } else if (texture.isCompressedTexture) {
  13788. if (useTexStorage && allocateMemory) {
  13789. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height);
  13790. }
  13791. for (let i = 0, il = mipmaps.length; i < il; i++) {
  13792. mipmap = mipmaps[i];
  13793. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  13794. if (glFormat !== null) {
  13795. if (useTexStorage) {
  13796. state.compressedTexSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data);
  13797. } else {
  13798. state.compressedTexImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  13799. }
  13800. } else {
  13801. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
  13802. }
  13803. } else {
  13804. if (useTexStorage) {
  13805. state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data);
  13806. } else {
  13807. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13808. }
  13809. }
  13810. }
  13811. } else if (texture.isDataTexture2DArray) {
  13812. if (useTexStorage) {
  13813. if (allocateMemory) {
  13814. state.texStorage3D(_gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth);
  13815. }
  13816. state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data);
  13817. } else {
  13818. state.texImage3D(_gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  13819. }
  13820. } else if (texture.isDataTexture3D) {
  13821. if (useTexStorage) {
  13822. if (allocateMemory) {
  13823. state.texStorage3D(_gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth);
  13824. }
  13825. state.texSubImage3D(_gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data);
  13826. } else {
  13827. state.texImage3D(_gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  13828. }
  13829. } else if (texture.isFramebufferTexture) {
  13830. if (useTexStorage && allocateMemory) {
  13831. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height);
  13832. } else {
  13833. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  13834. }
  13835. } else {
  13836. // regular Texture (image, video, canvas)
  13837. // use manually created mipmaps if available
  13838. // if there are no manual mipmaps
  13839. // set 0 level mipmap and then use GL to generate other mipmap levels
  13840. if (mipmaps.length > 0 && supportsMips) {
  13841. if (useTexStorage && allocateMemory) {
  13842. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height);
  13843. }
  13844. for (let i = 0, il = mipmaps.length; i < il; i++) {
  13845. mipmap = mipmaps[i];
  13846. if (useTexStorage) {
  13847. state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap);
  13848. } else {
  13849. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap);
  13850. }
  13851. }
  13852. texture.generateMipmaps = false;
  13853. } else {
  13854. if (useTexStorage) {
  13855. if (allocateMemory) {
  13856. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height);
  13857. }
  13858. state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image);
  13859. } else {
  13860. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image);
  13861. }
  13862. }
  13863. }
  13864. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13865. generateMipmap(textureType);
  13866. }
  13867. textureProperties.__version = texture.version;
  13868. if (texture.onUpdate) texture.onUpdate(texture);
  13869. }
  13870. function uploadCubeTexture(textureProperties, texture, slot) {
  13871. if (texture.image.length !== 6) return;
  13872. initTexture(textureProperties, texture);
  13873. state.activeTexture(_gl.TEXTURE0 + slot);
  13874. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  13875. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  13876. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  13877. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  13878. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  13879. const isCompressed = texture && (texture.isCompressedTexture || texture.image[0].isCompressedTexture);
  13880. const isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
  13881. const cubeImage = [];
  13882. for (let i = 0; i < 6; i++) {
  13883. if (!isCompressed && !isDataTexture) {
  13884. cubeImage[i] = resizeImage(texture.image[i], false, true, maxCubemapSize);
  13885. } else {
  13886. cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
  13887. }
  13888. }
  13889. const image = cubeImage[0],
  13890. supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  13891. glFormat = utils.convert(texture.format),
  13892. glType = utils.convert(texture.type),
  13893. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  13894. const useTexStorage = isWebGL2 && texture.isVideoTexture !== true;
  13895. const allocateMemory = textureProperties.__version === undefined;
  13896. let levels = getMipLevels(texture, image, supportsMips);
  13897. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  13898. let mipmaps;
  13899. if (isCompressed) {
  13900. if (useTexStorage && allocateMemory) {
  13901. state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height);
  13902. }
  13903. for (let i = 0; i < 6; i++) {
  13904. mipmaps = cubeImage[i].mipmaps;
  13905. for (let j = 0; j < mipmaps.length; j++) {
  13906. const mipmap = mipmaps[j];
  13907. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  13908. if (glFormat !== null) {
  13909. if (useTexStorage) {
  13910. state.compressedTexSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data);
  13911. } else {
  13912. state.compressedTexImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  13913. }
  13914. } else {
  13915. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
  13916. }
  13917. } else {
  13918. if (useTexStorage) {
  13919. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data);
  13920. } else {
  13921. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13922. }
  13923. }
  13924. }
  13925. }
  13926. } else {
  13927. mipmaps = texture.mipmaps;
  13928. if (useTexStorage && allocateMemory) {
  13929. // TODO: Uniformly handle mipmap definitions
  13930. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  13931. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  13932. if (mipmaps.length > 0) levels++;
  13933. state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, cubeImage[0].width, cubeImage[0].height);
  13934. }
  13935. for (let i = 0; i < 6; i++) {
  13936. if (isDataTexture) {
  13937. if (useTexStorage) {
  13938. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[i].width, cubeImage[i].height, glFormat, glType, cubeImage[i].data);
  13939. } else {
  13940. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data);
  13941. }
  13942. for (let j = 0; j < mipmaps.length; j++) {
  13943. const mipmap = mipmaps[j];
  13944. const mipmapImage = mipmap.image[i].image;
  13945. if (useTexStorage) {
  13946. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data);
  13947. } else {
  13948. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
  13949. }
  13950. }
  13951. } else {
  13952. if (useTexStorage) {
  13953. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[i]);
  13954. } else {
  13955. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]);
  13956. }
  13957. for (let j = 0; j < mipmaps.length; j++) {
  13958. const mipmap = mipmaps[j];
  13959. if (useTexStorage) {
  13960. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[i]);
  13961. } else {
  13962. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]);
  13963. }
  13964. }
  13965. }
  13966. }
  13967. }
  13968. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13969. // We assume images for cube map have the same size.
  13970. generateMipmap(_gl.TEXTURE_CUBE_MAP);
  13971. }
  13972. textureProperties.__version = texture.version;
  13973. if (texture.onUpdate) texture.onUpdate(texture);
  13974. } // Render targets
  13975. // Setup storage for target texture and bind it to correct framebuffer
  13976. function setupFrameBufferTexture(framebuffer, renderTarget, texture, attachment, textureTarget) {
  13977. const glFormat = utils.convert(texture.format);
  13978. const glType = utils.convert(texture.type);
  13979. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  13980. const renderTargetProperties = properties.get(renderTarget);
  13981. if (!renderTargetProperties.__hasExternalTextures) {
  13982. if (textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY) {
  13983. state.texImage3D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null);
  13984. } else {
  13985. state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
  13986. }
  13987. }
  13988. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  13989. if (renderTarget.useRenderToTexture) {
  13990. MultisampledRenderToTextureExtension.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, attachment, textureTarget, properties.get(texture).__webglTexture, 0, getRenderTargetSamples(renderTarget));
  13991. } else {
  13992. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, attachment, textureTarget, properties.get(texture).__webglTexture, 0);
  13993. }
  13994. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  13995. } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  13996. function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
  13997. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer);
  13998. if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
  13999. let glInternalFormat = _gl.DEPTH_COMPONENT16;
  14000. if (isMultisample || renderTarget.useRenderToTexture) {
  14001. const depthTexture = renderTarget.depthTexture;
  14002. if (depthTexture && depthTexture.isDepthTexture) {
  14003. if (depthTexture.type === FloatType) {
  14004. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  14005. } else if (depthTexture.type === UnsignedIntType) {
  14006. glInternalFormat = _gl.DEPTH_COMPONENT24;
  14007. }
  14008. }
  14009. const samples = getRenderTargetSamples(renderTarget);
  14010. if (renderTarget.useRenderToTexture) {
  14011. MultisampledRenderToTextureExtension.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14012. } else {
  14013. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14014. }
  14015. } else {
  14016. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  14017. }
  14018. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  14019. } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
  14020. const samples = getRenderTargetSamples(renderTarget);
  14021. if (isMultisample && renderTarget.useRenderbuffer) {
  14022. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height);
  14023. } else if (renderTarget.useRenderToTexture) {
  14024. MultisampledRenderToTextureExtension.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height);
  14025. } else {
  14026. _gl.renderbufferStorage(_gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height);
  14027. }
  14028. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  14029. } else {
  14030. // Use the first texture for MRT so far
  14031. const texture = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture[0] : renderTarget.texture;
  14032. const glFormat = utils.convert(texture.format);
  14033. const glType = utils.convert(texture.type);
  14034. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  14035. const samples = getRenderTargetSamples(renderTarget);
  14036. if (isMultisample && renderTarget.useRenderbuffer) {
  14037. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14038. } else if (renderTarget.useRenderToTexture) {
  14039. MultisampledRenderToTextureExtension.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14040. } else {
  14041. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  14042. }
  14043. }
  14044. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  14045. } // Setup resources for a Depth Texture for a FBO (needs an extension)
  14046. function setupDepthTexture(framebuffer, renderTarget) {
  14047. const isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget;
  14048. if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
  14049. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  14050. if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
  14051. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  14052. } // upload an empty depth texture with framebuffer size
  14053. if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
  14054. renderTarget.depthTexture.image.width = renderTarget.width;
  14055. renderTarget.depthTexture.image.height = renderTarget.height;
  14056. renderTarget.depthTexture.needsUpdate = true;
  14057. }
  14058. setTexture2D(renderTarget.depthTexture, 0);
  14059. const webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
  14060. const samples = getRenderTargetSamples(renderTarget);
  14061. if (renderTarget.depthTexture.format === DepthFormat) {
  14062. if (renderTarget.useRenderToTexture) {
  14063. MultisampledRenderToTextureExtension.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples);
  14064. } else {
  14065. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  14066. }
  14067. } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
  14068. if (renderTarget.useRenderToTexture) {
  14069. MultisampledRenderToTextureExtension.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples);
  14070. } else {
  14071. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  14072. }
  14073. } else {
  14074. throw new Error('Unknown depthTexture format');
  14075. }
  14076. } // Setup GL resources for a non-texture depth buffer
  14077. function setupDepthRenderbuffer(renderTarget) {
  14078. const renderTargetProperties = properties.get(renderTarget);
  14079. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  14080. if (renderTarget.depthTexture && !renderTargetProperties.__autoAllocateDepthBuffer) {
  14081. if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
  14082. setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
  14083. } else {
  14084. if (isCube) {
  14085. renderTargetProperties.__webglDepthbuffer = [];
  14086. for (let i = 0; i < 6; i++) {
  14087. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[i]);
  14088. renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
  14089. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false);
  14090. }
  14091. } else {
  14092. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  14093. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  14094. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false);
  14095. }
  14096. }
  14097. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  14098. } // rebind framebuffer with external textures
  14099. function rebindTextures(renderTarget, colorTexture, depthTexture) {
  14100. const renderTargetProperties = properties.get(renderTarget);
  14101. if (colorTexture !== undefined) {
  14102. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D);
  14103. }
  14104. if (depthTexture !== undefined) {
  14105. setupDepthRenderbuffer(renderTarget);
  14106. }
  14107. } // Set up GL resources for the render target
  14108. function setupRenderTarget(renderTarget) {
  14109. const texture = renderTarget.texture;
  14110. const renderTargetProperties = properties.get(renderTarget);
  14111. const textureProperties = properties.get(texture);
  14112. renderTarget.addEventListener('dispose', onRenderTargetDispose);
  14113. if (renderTarget.isWebGLMultipleRenderTargets !== true) {
  14114. if (textureProperties.__webglTexture === undefined) {
  14115. textureProperties.__webglTexture = _gl.createTexture();
  14116. }
  14117. textureProperties.__version = texture.version;
  14118. info.memory.textures++;
  14119. }
  14120. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  14121. const isMultipleRenderTargets = renderTarget.isWebGLMultipleRenderTargets === true;
  14122. const isRenderTarget3D = texture.isDataTexture3D || texture.isDataTexture2DArray;
  14123. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2; // Handles WebGL2 RGBFormat fallback - #18858
  14124. if (isWebGL2 && texture.format === RGBFormat && (texture.type === FloatType || texture.type === HalfFloatType)) {
  14125. texture.format = RGBAFormat;
  14126. console.warn('THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.');
  14127. } // Setup framebuffer
  14128. if (isCube) {
  14129. renderTargetProperties.__webglFramebuffer = [];
  14130. for (let i = 0; i < 6; i++) {
  14131. renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
  14132. }
  14133. } else {
  14134. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  14135. if (isMultipleRenderTargets) {
  14136. if (capabilities.drawBuffers) {
  14137. const textures = renderTarget.texture;
  14138. for (let i = 0, il = textures.length; i < il; i++) {
  14139. const attachmentProperties = properties.get(textures[i]);
  14140. if (attachmentProperties.__webglTexture === undefined) {
  14141. attachmentProperties.__webglTexture = _gl.createTexture();
  14142. info.memory.textures++;
  14143. }
  14144. }
  14145. } else {
  14146. console.warn('THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.');
  14147. }
  14148. } else if (renderTarget.useRenderbuffer) {
  14149. if (isWebGL2) {
  14150. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  14151. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  14152. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer);
  14153. const glFormat = utils.convert(texture.format);
  14154. const glType = utils.convert(texture.type);
  14155. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  14156. const samples = getRenderTargetSamples(renderTarget);
  14157. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14158. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14159. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer);
  14160. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  14161. if (renderTarget.depthBuffer) {
  14162. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  14163. setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
  14164. }
  14165. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  14166. } else {
  14167. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  14168. }
  14169. }
  14170. } // Setup color buffer
  14171. if (isCube) {
  14172. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  14173. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  14174. for (let i = 0; i < 6; i++) {
  14175. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i);
  14176. }
  14177. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14178. generateMipmap(_gl.TEXTURE_CUBE_MAP);
  14179. }
  14180. state.unbindTexture();
  14181. } else if (isMultipleRenderTargets) {
  14182. const textures = renderTarget.texture;
  14183. for (let i = 0, il = textures.length; i < il; i++) {
  14184. const attachment = textures[i];
  14185. const attachmentProperties = properties.get(attachment);
  14186. state.bindTexture(_gl.TEXTURE_2D, attachmentProperties.__webglTexture);
  14187. setTextureParameters(_gl.TEXTURE_2D, attachment, supportsMips);
  14188. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D);
  14189. if (textureNeedsGenerateMipmaps(attachment, supportsMips)) {
  14190. generateMipmap(_gl.TEXTURE_2D);
  14191. }
  14192. }
  14193. state.unbindTexture();
  14194. } else {
  14195. let glTextureType = _gl.TEXTURE_2D;
  14196. if (isRenderTarget3D) {
  14197. // Render targets containing layers, i.e: Texture 3D and 2d arrays
  14198. if (isWebGL2) {
  14199. const isTexture3D = texture.isDataTexture3D;
  14200. glTextureType = isTexture3D ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  14201. } else {
  14202. console.warn('THREE.DataTexture3D and THREE.DataTexture2DArray only supported with WebGL2.');
  14203. }
  14204. }
  14205. state.bindTexture(glTextureType, textureProperties.__webglTexture);
  14206. setTextureParameters(glTextureType, texture, supportsMips);
  14207. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType);
  14208. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14209. generateMipmap(glTextureType);
  14210. }
  14211. state.unbindTexture();
  14212. } // Setup depth and stencil buffers
  14213. if (renderTarget.depthBuffer) {
  14214. setupDepthRenderbuffer(renderTarget);
  14215. }
  14216. }
  14217. function updateRenderTargetMipmap(renderTarget) {
  14218. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2;
  14219. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [renderTarget.texture];
  14220. for (let i = 0, il = textures.length; i < il; i++) {
  14221. const texture = textures[i];
  14222. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14223. const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  14224. const webglTexture = properties.get(texture).__webglTexture;
  14225. state.bindTexture(target, webglTexture);
  14226. generateMipmap(target);
  14227. state.unbindTexture();
  14228. }
  14229. }
  14230. }
  14231. function updateMultisampleRenderTarget(renderTarget) {
  14232. if (renderTarget.useRenderbuffer) {
  14233. if (isWebGL2) {
  14234. const width = renderTarget.width;
  14235. const height = renderTarget.height;
  14236. let mask = _gl.COLOR_BUFFER_BIT;
  14237. const invalidationArray = [_gl.COLOR_ATTACHMENT0];
  14238. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  14239. if (renderTarget.depthBuffer) {
  14240. invalidationArray.push(depthStyle);
  14241. }
  14242. if (!renderTarget.ignoreDepthForMultisampleCopy) {
  14243. if (renderTarget.depthBuffer) mask |= _gl.DEPTH_BUFFER_BIT;
  14244. if (renderTarget.stencilBuffer) mask |= _gl.STENCIL_BUFFER_BIT;
  14245. }
  14246. const renderTargetProperties = properties.get(renderTarget);
  14247. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14248. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  14249. if (renderTarget.ignoreDepthForMultisampleCopy) {
  14250. _gl.invalidateFramebuffer(_gl.READ_FRAMEBUFFER, [depthStyle]);
  14251. _gl.invalidateFramebuffer(_gl.DRAW_FRAMEBUFFER, [depthStyle]);
  14252. }
  14253. _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST);
  14254. _gl.invalidateFramebuffer(_gl.READ_FRAMEBUFFER, invalidationArray);
  14255. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null);
  14256. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14257. } else {
  14258. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  14259. }
  14260. }
  14261. }
  14262. function getRenderTargetSamples(renderTarget) {
  14263. return isWebGL2 && (renderTarget.useRenderbuffer || renderTarget.useRenderToTexture) ? Math.min(maxSamples, renderTarget.samples) : 0;
  14264. }
  14265. function updateVideoTexture(texture) {
  14266. const frame = info.render.frame; // Check the last frame we updated the VideoTexture
  14267. if (_videoTextures.get(texture) !== frame) {
  14268. _videoTextures.set(texture, frame);
  14269. texture.update();
  14270. }
  14271. } // backwards compatibility
  14272. let warnedTexture2D = false;
  14273. let warnedTextureCube = false;
  14274. function safeSetTexture2D(texture, slot) {
  14275. if (texture && texture.isWebGLRenderTarget) {
  14276. if (warnedTexture2D === false) {
  14277. console.warn('THREE.WebGLTextures.safeSetTexture2D: don\'t use render targets as textures. Use their .texture property instead.');
  14278. warnedTexture2D = true;
  14279. }
  14280. texture = texture.texture;
  14281. }
  14282. setTexture2D(texture, slot);
  14283. }
  14284. function safeSetTextureCube(texture, slot) {
  14285. if (texture && texture.isWebGLCubeRenderTarget) {
  14286. if (warnedTextureCube === false) {
  14287. console.warn('THREE.WebGLTextures.safeSetTextureCube: don\'t use cube render targets as textures. Use their .texture property instead.');
  14288. warnedTextureCube = true;
  14289. }
  14290. texture = texture.texture;
  14291. }
  14292. setTextureCube(texture, slot);
  14293. } //
  14294. this.allocateTextureUnit = allocateTextureUnit;
  14295. this.resetTextureUnits = resetTextureUnits;
  14296. this.setTexture2D = setTexture2D;
  14297. this.setTexture2DArray = setTexture2DArray;
  14298. this.setTexture3D = setTexture3D;
  14299. this.setTextureCube = setTextureCube;
  14300. this.rebindTextures = rebindTextures;
  14301. this.setupRenderTarget = setupRenderTarget;
  14302. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  14303. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  14304. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  14305. this.setupFrameBufferTexture = setupFrameBufferTexture;
  14306. this.safeSetTexture2D = safeSetTexture2D;
  14307. this.safeSetTextureCube = safeSetTextureCube;
  14308. }
  14309. function WebGLUtils(gl, extensions, capabilities) {
  14310. const isWebGL2 = capabilities.isWebGL2;
  14311. function convert(p) {
  14312. let extension;
  14313. if (p === UnsignedByteType) return gl.UNSIGNED_BYTE;
  14314. if (p === UnsignedShort4444Type) return gl.UNSIGNED_SHORT_4_4_4_4;
  14315. if (p === UnsignedShort5551Type) return gl.UNSIGNED_SHORT_5_5_5_1;
  14316. if (p === UnsignedShort565Type) return gl.UNSIGNED_SHORT_5_6_5;
  14317. if (p === ByteType) return gl.BYTE;
  14318. if (p === ShortType) return gl.SHORT;
  14319. if (p === UnsignedShortType) return gl.UNSIGNED_SHORT;
  14320. if (p === IntType) return gl.INT;
  14321. if (p === UnsignedIntType) return gl.UNSIGNED_INT;
  14322. if (p === FloatType) return gl.FLOAT;
  14323. if (p === HalfFloatType) {
  14324. if (isWebGL2) return gl.HALF_FLOAT;
  14325. extension = extensions.get('OES_texture_half_float');
  14326. if (extension !== null) {
  14327. return extension.HALF_FLOAT_OES;
  14328. } else {
  14329. return null;
  14330. }
  14331. }
  14332. if (p === AlphaFormat) return gl.ALPHA;
  14333. if (p === RGBFormat) return gl.RGB;
  14334. if (p === RGBAFormat) return gl.RGBA;
  14335. if (p === LuminanceFormat) return gl.LUMINANCE;
  14336. if (p === LuminanceAlphaFormat) return gl.LUMINANCE_ALPHA;
  14337. if (p === DepthFormat) return gl.DEPTH_COMPONENT;
  14338. if (p === DepthStencilFormat) return gl.DEPTH_STENCIL;
  14339. if (p === RedFormat) return gl.RED; // WebGL2 formats.
  14340. if (p === RedIntegerFormat) return gl.RED_INTEGER;
  14341. if (p === RGFormat) return gl.RG;
  14342. if (p === RGIntegerFormat) return gl.RG_INTEGER;
  14343. if (p === RGBIntegerFormat) return gl.RGB_INTEGER;
  14344. if (p === RGBAIntegerFormat) return gl.RGBA_INTEGER;
  14345. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  14346. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  14347. if (extension !== null) {
  14348. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14349. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14350. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14351. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14352. } else {
  14353. return null;
  14354. }
  14355. }
  14356. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  14357. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  14358. if (extension !== null) {
  14359. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  14360. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  14361. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  14362. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  14363. } else {
  14364. return null;
  14365. }
  14366. }
  14367. if (p === RGB_ETC1_Format) {
  14368. extension = extensions.get('WEBGL_compressed_texture_etc1');
  14369. if (extension !== null) {
  14370. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  14371. } else {
  14372. return null;
  14373. }
  14374. }
  14375. if (p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format) {
  14376. extension = extensions.get('WEBGL_compressed_texture_etc');
  14377. if (extension !== null) {
  14378. if (p === RGB_ETC2_Format) return extension.COMPRESSED_RGB8_ETC2;
  14379. if (p === RGBA_ETC2_EAC_Format) return extension.COMPRESSED_RGBA8_ETC2_EAC;
  14380. }
  14381. }
  14382. 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) {
  14383. extension = extensions.get('WEBGL_compressed_texture_astc');
  14384. if (extension !== null) {
  14385. // TODO Complete?
  14386. return p;
  14387. } else {
  14388. return null;
  14389. }
  14390. }
  14391. if (p === RGBA_BPTC_Format) {
  14392. extension = extensions.get('EXT_texture_compression_bptc');
  14393. if (extension !== null) {
  14394. // TODO Complete?
  14395. return p;
  14396. } else {
  14397. return null;
  14398. }
  14399. }
  14400. if (p === UnsignedInt248Type) {
  14401. if (isWebGL2) return gl.UNSIGNED_INT_24_8;
  14402. extension = extensions.get('WEBGL_depth_texture');
  14403. if (extension !== null) {
  14404. return extension.UNSIGNED_INT_24_8_WEBGL;
  14405. } else {
  14406. return null;
  14407. }
  14408. }
  14409. }
  14410. return {
  14411. convert: convert
  14412. };
  14413. }
  14414. class ArrayCamera extends PerspectiveCamera {
  14415. constructor(array = []) {
  14416. super();
  14417. this.cameras = array;
  14418. }
  14419. }
  14420. ArrayCamera.prototype.isArrayCamera = true;
  14421. class Group extends Object3D {
  14422. constructor() {
  14423. super();
  14424. this.type = 'Group';
  14425. }
  14426. }
  14427. Group.prototype.isGroup = true;
  14428. const _moveEvent = {
  14429. type: 'move'
  14430. };
  14431. class WebXRController {
  14432. constructor() {
  14433. this._targetRay = null;
  14434. this._grip = null;
  14435. this._hand = null;
  14436. }
  14437. getHandSpace() {
  14438. if (this._hand === null) {
  14439. this._hand = new Group();
  14440. this._hand.matrixAutoUpdate = false;
  14441. this._hand.visible = false;
  14442. this._hand.joints = {};
  14443. this._hand.inputState = {
  14444. pinching: false
  14445. };
  14446. }
  14447. return this._hand;
  14448. }
  14449. getTargetRaySpace() {
  14450. if (this._targetRay === null) {
  14451. this._targetRay = new Group();
  14452. this._targetRay.matrixAutoUpdate = false;
  14453. this._targetRay.visible = false;
  14454. this._targetRay.hasLinearVelocity = false;
  14455. this._targetRay.linearVelocity = new Vector3();
  14456. this._targetRay.hasAngularVelocity = false;
  14457. this._targetRay.angularVelocity = new Vector3();
  14458. }
  14459. return this._targetRay;
  14460. }
  14461. getGripSpace() {
  14462. if (this._grip === null) {
  14463. this._grip = new Group();
  14464. this._grip.matrixAutoUpdate = false;
  14465. this._grip.visible = false;
  14466. this._grip.hasLinearVelocity = false;
  14467. this._grip.linearVelocity = new Vector3();
  14468. this._grip.hasAngularVelocity = false;
  14469. this._grip.angularVelocity = new Vector3();
  14470. }
  14471. return this._grip;
  14472. }
  14473. dispatchEvent(event) {
  14474. if (this._targetRay !== null) {
  14475. this._targetRay.dispatchEvent(event);
  14476. }
  14477. if (this._grip !== null) {
  14478. this._grip.dispatchEvent(event);
  14479. }
  14480. if (this._hand !== null) {
  14481. this._hand.dispatchEvent(event);
  14482. }
  14483. return this;
  14484. }
  14485. disconnect(inputSource) {
  14486. this.dispatchEvent({
  14487. type: 'disconnected',
  14488. data: inputSource
  14489. });
  14490. if (this._targetRay !== null) {
  14491. this._targetRay.visible = false;
  14492. }
  14493. if (this._grip !== null) {
  14494. this._grip.visible = false;
  14495. }
  14496. if (this._hand !== null) {
  14497. this._hand.visible = false;
  14498. }
  14499. return this;
  14500. }
  14501. update(inputSource, frame, referenceSpace) {
  14502. let inputPose = null;
  14503. let gripPose = null;
  14504. let handPose = null;
  14505. const targetRay = this._targetRay;
  14506. const grip = this._grip;
  14507. const hand = this._hand;
  14508. if (inputSource && frame.session.visibilityState !== 'visible-blurred') {
  14509. if (targetRay !== null) {
  14510. inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace);
  14511. if (inputPose !== null) {
  14512. targetRay.matrix.fromArray(inputPose.transform.matrix);
  14513. targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale);
  14514. if (inputPose.linearVelocity) {
  14515. targetRay.hasLinearVelocity = true;
  14516. targetRay.linearVelocity.copy(inputPose.linearVelocity);
  14517. } else {
  14518. targetRay.hasLinearVelocity = false;
  14519. }
  14520. if (inputPose.angularVelocity) {
  14521. targetRay.hasAngularVelocity = true;
  14522. targetRay.angularVelocity.copy(inputPose.angularVelocity);
  14523. } else {
  14524. targetRay.hasAngularVelocity = false;
  14525. }
  14526. this.dispatchEvent(_moveEvent);
  14527. }
  14528. }
  14529. if (hand && inputSource.hand) {
  14530. handPose = true;
  14531. for (const inputjoint of inputSource.hand.values()) {
  14532. // Update the joints groups with the XRJoint poses
  14533. const jointPose = frame.getJointPose(inputjoint, referenceSpace);
  14534. if (hand.joints[inputjoint.jointName] === undefined) {
  14535. // The transform of this joint will be updated with the joint pose on each frame
  14536. const joint = new Group();
  14537. joint.matrixAutoUpdate = false;
  14538. joint.visible = false;
  14539. hand.joints[inputjoint.jointName] = joint; // ??
  14540. hand.add(joint);
  14541. }
  14542. const joint = hand.joints[inputjoint.jointName];
  14543. if (jointPose !== null) {
  14544. joint.matrix.fromArray(jointPose.transform.matrix);
  14545. joint.matrix.decompose(joint.position, joint.rotation, joint.scale);
  14546. joint.jointRadius = jointPose.radius;
  14547. }
  14548. joint.visible = jointPose !== null;
  14549. } // Custom events
  14550. // Check pinchz
  14551. const indexTip = hand.joints['index-finger-tip'];
  14552. const thumbTip = hand.joints['thumb-tip'];
  14553. const distance = indexTip.position.distanceTo(thumbTip.position);
  14554. const distanceToPinch = 0.02;
  14555. const threshold = 0.005;
  14556. if (hand.inputState.pinching && distance > distanceToPinch + threshold) {
  14557. hand.inputState.pinching = false;
  14558. this.dispatchEvent({
  14559. type: 'pinchend',
  14560. handedness: inputSource.handedness,
  14561. target: this
  14562. });
  14563. } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) {
  14564. hand.inputState.pinching = true;
  14565. this.dispatchEvent({
  14566. type: 'pinchstart',
  14567. handedness: inputSource.handedness,
  14568. target: this
  14569. });
  14570. }
  14571. } else {
  14572. if (grip !== null && inputSource.gripSpace) {
  14573. gripPose = frame.getPose(inputSource.gripSpace, referenceSpace);
  14574. if (gripPose !== null) {
  14575. grip.matrix.fromArray(gripPose.transform.matrix);
  14576. grip.matrix.decompose(grip.position, grip.rotation, grip.scale);
  14577. if (gripPose.linearVelocity) {
  14578. grip.hasLinearVelocity = true;
  14579. grip.linearVelocity.copy(gripPose.linearVelocity);
  14580. } else {
  14581. grip.hasLinearVelocity = false;
  14582. }
  14583. if (gripPose.angularVelocity) {
  14584. grip.hasAngularVelocity = true;
  14585. grip.angularVelocity.copy(gripPose.angularVelocity);
  14586. } else {
  14587. grip.hasAngularVelocity = false;
  14588. }
  14589. }
  14590. }
  14591. }
  14592. }
  14593. if (targetRay !== null) {
  14594. targetRay.visible = inputPose !== null;
  14595. }
  14596. if (grip !== null) {
  14597. grip.visible = gripPose !== null;
  14598. }
  14599. if (hand !== null) {
  14600. hand.visible = handPose !== null;
  14601. }
  14602. return this;
  14603. }
  14604. }
  14605. class DepthTexture extends Texture {
  14606. constructor(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
  14607. format = format !== undefined ? format : DepthFormat;
  14608. if (format !== DepthFormat && format !== DepthStencilFormat) {
  14609. throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
  14610. }
  14611. if (type === undefined && format === DepthFormat) type = UnsignedShortType;
  14612. if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
  14613. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  14614. this.image = {
  14615. width: width,
  14616. height: height
  14617. };
  14618. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  14619. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  14620. this.flipY = false;
  14621. this.generateMipmaps = false;
  14622. }
  14623. }
  14624. DepthTexture.prototype.isDepthTexture = true;
  14625. class WebXRManager extends EventDispatcher {
  14626. constructor(renderer, gl) {
  14627. super();
  14628. const scope = this;
  14629. let session = null;
  14630. let framebufferScaleFactor = 1.0;
  14631. let referenceSpace = null;
  14632. let referenceSpaceType = 'local-floor';
  14633. const hasMultisampledRenderToTexture = renderer.extensions.has('WEBGL_multisampled_render_to_texture');
  14634. let pose = null;
  14635. let glBinding = null;
  14636. let glProjLayer = null;
  14637. let glBaseLayer = null;
  14638. let isMultisample = false;
  14639. let xrFrame = null;
  14640. const attributes = gl.getContextAttributes();
  14641. let initialRenderTarget = null;
  14642. let newRenderTarget = null;
  14643. const controllers = [];
  14644. const inputSourcesMap = new Map(); //
  14645. const cameraL = new PerspectiveCamera();
  14646. cameraL.layers.enable(1);
  14647. cameraL.viewport = new Vector4();
  14648. const cameraR = new PerspectiveCamera();
  14649. cameraR.layers.enable(2);
  14650. cameraR.viewport = new Vector4();
  14651. const cameras = [cameraL, cameraR];
  14652. const cameraVR = new ArrayCamera();
  14653. cameraVR.layers.enable(1);
  14654. cameraVR.layers.enable(2);
  14655. let _currentDepthNear = null;
  14656. let _currentDepthFar = null; //
  14657. this.cameraAutoUpdate = true;
  14658. this.enabled = false;
  14659. this.isPresenting = false;
  14660. this.getController = function (index) {
  14661. let controller = controllers[index];
  14662. if (controller === undefined) {
  14663. controller = new WebXRController();
  14664. controllers[index] = controller;
  14665. }
  14666. return controller.getTargetRaySpace();
  14667. };
  14668. this.getControllerGrip = function (index) {
  14669. let controller = controllers[index];
  14670. if (controller === undefined) {
  14671. controller = new WebXRController();
  14672. controllers[index] = controller;
  14673. }
  14674. return controller.getGripSpace();
  14675. };
  14676. this.getHand = function (index) {
  14677. let controller = controllers[index];
  14678. if (controller === undefined) {
  14679. controller = new WebXRController();
  14680. controllers[index] = controller;
  14681. }
  14682. return controller.getHandSpace();
  14683. }; //
  14684. function onSessionEvent(event) {
  14685. const controller = inputSourcesMap.get(event.inputSource);
  14686. if (controller) {
  14687. controller.dispatchEvent({
  14688. type: event.type,
  14689. data: event.inputSource
  14690. });
  14691. }
  14692. }
  14693. function onSessionEnd() {
  14694. inputSourcesMap.forEach(function (controller, inputSource) {
  14695. controller.disconnect(inputSource);
  14696. });
  14697. inputSourcesMap.clear();
  14698. _currentDepthNear = null;
  14699. _currentDepthFar = null; // restore framebuffer/rendering state
  14700. renderer.setRenderTarget(initialRenderTarget);
  14701. glBaseLayer = null;
  14702. glProjLayer = null;
  14703. glBinding = null;
  14704. session = null;
  14705. newRenderTarget = null; //
  14706. animation.stop();
  14707. scope.isPresenting = false;
  14708. scope.dispatchEvent({
  14709. type: 'sessionend'
  14710. });
  14711. }
  14712. this.setFramebufferScaleFactor = function (value) {
  14713. framebufferScaleFactor = value;
  14714. if (scope.isPresenting === true) {
  14715. console.warn('THREE.WebXRManager: Cannot change framebuffer scale while presenting.');
  14716. }
  14717. };
  14718. this.setReferenceSpaceType = function (value) {
  14719. referenceSpaceType = value;
  14720. if (scope.isPresenting === true) {
  14721. console.warn('THREE.WebXRManager: Cannot change reference space type while presenting.');
  14722. }
  14723. };
  14724. this.getReferenceSpace = function () {
  14725. return referenceSpace;
  14726. };
  14727. this.getBaseLayer = function () {
  14728. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  14729. };
  14730. this.getBinding = function () {
  14731. return glBinding;
  14732. };
  14733. this.getFrame = function () {
  14734. return xrFrame;
  14735. };
  14736. this.getSession = function () {
  14737. return session;
  14738. };
  14739. this.setSession = async function (value) {
  14740. session = value;
  14741. if (session !== null) {
  14742. initialRenderTarget = renderer.getRenderTarget();
  14743. session.addEventListener('select', onSessionEvent);
  14744. session.addEventListener('selectstart', onSessionEvent);
  14745. session.addEventListener('selectend', onSessionEvent);
  14746. session.addEventListener('squeeze', onSessionEvent);
  14747. session.addEventListener('squeezestart', onSessionEvent);
  14748. session.addEventListener('squeezeend', onSessionEvent);
  14749. session.addEventListener('end', onSessionEnd);
  14750. session.addEventListener('inputsourceschange', onInputSourcesChange);
  14751. if (attributes.xrCompatible !== true) {
  14752. await gl.makeXRCompatible();
  14753. }
  14754. if (session.renderState.layers === undefined || renderer.capabilities.isWebGL2 === false) {
  14755. const layerInit = {
  14756. antialias: session.renderState.layers === undefined ? attributes.antialias : true,
  14757. alpha: attributes.alpha,
  14758. depth: attributes.depth,
  14759. stencil: attributes.stencil,
  14760. framebufferScaleFactor: framebufferScaleFactor
  14761. };
  14762. glBaseLayer = new XRWebGLLayer(session, gl, layerInit);
  14763. session.updateRenderState({
  14764. baseLayer: glBaseLayer
  14765. });
  14766. newRenderTarget = new WebGLRenderTarget(glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, {
  14767. format: RGBAFormat,
  14768. type: UnsignedByteType,
  14769. encoding: renderer.outputEncoding
  14770. });
  14771. } else {
  14772. isMultisample = attributes.antialias;
  14773. let depthFormat = null;
  14774. let depthType = null;
  14775. let glDepthFormat = null;
  14776. if (attributes.depth) {
  14777. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  14778. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  14779. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedShortType;
  14780. }
  14781. const projectionlayerInit = {
  14782. colorFormat: attributes.alpha || isMultisample ? gl.RGBA8 : gl.RGB8,
  14783. depthFormat: glDepthFormat,
  14784. scaleFactor: framebufferScaleFactor
  14785. };
  14786. glBinding = new XRWebGLBinding(session, gl);
  14787. glProjLayer = glBinding.createProjectionLayer(projectionlayerInit);
  14788. session.updateRenderState({
  14789. layers: [glProjLayer]
  14790. });
  14791. if (isMultisample) {
  14792. newRenderTarget = new WebGLMultisampleRenderTarget(glProjLayer.textureWidth, glProjLayer.textureHeight, {
  14793. format: RGBAFormat,
  14794. type: UnsignedByteType,
  14795. depthTexture: new DepthTexture(glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat),
  14796. stencilBuffer: attributes.stencil,
  14797. ignoreDepth: glProjLayer.ignoreDepthValues,
  14798. useRenderToTexture: hasMultisampledRenderToTexture,
  14799. encoding: renderer.outputEncoding
  14800. });
  14801. } else {
  14802. newRenderTarget = new WebGLRenderTarget(glProjLayer.textureWidth, glProjLayer.textureHeight, {
  14803. format: attributes.alpha ? RGBAFormat : RGBFormat,
  14804. type: UnsignedByteType,
  14805. depthTexture: new DepthTexture(glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat),
  14806. stencilBuffer: attributes.stencil,
  14807. ignoreDepth: glProjLayer.ignoreDepthValues,
  14808. encoding: renderer.outputEncoding
  14809. });
  14810. }
  14811. } // Set foveation to maximum.
  14812. this.setFoveation(1.0);
  14813. referenceSpace = await session.requestReferenceSpace(referenceSpaceType);
  14814. animation.setContext(session);
  14815. animation.start();
  14816. scope.isPresenting = true;
  14817. scope.dispatchEvent({
  14818. type: 'sessionstart'
  14819. });
  14820. }
  14821. };
  14822. function onInputSourcesChange(event) {
  14823. const inputSources = session.inputSources; // Assign inputSources to available controllers
  14824. for (let i = 0; i < controllers.length; i++) {
  14825. inputSourcesMap.set(inputSources[i], controllers[i]);
  14826. } // Notify disconnected
  14827. for (let i = 0; i < event.removed.length; i++) {
  14828. const inputSource = event.removed[i];
  14829. const controller = inputSourcesMap.get(inputSource);
  14830. if (controller) {
  14831. controller.dispatchEvent({
  14832. type: 'disconnected',
  14833. data: inputSource
  14834. });
  14835. inputSourcesMap.delete(inputSource);
  14836. }
  14837. } // Notify connected
  14838. for (let i = 0; i < event.added.length; i++) {
  14839. const inputSource = event.added[i];
  14840. const controller = inputSourcesMap.get(inputSource);
  14841. if (controller) {
  14842. controller.dispatchEvent({
  14843. type: 'connected',
  14844. data: inputSource
  14845. });
  14846. }
  14847. }
  14848. } //
  14849. const cameraLPos = new Vector3();
  14850. const cameraRPos = new Vector3();
  14851. /**
  14852. * Assumes 2 cameras that are parallel and share an X-axis, and that
  14853. * the cameras' projection and world matrices have already been set.
  14854. * And that near and far planes are identical for both cameras.
  14855. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  14856. */
  14857. function setProjectionFromUnion(camera, cameraL, cameraR) {
  14858. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  14859. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  14860. const ipd = cameraLPos.distanceTo(cameraRPos);
  14861. const projL = cameraL.projectionMatrix.elements;
  14862. const projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
  14863. // most likely identical top and bottom frustum extents.
  14864. // Use the left camera for these values.
  14865. const near = projL[14] / (projL[10] - 1);
  14866. const far = projL[14] / (projL[10] + 1);
  14867. const topFov = (projL[9] + 1) / projL[5];
  14868. const bottomFov = (projL[9] - 1) / projL[5];
  14869. const leftFov = (projL[8] - 1) / projL[0];
  14870. const rightFov = (projR[8] + 1) / projR[0];
  14871. const left = near * leftFov;
  14872. const right = near * rightFov; // Calculate the new camera's position offset from the
  14873. // left camera. xOffset should be roughly half `ipd`.
  14874. const zOffset = ipd / (-leftFov + rightFov);
  14875. const xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
  14876. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  14877. camera.translateX(xOffset);
  14878. camera.translateZ(zOffset);
  14879. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  14880. camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); // Find the union of the frustum values of the cameras and scale
  14881. // the values so that the near plane's position does not change in world space,
  14882. // although must now be relative to the new union camera.
  14883. const near2 = near + zOffset;
  14884. const far2 = far + zOffset;
  14885. const left2 = left - xOffset;
  14886. const right2 = right + (ipd - xOffset);
  14887. const top2 = topFov * far / far2 * near2;
  14888. const bottom2 = bottomFov * far / far2 * near2;
  14889. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  14890. }
  14891. function updateCamera(camera, parent) {
  14892. if (parent === null) {
  14893. camera.matrixWorld.copy(camera.matrix);
  14894. } else {
  14895. camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
  14896. }
  14897. camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  14898. }
  14899. this.updateCamera = function (camera) {
  14900. if (session === null) return;
  14901. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  14902. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  14903. if (_currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far) {
  14904. // Note that the new renderState won't apply until the next frame. See #18320
  14905. session.updateRenderState({
  14906. depthNear: cameraVR.near,
  14907. depthFar: cameraVR.far
  14908. });
  14909. _currentDepthNear = cameraVR.near;
  14910. _currentDepthFar = cameraVR.far;
  14911. }
  14912. const parent = camera.parent;
  14913. const cameras = cameraVR.cameras;
  14914. updateCamera(cameraVR, parent);
  14915. for (let i = 0; i < cameras.length; i++) {
  14916. updateCamera(cameras[i], parent);
  14917. }
  14918. cameraVR.matrixWorld.decompose(cameraVR.position, cameraVR.quaternion, cameraVR.scale); // update user camera and its children
  14919. camera.position.copy(cameraVR.position);
  14920. camera.quaternion.copy(cameraVR.quaternion);
  14921. camera.scale.copy(cameraVR.scale);
  14922. camera.matrix.copy(cameraVR.matrix);
  14923. camera.matrixWorld.copy(cameraVR.matrixWorld);
  14924. const children = camera.children;
  14925. for (let i = 0, l = children.length; i < l; i++) {
  14926. children[i].updateMatrixWorld(true);
  14927. } // update projection matrix for proper view frustum culling
  14928. if (cameras.length === 2) {
  14929. setProjectionFromUnion(cameraVR, cameraL, cameraR);
  14930. } else {
  14931. // assume single camera setup (AR)
  14932. cameraVR.projectionMatrix.copy(cameraL.projectionMatrix);
  14933. }
  14934. };
  14935. this.getCamera = function () {
  14936. return cameraVR;
  14937. };
  14938. this.getFoveation = function () {
  14939. if (glProjLayer !== null) {
  14940. return glProjLayer.fixedFoveation;
  14941. }
  14942. if (glBaseLayer !== null) {
  14943. return glBaseLayer.fixedFoveation;
  14944. }
  14945. return undefined;
  14946. };
  14947. this.setFoveation = function (foveation) {
  14948. // 0 = no foveation = full resolution
  14949. // 1 = maximum foveation = the edges render at lower resolution
  14950. if (glProjLayer !== null) {
  14951. glProjLayer.fixedFoveation = foveation;
  14952. }
  14953. if (glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined) {
  14954. glBaseLayer.fixedFoveation = foveation;
  14955. }
  14956. }; // Animation Loop
  14957. let onAnimationFrameCallback = null;
  14958. function onAnimationFrame(time, frame) {
  14959. pose = frame.getViewerPose(referenceSpace);
  14960. xrFrame = frame;
  14961. if (pose !== null) {
  14962. const views = pose.views;
  14963. if (glBaseLayer !== null) {
  14964. renderer.setRenderTargetFramebuffer(newRenderTarget, glBaseLayer.framebuffer);
  14965. renderer.setRenderTarget(newRenderTarget);
  14966. }
  14967. let cameraVRNeedsUpdate = false; // check if it's necessary to rebuild cameraVR's camera list
  14968. if (views.length !== cameraVR.cameras.length) {
  14969. cameraVR.cameras.length = 0;
  14970. cameraVRNeedsUpdate = true;
  14971. }
  14972. for (let i = 0; i < views.length; i++) {
  14973. const view = views[i];
  14974. let viewport = null;
  14975. if (glBaseLayer !== null) {
  14976. viewport = glBaseLayer.getViewport(view);
  14977. } else {
  14978. const glSubImage = glBinding.getViewSubImage(glProjLayer, view);
  14979. viewport = glSubImage.viewport; // For side-by-side projection, we only produce a single texture for both eyes.
  14980. if (i === 0) {
  14981. renderer.setRenderTargetTextures(newRenderTarget, glSubImage.colorTexture, glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture);
  14982. renderer.setRenderTarget(newRenderTarget);
  14983. }
  14984. }
  14985. const camera = cameras[i];
  14986. camera.matrix.fromArray(view.transform.matrix);
  14987. camera.projectionMatrix.fromArray(view.projectionMatrix);
  14988. camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
  14989. if (i === 0) {
  14990. cameraVR.matrix.copy(camera.matrix);
  14991. }
  14992. if (cameraVRNeedsUpdate === true) {
  14993. cameraVR.cameras.push(camera);
  14994. }
  14995. }
  14996. } //
  14997. const inputSources = session.inputSources;
  14998. for (let i = 0; i < controllers.length; i++) {
  14999. const controller = controllers[i];
  15000. const inputSource = inputSources[i];
  15001. controller.update(inputSource, frame, referenceSpace);
  15002. }
  15003. if (onAnimationFrameCallback) onAnimationFrameCallback(time, frame);
  15004. xrFrame = null;
  15005. }
  15006. const animation = new WebGLAnimation();
  15007. animation.setAnimationLoop(onAnimationFrame);
  15008. this.setAnimationLoop = function (callback) {
  15009. onAnimationFrameCallback = callback;
  15010. };
  15011. this.dispose = function () {};
  15012. }
  15013. }
  15014. function WebGLMaterials(properties) {
  15015. function refreshFogUniforms(uniforms, fog) {
  15016. uniforms.fogColor.value.copy(fog.color);
  15017. if (fog.isFog) {
  15018. uniforms.fogNear.value = fog.near;
  15019. uniforms.fogFar.value = fog.far;
  15020. } else if (fog.isFogExp2) {
  15021. uniforms.fogDensity.value = fog.density;
  15022. }
  15023. }
  15024. function refreshMaterialUniforms(uniforms, material, pixelRatio, height, transmissionRenderTarget) {
  15025. if (material.isMeshBasicMaterial) {
  15026. refreshUniformsCommon(uniforms, material);
  15027. } else if (material.isMeshLambertMaterial) {
  15028. refreshUniformsCommon(uniforms, material);
  15029. refreshUniformsLambert(uniforms, material);
  15030. } else if (material.isMeshToonMaterial) {
  15031. refreshUniformsCommon(uniforms, material);
  15032. refreshUniformsToon(uniforms, material);
  15033. } else if (material.isMeshPhongMaterial) {
  15034. refreshUniformsCommon(uniforms, material);
  15035. refreshUniformsPhong(uniforms, material);
  15036. } else if (material.isMeshStandardMaterial) {
  15037. refreshUniformsCommon(uniforms, material);
  15038. if (material.isMeshPhysicalMaterial) {
  15039. refreshUniformsPhysical(uniforms, material, transmissionRenderTarget);
  15040. } else {
  15041. refreshUniformsStandard(uniforms, material);
  15042. }
  15043. } else if (material.isMeshMatcapMaterial) {
  15044. refreshUniformsCommon(uniforms, material);
  15045. refreshUniformsMatcap(uniforms, material);
  15046. } else if (material.isMeshDepthMaterial) {
  15047. refreshUniformsCommon(uniforms, material);
  15048. refreshUniformsDepth(uniforms, material);
  15049. } else if (material.isMeshDistanceMaterial) {
  15050. refreshUniformsCommon(uniforms, material);
  15051. refreshUniformsDistance(uniforms, material);
  15052. } else if (material.isMeshNormalMaterial) {
  15053. refreshUniformsCommon(uniforms, material);
  15054. refreshUniformsNormal(uniforms, material);
  15055. } else if (material.isLineBasicMaterial) {
  15056. refreshUniformsLine(uniforms, material);
  15057. if (material.isLineDashedMaterial) {
  15058. refreshUniformsDash(uniforms, material);
  15059. }
  15060. } else if (material.isPointsMaterial) {
  15061. refreshUniformsPoints(uniforms, material, pixelRatio, height);
  15062. } else if (material.isSpriteMaterial) {
  15063. refreshUniformsSprites(uniforms, material);
  15064. } else if (material.isShadowMaterial) {
  15065. uniforms.color.value.copy(material.color);
  15066. uniforms.opacity.value = material.opacity;
  15067. } else if (material.isShaderMaterial) {
  15068. material.uniformsNeedUpdate = false; // #15581
  15069. }
  15070. }
  15071. function refreshUniformsCommon(uniforms, material) {
  15072. uniforms.opacity.value = material.opacity;
  15073. if (material.color) {
  15074. uniforms.diffuse.value.copy(material.color);
  15075. }
  15076. if (material.emissive) {
  15077. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  15078. }
  15079. if (material.map) {
  15080. uniforms.map.value = material.map;
  15081. }
  15082. if (material.alphaMap) {
  15083. uniforms.alphaMap.value = material.alphaMap;
  15084. }
  15085. if (material.specularMap) {
  15086. uniforms.specularMap.value = material.specularMap;
  15087. }
  15088. if (material.alphaTest > 0) {
  15089. uniforms.alphaTest.value = material.alphaTest;
  15090. }
  15091. const envMap = properties.get(material).envMap;
  15092. if (envMap) {
  15093. uniforms.envMap.value = envMap;
  15094. uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1;
  15095. uniforms.reflectivity.value = material.reflectivity;
  15096. uniforms.ior.value = material.ior;
  15097. uniforms.refractionRatio.value = material.refractionRatio;
  15098. }
  15099. if (material.lightMap) {
  15100. uniforms.lightMap.value = material.lightMap;
  15101. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  15102. }
  15103. if (material.aoMap) {
  15104. uniforms.aoMap.value = material.aoMap;
  15105. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  15106. } // uv repeat and offset setting priorities
  15107. // 1. color map
  15108. // 2. specular map
  15109. // 3. displacementMap map
  15110. // 4. normal map
  15111. // 5. bump map
  15112. // 6. roughnessMap map
  15113. // 7. metalnessMap map
  15114. // 8. alphaMap map
  15115. // 9. emissiveMap map
  15116. // 10. clearcoat map
  15117. // 11. clearcoat normal map
  15118. // 12. clearcoat roughnessMap map
  15119. // 13. specular intensity map
  15120. // 14. specular tint map
  15121. // 15. transmission map
  15122. // 16. thickness map
  15123. let uvScaleMap;
  15124. if (material.map) {
  15125. uvScaleMap = material.map;
  15126. } else if (material.specularMap) {
  15127. uvScaleMap = material.specularMap;
  15128. } else if (material.displacementMap) {
  15129. uvScaleMap = material.displacementMap;
  15130. } else if (material.normalMap) {
  15131. uvScaleMap = material.normalMap;
  15132. } else if (material.bumpMap) {
  15133. uvScaleMap = material.bumpMap;
  15134. } else if (material.roughnessMap) {
  15135. uvScaleMap = material.roughnessMap;
  15136. } else if (material.metalnessMap) {
  15137. uvScaleMap = material.metalnessMap;
  15138. } else if (material.alphaMap) {
  15139. uvScaleMap = material.alphaMap;
  15140. } else if (material.emissiveMap) {
  15141. uvScaleMap = material.emissiveMap;
  15142. } else if (material.clearcoatMap) {
  15143. uvScaleMap = material.clearcoatMap;
  15144. } else if (material.clearcoatNormalMap) {
  15145. uvScaleMap = material.clearcoatNormalMap;
  15146. } else if (material.clearcoatRoughnessMap) {
  15147. uvScaleMap = material.clearcoatRoughnessMap;
  15148. } else if (material.specularIntensityMap) {
  15149. uvScaleMap = material.specularIntensityMap;
  15150. } else if (material.specularColorMap) {
  15151. uvScaleMap = material.specularColorMap;
  15152. } else if (material.transmissionMap) {
  15153. uvScaleMap = material.transmissionMap;
  15154. } else if (material.thicknessMap) {
  15155. uvScaleMap = material.thicknessMap;
  15156. } else if (material.sheenColorMap) {
  15157. uvScaleMap = material.sheenColorMap;
  15158. } else if (material.sheenRoughnessMap) {
  15159. uvScaleMap = material.sheenRoughnessMap;
  15160. }
  15161. if (uvScaleMap !== undefined) {
  15162. // backwards compatibility
  15163. if (uvScaleMap.isWebGLRenderTarget) {
  15164. uvScaleMap = uvScaleMap.texture;
  15165. }
  15166. if (uvScaleMap.matrixAutoUpdate === true) {
  15167. uvScaleMap.updateMatrix();
  15168. }
  15169. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  15170. } // uv repeat and offset setting priorities for uv2
  15171. // 1. ao map
  15172. // 2. light map
  15173. let uv2ScaleMap;
  15174. if (material.aoMap) {
  15175. uv2ScaleMap = material.aoMap;
  15176. } else if (material.lightMap) {
  15177. uv2ScaleMap = material.lightMap;
  15178. }
  15179. if (uv2ScaleMap !== undefined) {
  15180. // backwards compatibility
  15181. if (uv2ScaleMap.isWebGLRenderTarget) {
  15182. uv2ScaleMap = uv2ScaleMap.texture;
  15183. }
  15184. if (uv2ScaleMap.matrixAutoUpdate === true) {
  15185. uv2ScaleMap.updateMatrix();
  15186. }
  15187. uniforms.uv2Transform.value.copy(uv2ScaleMap.matrix);
  15188. }
  15189. }
  15190. function refreshUniformsLine(uniforms, material) {
  15191. uniforms.diffuse.value.copy(material.color);
  15192. uniforms.opacity.value = material.opacity;
  15193. }
  15194. function refreshUniformsDash(uniforms, material) {
  15195. uniforms.dashSize.value = material.dashSize;
  15196. uniforms.totalSize.value = material.dashSize + material.gapSize;
  15197. uniforms.scale.value = material.scale;
  15198. }
  15199. function refreshUniformsPoints(uniforms, material, pixelRatio, height) {
  15200. uniforms.diffuse.value.copy(material.color);
  15201. uniforms.opacity.value = material.opacity;
  15202. uniforms.size.value = material.size * pixelRatio;
  15203. uniforms.scale.value = height * 0.5;
  15204. if (material.map) {
  15205. uniforms.map.value = material.map;
  15206. }
  15207. if (material.alphaMap) {
  15208. uniforms.alphaMap.value = material.alphaMap;
  15209. }
  15210. if (material.alphaTest > 0) {
  15211. uniforms.alphaTest.value = material.alphaTest;
  15212. } // uv repeat and offset setting priorities
  15213. // 1. color map
  15214. // 2. alpha map
  15215. let uvScaleMap;
  15216. if (material.map) {
  15217. uvScaleMap = material.map;
  15218. } else if (material.alphaMap) {
  15219. uvScaleMap = material.alphaMap;
  15220. }
  15221. if (uvScaleMap !== undefined) {
  15222. if (uvScaleMap.matrixAutoUpdate === true) {
  15223. uvScaleMap.updateMatrix();
  15224. }
  15225. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  15226. }
  15227. }
  15228. function refreshUniformsSprites(uniforms, material) {
  15229. uniforms.diffuse.value.copy(material.color);
  15230. uniforms.opacity.value = material.opacity;
  15231. uniforms.rotation.value = material.rotation;
  15232. if (material.map) {
  15233. uniforms.map.value = material.map;
  15234. }
  15235. if (material.alphaMap) {
  15236. uniforms.alphaMap.value = material.alphaMap;
  15237. }
  15238. if (material.alphaTest > 0) {
  15239. uniforms.alphaTest.value = material.alphaTest;
  15240. } // uv repeat and offset setting priorities
  15241. // 1. color map
  15242. // 2. alpha map
  15243. let uvScaleMap;
  15244. if (material.map) {
  15245. uvScaleMap = material.map;
  15246. } else if (material.alphaMap) {
  15247. uvScaleMap = material.alphaMap;
  15248. }
  15249. if (uvScaleMap !== undefined) {
  15250. if (uvScaleMap.matrixAutoUpdate === true) {
  15251. uvScaleMap.updateMatrix();
  15252. }
  15253. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  15254. }
  15255. }
  15256. function refreshUniformsLambert(uniforms, material) {
  15257. if (material.emissiveMap) {
  15258. uniforms.emissiveMap.value = material.emissiveMap;
  15259. }
  15260. }
  15261. function refreshUniformsPhong(uniforms, material) {
  15262. uniforms.specular.value.copy(material.specular);
  15263. uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
  15264. if (material.emissiveMap) {
  15265. uniforms.emissiveMap.value = material.emissiveMap;
  15266. }
  15267. if (material.bumpMap) {
  15268. uniforms.bumpMap.value = material.bumpMap;
  15269. uniforms.bumpScale.value = material.bumpScale;
  15270. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15271. }
  15272. if (material.normalMap) {
  15273. uniforms.normalMap.value = material.normalMap;
  15274. uniforms.normalScale.value.copy(material.normalScale);
  15275. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15276. }
  15277. if (material.displacementMap) {
  15278. uniforms.displacementMap.value = material.displacementMap;
  15279. uniforms.displacementScale.value = material.displacementScale;
  15280. uniforms.displacementBias.value = material.displacementBias;
  15281. }
  15282. }
  15283. function refreshUniformsToon(uniforms, material) {
  15284. if (material.gradientMap) {
  15285. uniforms.gradientMap.value = material.gradientMap;
  15286. }
  15287. if (material.emissiveMap) {
  15288. uniforms.emissiveMap.value = material.emissiveMap;
  15289. }
  15290. if (material.bumpMap) {
  15291. uniforms.bumpMap.value = material.bumpMap;
  15292. uniforms.bumpScale.value = material.bumpScale;
  15293. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15294. }
  15295. if (material.normalMap) {
  15296. uniforms.normalMap.value = material.normalMap;
  15297. uniforms.normalScale.value.copy(material.normalScale);
  15298. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15299. }
  15300. if (material.displacementMap) {
  15301. uniforms.displacementMap.value = material.displacementMap;
  15302. uniforms.displacementScale.value = material.displacementScale;
  15303. uniforms.displacementBias.value = material.displacementBias;
  15304. }
  15305. }
  15306. function refreshUniformsStandard(uniforms, material) {
  15307. uniforms.roughness.value = material.roughness;
  15308. uniforms.metalness.value = material.metalness;
  15309. if (material.roughnessMap) {
  15310. uniforms.roughnessMap.value = material.roughnessMap;
  15311. }
  15312. if (material.metalnessMap) {
  15313. uniforms.metalnessMap.value = material.metalnessMap;
  15314. }
  15315. if (material.emissiveMap) {
  15316. uniforms.emissiveMap.value = material.emissiveMap;
  15317. }
  15318. if (material.bumpMap) {
  15319. uniforms.bumpMap.value = material.bumpMap;
  15320. uniforms.bumpScale.value = material.bumpScale;
  15321. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15322. }
  15323. if (material.normalMap) {
  15324. uniforms.normalMap.value = material.normalMap;
  15325. uniforms.normalScale.value.copy(material.normalScale);
  15326. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15327. }
  15328. if (material.displacementMap) {
  15329. uniforms.displacementMap.value = material.displacementMap;
  15330. uniforms.displacementScale.value = material.displacementScale;
  15331. uniforms.displacementBias.value = material.displacementBias;
  15332. }
  15333. const envMap = properties.get(material).envMap;
  15334. if (envMap) {
  15335. //uniforms.envMap.value = material.envMap; // part of uniforms common
  15336. uniforms.envMapIntensity.value = material.envMapIntensity;
  15337. }
  15338. }
  15339. function refreshUniformsPhysical(uniforms, material, transmissionRenderTarget) {
  15340. refreshUniformsStandard(uniforms, material);
  15341. uniforms.ior.value = material.ior; // also part of uniforms common
  15342. if (material.sheen > 0) {
  15343. uniforms.sheenColor.value.copy(material.sheenColor).multiplyScalar(material.sheen);
  15344. uniforms.sheenRoughness.value = material.sheenRoughness;
  15345. if (material.sheenColorMap) {
  15346. uniforms.sheenColorMap.value = material.sheenColorMap;
  15347. }
  15348. if (material.sheenRoughnessMap) {
  15349. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  15350. }
  15351. }
  15352. if (material.clearcoat > 0) {
  15353. uniforms.clearcoat.value = material.clearcoat;
  15354. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  15355. if (material.clearcoatMap) {
  15356. uniforms.clearcoatMap.value = material.clearcoatMap;
  15357. }
  15358. if (material.clearcoatRoughnessMap) {
  15359. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  15360. }
  15361. if (material.clearcoatNormalMap) {
  15362. uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
  15363. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  15364. if (material.side === BackSide) {
  15365. uniforms.clearcoatNormalScale.value.negate();
  15366. }
  15367. }
  15368. }
  15369. if (material.transmission > 0) {
  15370. uniforms.transmission.value = material.transmission;
  15371. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  15372. uniforms.transmissionSamplerSize.value.set(transmissionRenderTarget.width, transmissionRenderTarget.height);
  15373. if (material.transmissionMap) {
  15374. uniforms.transmissionMap.value = material.transmissionMap;
  15375. }
  15376. uniforms.thickness.value = material.thickness;
  15377. if (material.thicknessMap) {
  15378. uniforms.thicknessMap.value = material.thicknessMap;
  15379. }
  15380. uniforms.attenuationDistance.value = material.attenuationDistance;
  15381. uniforms.attenuationColor.value.copy(material.attenuationColor);
  15382. }
  15383. uniforms.specularIntensity.value = material.specularIntensity;
  15384. uniforms.specularColor.value.copy(material.specularColor);
  15385. if (material.specularIntensityMap) {
  15386. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  15387. }
  15388. if (material.specularColorMap) {
  15389. uniforms.specularColorMap.value = material.specularColorMap;
  15390. }
  15391. }
  15392. function refreshUniformsMatcap(uniforms, material) {
  15393. if (material.matcap) {
  15394. uniforms.matcap.value = material.matcap;
  15395. }
  15396. if (material.bumpMap) {
  15397. uniforms.bumpMap.value = material.bumpMap;
  15398. uniforms.bumpScale.value = material.bumpScale;
  15399. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15400. }
  15401. if (material.normalMap) {
  15402. uniforms.normalMap.value = material.normalMap;
  15403. uniforms.normalScale.value.copy(material.normalScale);
  15404. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15405. }
  15406. if (material.displacementMap) {
  15407. uniforms.displacementMap.value = material.displacementMap;
  15408. uniforms.displacementScale.value = material.displacementScale;
  15409. uniforms.displacementBias.value = material.displacementBias;
  15410. }
  15411. }
  15412. function refreshUniformsDepth(uniforms, material) {
  15413. if (material.displacementMap) {
  15414. uniforms.displacementMap.value = material.displacementMap;
  15415. uniforms.displacementScale.value = material.displacementScale;
  15416. uniforms.displacementBias.value = material.displacementBias;
  15417. }
  15418. }
  15419. function refreshUniformsDistance(uniforms, material) {
  15420. if (material.displacementMap) {
  15421. uniforms.displacementMap.value = material.displacementMap;
  15422. uniforms.displacementScale.value = material.displacementScale;
  15423. uniforms.displacementBias.value = material.displacementBias;
  15424. }
  15425. uniforms.referencePosition.value.copy(material.referencePosition);
  15426. uniforms.nearDistance.value = material.nearDistance;
  15427. uniforms.farDistance.value = material.farDistance;
  15428. }
  15429. function refreshUniformsNormal(uniforms, material) {
  15430. if (material.bumpMap) {
  15431. uniforms.bumpMap.value = material.bumpMap;
  15432. uniforms.bumpScale.value = material.bumpScale;
  15433. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15434. }
  15435. if (material.normalMap) {
  15436. uniforms.normalMap.value = material.normalMap;
  15437. uniforms.normalScale.value.copy(material.normalScale);
  15438. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15439. }
  15440. if (material.displacementMap) {
  15441. uniforms.displacementMap.value = material.displacementMap;
  15442. uniforms.displacementScale.value = material.displacementScale;
  15443. uniforms.displacementBias.value = material.displacementBias;
  15444. }
  15445. }
  15446. return {
  15447. refreshFogUniforms: refreshFogUniforms,
  15448. refreshMaterialUniforms: refreshMaterialUniforms
  15449. };
  15450. }
  15451. function createCanvasElement() {
  15452. const canvas = createElementNS('canvas');
  15453. canvas.style.display = 'block';
  15454. return canvas;
  15455. }
  15456. function WebGLRenderer(parameters = {}) {
  15457. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  15458. _context = parameters.context !== undefined ? parameters.context : null,
  15459. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  15460. _depth = parameters.depth !== undefined ? parameters.depth : true,
  15461. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  15462. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  15463. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  15464. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  15465. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  15466. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  15467. let currentRenderList = null;
  15468. let currentRenderState = null; // render() can be called from within a callback triggered by another render.
  15469. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  15470. const renderListStack = [];
  15471. const renderStateStack = []; // public properties
  15472. this.domElement = _canvas; // Debug configuration container
  15473. this.debug = {
  15474. /**
  15475. * Enables error checking and reporting when shader programs are being compiled
  15476. * @type {boolean}
  15477. */
  15478. checkShaderErrors: true
  15479. }; // clearing
  15480. this.autoClear = true;
  15481. this.autoClearColor = true;
  15482. this.autoClearDepth = true;
  15483. this.autoClearStencil = true; // scene graph
  15484. this.sortObjects = true; // user-defined clipping
  15485. this.clippingPlanes = [];
  15486. this.localClippingEnabled = false; // physically based shading
  15487. this.outputEncoding = LinearEncoding; // physical lights
  15488. this.physicallyCorrectLights = false; // tone mapping
  15489. this.toneMapping = NoToneMapping;
  15490. this.toneMappingExposure = 1.0; // internal properties
  15491. const _this = this;
  15492. let _isContextLost = false; // internal state cache
  15493. let _currentActiveCubeFace = 0;
  15494. let _currentActiveMipmapLevel = 0;
  15495. let _currentRenderTarget = null;
  15496. let _currentMaterialId = -1;
  15497. let _currentCamera = null;
  15498. const _currentViewport = new Vector4();
  15499. const _currentScissor = new Vector4();
  15500. let _currentScissorTest = null; //
  15501. let _width = _canvas.width;
  15502. let _height = _canvas.height;
  15503. let _pixelRatio = 1;
  15504. let _opaqueSort = null;
  15505. let _transparentSort = null;
  15506. const _viewport = new Vector4(0, 0, _width, _height);
  15507. const _scissor = new Vector4(0, 0, _width, _height);
  15508. let _scissorTest = false; //
  15509. const _currentDrawBuffers = []; // frustum
  15510. const _frustum = new Frustum(); // clipping
  15511. let _clippingEnabled = false;
  15512. let _localClippingEnabled = false; // transmission
  15513. let _transmissionRenderTarget = null; // camera matrices cache
  15514. const _projScreenMatrix = new Matrix4();
  15515. const _vector3 = new Vector3();
  15516. const _emptyScene = {
  15517. background: null,
  15518. fog: null,
  15519. environment: null,
  15520. overrideMaterial: null,
  15521. isScene: true
  15522. };
  15523. function getTargetPixelRatio() {
  15524. return _currentRenderTarget === null ? _pixelRatio : 1;
  15525. } // initialize
  15526. let _gl = _context;
  15527. function getContext(contextNames, contextAttributes) {
  15528. for (let i = 0; i < contextNames.length; i++) {
  15529. const contextName = contextNames[i];
  15530. const context = _canvas.getContext(contextName, contextAttributes);
  15531. if (context !== null) return context;
  15532. }
  15533. return null;
  15534. }
  15535. try {
  15536. const contextAttributes = {
  15537. alpha: _alpha,
  15538. depth: _depth,
  15539. stencil: _stencil,
  15540. antialias: _antialias,
  15541. premultipliedAlpha: _premultipliedAlpha,
  15542. preserveDrawingBuffer: _preserveDrawingBuffer,
  15543. powerPreference: _powerPreference,
  15544. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  15545. }; // OffscreenCanvas does not have setAttribute, see #22811
  15546. if ('setAttribute' in _canvas) _canvas.setAttribute('data-engine', `three.js r${REVISION}`); // event listeners must be registered before WebGL context is created, see #12753
  15547. _canvas.addEventListener('webglcontextlost', onContextLost, false);
  15548. _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
  15549. if (_gl === null) {
  15550. const contextNames = ['webgl2', 'webgl', 'experimental-webgl'];
  15551. if (_this.isWebGL1Renderer === true) {
  15552. contextNames.shift();
  15553. }
  15554. _gl = getContext(contextNames, contextAttributes);
  15555. if (_gl === null) {
  15556. if (getContext(contextNames)) {
  15557. throw new Error('Error creating WebGL context with your selected attributes.');
  15558. } else {
  15559. throw new Error('Error creating WebGL context.');
  15560. }
  15561. }
  15562. } // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  15563. if (_gl.getShaderPrecisionFormat === undefined) {
  15564. _gl.getShaderPrecisionFormat = function () {
  15565. return {
  15566. 'rangeMin': 1,
  15567. 'rangeMax': 1,
  15568. 'precision': 1
  15569. };
  15570. };
  15571. }
  15572. } catch (error) {
  15573. console.error('THREE.WebGLRenderer: ' + error.message);
  15574. throw error;
  15575. }
  15576. let extensions, capabilities, state, info;
  15577. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  15578. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  15579. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  15580. let utils, bindingStates;
  15581. function initGLContext() {
  15582. extensions = new WebGLExtensions(_gl);
  15583. capabilities = new WebGLCapabilities(_gl, extensions, parameters);
  15584. extensions.init(capabilities);
  15585. utils = new WebGLUtils(_gl, extensions, capabilities);
  15586. state = new WebGLState(_gl, extensions, capabilities);
  15587. _currentDrawBuffers[0] = _gl.BACK;
  15588. info = new WebGLInfo(_gl);
  15589. properties = new WebGLProperties();
  15590. textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
  15591. cubemaps = new WebGLCubeMaps(_this);
  15592. cubeuvmaps = new WebGLCubeUVMaps(_this);
  15593. attributes = new WebGLAttributes(_gl, capabilities);
  15594. bindingStates = new WebGLBindingStates(_gl, extensions, attributes, capabilities);
  15595. geometries = new WebGLGeometries(_gl, attributes, info, bindingStates);
  15596. objects = new WebGLObjects(_gl, geometries, attributes, info);
  15597. morphtargets = new WebGLMorphtargets(_gl, capabilities, textures);
  15598. clipping = new WebGLClipping(properties);
  15599. programCache = new WebGLPrograms(_this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping);
  15600. materials = new WebGLMaterials(properties);
  15601. renderLists = new WebGLRenderLists();
  15602. renderStates = new WebGLRenderStates(extensions, capabilities);
  15603. background = new WebGLBackground(_this, cubemaps, state, objects, _premultipliedAlpha);
  15604. shadowMap = new WebGLShadowMap(_this, objects, capabilities);
  15605. bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
  15606. indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
  15607. info.programs = programCache.programs;
  15608. _this.capabilities = capabilities;
  15609. _this.extensions = extensions;
  15610. _this.properties = properties;
  15611. _this.renderLists = renderLists;
  15612. _this.shadowMap = shadowMap;
  15613. _this.state = state;
  15614. _this.info = info;
  15615. }
  15616. initGLContext(); // xr
  15617. const xr = new WebXRManager(_this, _gl);
  15618. this.xr = xr; // API
  15619. this.getContext = function () {
  15620. return _gl;
  15621. };
  15622. this.getContextAttributes = function () {
  15623. return _gl.getContextAttributes();
  15624. };
  15625. this.forceContextLoss = function () {
  15626. const extension = extensions.get('WEBGL_lose_context');
  15627. if (extension) extension.loseContext();
  15628. };
  15629. this.forceContextRestore = function () {
  15630. const extension = extensions.get('WEBGL_lose_context');
  15631. if (extension) extension.restoreContext();
  15632. };
  15633. this.getPixelRatio = function () {
  15634. return _pixelRatio;
  15635. };
  15636. this.setPixelRatio = function (value) {
  15637. if (value === undefined) return;
  15638. _pixelRatio = value;
  15639. this.setSize(_width, _height, false);
  15640. };
  15641. this.getSize = function (target) {
  15642. return target.set(_width, _height);
  15643. };
  15644. this.setSize = function (width, height, updateStyle) {
  15645. if (xr.isPresenting) {
  15646. console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');
  15647. return;
  15648. }
  15649. _width = width;
  15650. _height = height;
  15651. _canvas.width = Math.floor(width * _pixelRatio);
  15652. _canvas.height = Math.floor(height * _pixelRatio);
  15653. if (updateStyle !== false) {
  15654. _canvas.style.width = width + 'px';
  15655. _canvas.style.height = height + 'px';
  15656. }
  15657. this.setViewport(0, 0, width, height);
  15658. };
  15659. this.getDrawingBufferSize = function (target) {
  15660. return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();
  15661. };
  15662. this.setDrawingBufferSize = function (width, height, pixelRatio) {
  15663. _width = width;
  15664. _height = height;
  15665. _pixelRatio = pixelRatio;
  15666. _canvas.width = Math.floor(width * pixelRatio);
  15667. _canvas.height = Math.floor(height * pixelRatio);
  15668. this.setViewport(0, 0, width, height);
  15669. };
  15670. this.getCurrentViewport = function (target) {
  15671. return target.copy(_currentViewport);
  15672. };
  15673. this.getViewport = function (target) {
  15674. return target.copy(_viewport);
  15675. };
  15676. this.setViewport = function (x, y, width, height) {
  15677. if (x.isVector4) {
  15678. _viewport.set(x.x, x.y, x.z, x.w);
  15679. } else {
  15680. _viewport.set(x, y, width, height);
  15681. }
  15682. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  15683. };
  15684. this.getScissor = function (target) {
  15685. return target.copy(_scissor);
  15686. };
  15687. this.setScissor = function (x, y, width, height) {
  15688. if (x.isVector4) {
  15689. _scissor.set(x.x, x.y, x.z, x.w);
  15690. } else {
  15691. _scissor.set(x, y, width, height);
  15692. }
  15693. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  15694. };
  15695. this.getScissorTest = function () {
  15696. return _scissorTest;
  15697. };
  15698. this.setScissorTest = function (boolean) {
  15699. state.setScissorTest(_scissorTest = boolean);
  15700. };
  15701. this.setOpaqueSort = function (method) {
  15702. _opaqueSort = method;
  15703. };
  15704. this.setTransparentSort = function (method) {
  15705. _transparentSort = method;
  15706. }; // Clearing
  15707. this.getClearColor = function (target) {
  15708. return target.copy(background.getClearColor());
  15709. };
  15710. this.setClearColor = function () {
  15711. background.setClearColor.apply(background, arguments);
  15712. };
  15713. this.getClearAlpha = function () {
  15714. return background.getClearAlpha();
  15715. };
  15716. this.setClearAlpha = function () {
  15717. background.setClearAlpha.apply(background, arguments);
  15718. };
  15719. this.clear = function (color, depth, stencil) {
  15720. let bits = 0;
  15721. if (color === undefined || color) bits |= _gl.COLOR_BUFFER_BIT;
  15722. if (depth === undefined || depth) bits |= _gl.DEPTH_BUFFER_BIT;
  15723. if (stencil === undefined || stencil) bits |= _gl.STENCIL_BUFFER_BIT;
  15724. _gl.clear(bits);
  15725. };
  15726. this.clearColor = function () {
  15727. this.clear(true, false, false);
  15728. };
  15729. this.clearDepth = function () {
  15730. this.clear(false, true, false);
  15731. };
  15732. this.clearStencil = function () {
  15733. this.clear(false, false, true);
  15734. }; //
  15735. this.dispose = function () {
  15736. _canvas.removeEventListener('webglcontextlost', onContextLost, false);
  15737. _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);
  15738. renderLists.dispose();
  15739. renderStates.dispose();
  15740. properties.dispose();
  15741. cubemaps.dispose();
  15742. cubeuvmaps.dispose();
  15743. objects.dispose();
  15744. bindingStates.dispose();
  15745. programCache.dispose();
  15746. xr.dispose();
  15747. xr.removeEventListener('sessionstart', onXRSessionStart);
  15748. xr.removeEventListener('sessionend', onXRSessionEnd);
  15749. if (_transmissionRenderTarget) {
  15750. _transmissionRenderTarget.dispose();
  15751. _transmissionRenderTarget = null;
  15752. }
  15753. animation.stop();
  15754. }; // Events
  15755. function onContextLost(event) {
  15756. event.preventDefault();
  15757. console.log('THREE.WebGLRenderer: Context Lost.');
  15758. _isContextLost = true;
  15759. }
  15760. function onContextRestore() {
  15761. console.log('THREE.WebGLRenderer: Context Restored.');
  15762. _isContextLost = false;
  15763. const infoAutoReset = info.autoReset;
  15764. const shadowMapEnabled = shadowMap.enabled;
  15765. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  15766. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  15767. const shadowMapType = shadowMap.type;
  15768. initGLContext();
  15769. info.autoReset = infoAutoReset;
  15770. shadowMap.enabled = shadowMapEnabled;
  15771. shadowMap.autoUpdate = shadowMapAutoUpdate;
  15772. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  15773. shadowMap.type = shadowMapType;
  15774. }
  15775. function onMaterialDispose(event) {
  15776. const material = event.target;
  15777. material.removeEventListener('dispose', onMaterialDispose);
  15778. deallocateMaterial(material);
  15779. } // Buffer deallocation
  15780. function deallocateMaterial(material) {
  15781. releaseMaterialProgramReferences(material);
  15782. properties.remove(material);
  15783. }
  15784. function releaseMaterialProgramReferences(material) {
  15785. const programs = properties.get(material).programs;
  15786. if (programs !== undefined) {
  15787. programs.forEach(function (program) {
  15788. programCache.releaseProgram(program);
  15789. });
  15790. if (material.isShaderMaterial) {
  15791. programCache.releaseShaderCache(material);
  15792. }
  15793. }
  15794. } // Buffer rendering
  15795. this.renderBufferDirect = function (camera, scene, geometry, material, object, group) {
  15796. if (scene === null) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  15797. const frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
  15798. const program = setProgram(camera, scene, geometry, material, object);
  15799. state.setMaterial(material, frontFaceCW); //
  15800. let index = geometry.index;
  15801. const position = geometry.attributes.position; //
  15802. if (index === null) {
  15803. if (position === undefined || position.count === 0) return;
  15804. } else if (index.count === 0) {
  15805. return;
  15806. } //
  15807. let rangeFactor = 1;
  15808. if (material.wireframe === true) {
  15809. index = geometries.getWireframeAttribute(geometry);
  15810. rangeFactor = 2;
  15811. }
  15812. bindingStates.setup(object, material, program, geometry, index);
  15813. let attribute;
  15814. let renderer = bufferRenderer;
  15815. if (index !== null) {
  15816. attribute = attributes.get(index);
  15817. renderer = indexedBufferRenderer;
  15818. renderer.setIndex(attribute);
  15819. } //
  15820. const dataCount = index !== null ? index.count : position.count;
  15821. const rangeStart = geometry.drawRange.start * rangeFactor;
  15822. const rangeCount = geometry.drawRange.count * rangeFactor;
  15823. const groupStart = group !== null ? group.start * rangeFactor : 0;
  15824. const groupCount = group !== null ? group.count * rangeFactor : Infinity;
  15825. const drawStart = Math.max(rangeStart, groupStart);
  15826. const drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1;
  15827. const drawCount = Math.max(0, drawEnd - drawStart + 1);
  15828. if (drawCount === 0) return; //
  15829. if (object.isMesh) {
  15830. if (material.wireframe === true) {
  15831. state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());
  15832. renderer.setMode(_gl.LINES);
  15833. } else {
  15834. renderer.setMode(_gl.TRIANGLES);
  15835. }
  15836. } else if (object.isLine) {
  15837. let lineWidth = material.linewidth;
  15838. if (lineWidth === undefined) lineWidth = 1; // Not using Line*Material
  15839. state.setLineWidth(lineWidth * getTargetPixelRatio());
  15840. if (object.isLineSegments) {
  15841. renderer.setMode(_gl.LINES);
  15842. } else if (object.isLineLoop) {
  15843. renderer.setMode(_gl.LINE_LOOP);
  15844. } else {
  15845. renderer.setMode(_gl.LINE_STRIP);
  15846. }
  15847. } else if (object.isPoints) {
  15848. renderer.setMode(_gl.POINTS);
  15849. } else if (object.isSprite) {
  15850. renderer.setMode(_gl.TRIANGLES);
  15851. }
  15852. if (object.isInstancedMesh) {
  15853. renderer.renderInstances(drawStart, drawCount, object.count);
  15854. } else if (geometry.isInstancedBufferGeometry) {
  15855. const instanceCount = Math.min(geometry.instanceCount, geometry._maxInstanceCount);
  15856. renderer.renderInstances(drawStart, drawCount, instanceCount);
  15857. } else {
  15858. renderer.render(drawStart, drawCount);
  15859. }
  15860. }; // Compile
  15861. this.compile = function (scene, camera) {
  15862. currentRenderState = renderStates.get(scene);
  15863. currentRenderState.init();
  15864. renderStateStack.push(currentRenderState);
  15865. scene.traverseVisible(function (object) {
  15866. if (object.isLight && object.layers.test(camera.layers)) {
  15867. currentRenderState.pushLight(object);
  15868. if (object.castShadow) {
  15869. currentRenderState.pushShadow(object);
  15870. }
  15871. }
  15872. });
  15873. currentRenderState.setupLights(_this.physicallyCorrectLights);
  15874. scene.traverse(function (object) {
  15875. const material = object.material;
  15876. if (material) {
  15877. if (Array.isArray(material)) {
  15878. for (let i = 0; i < material.length; i++) {
  15879. const material2 = material[i];
  15880. getProgram(material2, scene, object);
  15881. }
  15882. } else {
  15883. getProgram(material, scene, object);
  15884. }
  15885. }
  15886. });
  15887. renderStateStack.pop();
  15888. currentRenderState = null;
  15889. }; // Animation Loop
  15890. let onAnimationFrameCallback = null;
  15891. function onAnimationFrame(time) {
  15892. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  15893. }
  15894. function onXRSessionStart() {
  15895. animation.stop();
  15896. }
  15897. function onXRSessionEnd() {
  15898. animation.start();
  15899. }
  15900. const animation = new WebGLAnimation();
  15901. animation.setAnimationLoop(onAnimationFrame);
  15902. if (typeof window !== 'undefined') animation.setContext(window);
  15903. this.setAnimationLoop = function (callback) {
  15904. onAnimationFrameCallback = callback;
  15905. xr.setAnimationLoop(callback);
  15906. callback === null ? animation.stop() : animation.start();
  15907. };
  15908. xr.addEventListener('sessionstart', onXRSessionStart);
  15909. xr.addEventListener('sessionend', onXRSessionEnd); // Rendering
  15910. this.render = function (scene, camera) {
  15911. if (camera !== undefined && camera.isCamera !== true) {
  15912. console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');
  15913. return;
  15914. }
  15915. if (_isContextLost === true) return; // update scene graph
  15916. if (scene.autoUpdate === true) scene.updateMatrixWorld(); // update camera matrices and frustum
  15917. if (camera.parent === null) camera.updateMatrixWorld();
  15918. if (xr.enabled === true && xr.isPresenting === true) {
  15919. if (xr.cameraAutoUpdate === true) xr.updateCamera(camera);
  15920. camera = xr.getCamera(); // use XR camera for rendering
  15921. } //
  15922. if (scene.isScene === true) scene.onBeforeRender(_this, scene, camera, _currentRenderTarget);
  15923. currentRenderState = renderStates.get(scene, renderStateStack.length);
  15924. currentRenderState.init();
  15925. renderStateStack.push(currentRenderState);
  15926. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  15927. _frustum.setFromProjectionMatrix(_projScreenMatrix);
  15928. _localClippingEnabled = this.localClippingEnabled;
  15929. _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled, camera);
  15930. currentRenderList = renderLists.get(scene, renderListStack.length);
  15931. currentRenderList.init();
  15932. renderListStack.push(currentRenderList);
  15933. projectObject(scene, camera, 0, _this.sortObjects);
  15934. currentRenderList.finish();
  15935. if (_this.sortObjects === true) {
  15936. currentRenderList.sort(_opaqueSort, _transparentSort);
  15937. } //
  15938. if (_clippingEnabled === true) clipping.beginShadows();
  15939. const shadowsArray = currentRenderState.state.shadowsArray;
  15940. shadowMap.render(shadowsArray, scene, camera);
  15941. if (_clippingEnabled === true) clipping.endShadows(); //
  15942. if (this.info.autoReset === true) this.info.reset(); //
  15943. background.render(currentRenderList, scene); // render scene
  15944. currentRenderState.setupLights(_this.physicallyCorrectLights);
  15945. if (camera.isArrayCamera) {
  15946. const cameras = camera.cameras;
  15947. for (let i = 0, l = cameras.length; i < l; i++) {
  15948. const camera2 = cameras[i];
  15949. renderScene(currentRenderList, scene, camera2, camera2.viewport);
  15950. }
  15951. } else {
  15952. renderScene(currentRenderList, scene, camera);
  15953. } //
  15954. if (_currentRenderTarget !== null) {
  15955. // resolve multisample renderbuffers to a single-sample texture if necessary
  15956. textures.updateMultisampleRenderTarget(_currentRenderTarget); // Generate mipmap if we're using any kind of mipmap filtering
  15957. textures.updateRenderTargetMipmap(_currentRenderTarget);
  15958. } //
  15959. if (scene.isScene === true) scene.onAfterRender(_this, scene, camera); // Ensure depth buffer writing is enabled so it can be cleared on next render
  15960. state.buffers.depth.setTest(true);
  15961. state.buffers.depth.setMask(true);
  15962. state.buffers.color.setMask(true);
  15963. state.setPolygonOffset(false); // _gl.finish();
  15964. bindingStates.resetDefaultState();
  15965. _currentMaterialId = -1;
  15966. _currentCamera = null;
  15967. renderStateStack.pop();
  15968. if (renderStateStack.length > 0) {
  15969. currentRenderState = renderStateStack[renderStateStack.length - 1];
  15970. } else {
  15971. currentRenderState = null;
  15972. }
  15973. renderListStack.pop();
  15974. if (renderListStack.length > 0) {
  15975. currentRenderList = renderListStack[renderListStack.length - 1];
  15976. } else {
  15977. currentRenderList = null;
  15978. }
  15979. };
  15980. function projectObject(object, camera, groupOrder, sortObjects) {
  15981. if (object.visible === false) return;
  15982. const visible = object.layers.test(camera.layers);
  15983. if (visible) {
  15984. if (object.isGroup) {
  15985. groupOrder = object.renderOrder;
  15986. } else if (object.isLOD) {
  15987. if (object.autoUpdate === true) object.update(camera);
  15988. } else if (object.isLight) {
  15989. currentRenderState.pushLight(object);
  15990. if (object.castShadow) {
  15991. currentRenderState.pushShadow(object);
  15992. }
  15993. } else if (object.isSprite) {
  15994. if (!object.frustumCulled || _frustum.intersectsSprite(object)) {
  15995. if (sortObjects) {
  15996. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  15997. }
  15998. const geometry = objects.update(object);
  15999. const material = object.material;
  16000. if (material.visible) {
  16001. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  16002. }
  16003. }
  16004. } else if (object.isMesh || object.isLine || object.isPoints) {
  16005. if (object.isSkinnedMesh) {
  16006. // update skeleton only once in a frame
  16007. if (object.skeleton.frame !== info.render.frame) {
  16008. object.skeleton.update();
  16009. object.skeleton.frame = info.render.frame;
  16010. }
  16011. }
  16012. if (!object.frustumCulled || _frustum.intersectsObject(object)) {
  16013. if (sortObjects) {
  16014. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  16015. }
  16016. const geometry = objects.update(object);
  16017. const material = object.material;
  16018. if (Array.isArray(material)) {
  16019. const groups = geometry.groups;
  16020. for (let i = 0, l = groups.length; i < l; i++) {
  16021. const group = groups[i];
  16022. const groupMaterial = material[group.materialIndex];
  16023. if (groupMaterial && groupMaterial.visible) {
  16024. currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector3.z, group);
  16025. }
  16026. }
  16027. } else if (material.visible) {
  16028. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  16029. }
  16030. }
  16031. }
  16032. }
  16033. const children = object.children;
  16034. for (let i = 0, l = children.length; i < l; i++) {
  16035. projectObject(children[i], camera, groupOrder, sortObjects);
  16036. }
  16037. }
  16038. function renderScene(currentRenderList, scene, camera, viewport) {
  16039. const opaqueObjects = currentRenderList.opaque;
  16040. const transmissiveObjects = currentRenderList.transmissive;
  16041. const transparentObjects = currentRenderList.transparent;
  16042. currentRenderState.setupLightsView(camera);
  16043. if (transmissiveObjects.length > 0) renderTransmissionPass(opaqueObjects, scene, camera);
  16044. if (viewport) state.viewport(_currentViewport.copy(viewport));
  16045. if (opaqueObjects.length > 0) renderObjects(opaqueObjects, scene, camera);
  16046. if (transmissiveObjects.length > 0) renderObjects(transmissiveObjects, scene, camera);
  16047. if (transparentObjects.length > 0) renderObjects(transparentObjects, scene, camera);
  16048. }
  16049. function renderTransmissionPass(opaqueObjects, scene, camera) {
  16050. if (_transmissionRenderTarget === null) {
  16051. const needsAntialias = _antialias === true && capabilities.isWebGL2 === true;
  16052. const renderTargetType = needsAntialias ? WebGLMultisampleRenderTarget : WebGLRenderTarget;
  16053. _transmissionRenderTarget = new renderTargetType(1024, 1024, {
  16054. generateMipmaps: true,
  16055. type: utils.convert(HalfFloatType) !== null ? HalfFloatType : UnsignedByteType,
  16056. minFilter: LinearMipmapLinearFilter,
  16057. magFilter: NearestFilter,
  16058. wrapS: ClampToEdgeWrapping,
  16059. wrapT: ClampToEdgeWrapping,
  16060. useRenderToTexture: extensions.has('WEBGL_multisampled_render_to_texture')
  16061. });
  16062. }
  16063. const currentRenderTarget = _this.getRenderTarget();
  16064. _this.setRenderTarget(_transmissionRenderTarget);
  16065. _this.clear(); // Turn off the features which can affect the frag color for opaque objects pass.
  16066. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  16067. const currentToneMapping = _this.toneMapping;
  16068. _this.toneMapping = NoToneMapping;
  16069. renderObjects(opaqueObjects, scene, camera);
  16070. _this.toneMapping = currentToneMapping;
  16071. textures.updateMultisampleRenderTarget(_transmissionRenderTarget);
  16072. textures.updateRenderTargetMipmap(_transmissionRenderTarget);
  16073. _this.setRenderTarget(currentRenderTarget);
  16074. }
  16075. function renderObjects(renderList, scene, camera) {
  16076. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  16077. for (let i = 0, l = renderList.length; i < l; i++) {
  16078. const renderItem = renderList[i];
  16079. const object = renderItem.object;
  16080. const geometry = renderItem.geometry;
  16081. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  16082. const group = renderItem.group;
  16083. if (object.layers.test(camera.layers)) {
  16084. renderObject(object, scene, camera, geometry, material, group);
  16085. }
  16086. }
  16087. }
  16088. function renderObject(object, scene, camera, geometry, material, group) {
  16089. object.onBeforeRender(_this, scene, camera, geometry, material, group);
  16090. object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
  16091. object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
  16092. material.onBeforeRender(_this, scene, camera, geometry, object, group);
  16093. if (material.transparent === true && material.side === DoubleSide) {
  16094. material.side = BackSide;
  16095. material.needsUpdate = true;
  16096. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  16097. material.side = FrontSide;
  16098. material.needsUpdate = true;
  16099. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  16100. material.side = DoubleSide;
  16101. } else {
  16102. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  16103. }
  16104. object.onAfterRender(_this, scene, camera, geometry, material, group);
  16105. }
  16106. function getProgram(material, scene, object) {
  16107. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  16108. const materialProperties = properties.get(material);
  16109. const lights = currentRenderState.state.lights;
  16110. const shadowsArray = currentRenderState.state.shadowsArray;
  16111. const lightsStateVersion = lights.state.version;
  16112. const parameters = programCache.getParameters(material, lights.state, shadowsArray, scene, object);
  16113. const programCacheKey = programCache.getProgramCacheKey(parameters);
  16114. 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
  16115. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  16116. materialProperties.fog = scene.fog;
  16117. materialProperties.envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || materialProperties.environment);
  16118. if (programs === undefined) {
  16119. // new material
  16120. material.addEventListener('dispose', onMaterialDispose);
  16121. programs = new Map();
  16122. materialProperties.programs = programs;
  16123. }
  16124. let program = programs.get(programCacheKey);
  16125. if (program !== undefined) {
  16126. // early out if program and light state is identical
  16127. if (materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion) {
  16128. updateCommonMaterialProperties(material, parameters);
  16129. return program;
  16130. }
  16131. } else {
  16132. parameters.uniforms = programCache.getUniforms(material);
  16133. material.onBuild(object, parameters, _this);
  16134. material.onBeforeCompile(parameters, _this);
  16135. program = programCache.acquireProgram(parameters, programCacheKey);
  16136. programs.set(programCacheKey, program);
  16137. materialProperties.uniforms = parameters.uniforms;
  16138. }
  16139. const uniforms = materialProperties.uniforms;
  16140. if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
  16141. uniforms.clippingPlanes = clipping.uniform;
  16142. }
  16143. updateCommonMaterialProperties(material, parameters); // store the light setup it was created for
  16144. materialProperties.needsLights = materialNeedsLights(material);
  16145. materialProperties.lightsStateVersion = lightsStateVersion;
  16146. if (materialProperties.needsLights) {
  16147. // wire up the material to this renderer's lighting state
  16148. uniforms.ambientLightColor.value = lights.state.ambient;
  16149. uniforms.lightProbe.value = lights.state.probe;
  16150. uniforms.directionalLights.value = lights.state.directional;
  16151. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  16152. uniforms.spotLights.value = lights.state.spot;
  16153. uniforms.spotLightShadows.value = lights.state.spotShadow;
  16154. uniforms.rectAreaLights.value = lights.state.rectArea;
  16155. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  16156. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  16157. uniforms.pointLights.value = lights.state.point;
  16158. uniforms.pointLightShadows.value = lights.state.pointShadow;
  16159. uniforms.hemisphereLights.value = lights.state.hemi;
  16160. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  16161. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  16162. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  16163. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  16164. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  16165. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniforms
  16166. }
  16167. const progUniforms = program.getUniforms();
  16168. const uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);
  16169. materialProperties.currentProgram = program;
  16170. materialProperties.uniformsList = uniformsList;
  16171. return program;
  16172. }
  16173. function updateCommonMaterialProperties(material, parameters) {
  16174. const materialProperties = properties.get(material);
  16175. materialProperties.outputEncoding = parameters.outputEncoding;
  16176. materialProperties.instancing = parameters.instancing;
  16177. materialProperties.skinning = parameters.skinning;
  16178. materialProperties.morphTargets = parameters.morphTargets;
  16179. materialProperties.morphNormals = parameters.morphNormals;
  16180. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  16181. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  16182. materialProperties.numIntersection = parameters.numClipIntersection;
  16183. materialProperties.vertexAlphas = parameters.vertexAlphas;
  16184. materialProperties.vertexTangents = parameters.vertexTangents;
  16185. materialProperties.toneMapping = parameters.toneMapping;
  16186. }
  16187. function setProgram(camera, scene, geometry, material, object) {
  16188. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  16189. textures.resetTextureUnits();
  16190. const fog = scene.fog;
  16191. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  16192. const encoding = _currentRenderTarget === null ? _this.outputEncoding : _currentRenderTarget.texture.encoding;
  16193. const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment);
  16194. const vertexAlphas = material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  16195. const vertexTangents = !!material.normalMap && !!geometry.attributes.tangent;
  16196. const morphTargets = !!geometry.morphAttributes.position;
  16197. const morphNormals = !!geometry.morphAttributes.normal;
  16198. const morphTargetsCount = !!geometry.morphAttributes.position ? geometry.morphAttributes.position.length : 0;
  16199. const toneMapping = material.toneMapped ? _this.toneMapping : NoToneMapping;
  16200. const materialProperties = properties.get(material);
  16201. const lights = currentRenderState.state.lights;
  16202. if (_clippingEnabled === true) {
  16203. if (_localClippingEnabled === true || camera !== _currentCamera) {
  16204. const useCache = camera === _currentCamera && material.id === _currentMaterialId; // we might want to call this function with some ClippingGroup
  16205. // object instead of the material, once it becomes feasible
  16206. // (#8465, #8379)
  16207. clipping.setState(material, camera, useCache);
  16208. }
  16209. } //
  16210. let needsProgramChange = false;
  16211. if (material.version === materialProperties.__version) {
  16212. if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) {
  16213. needsProgramChange = true;
  16214. } else if (materialProperties.outputEncoding !== encoding) {
  16215. needsProgramChange = true;
  16216. } else if (object.isInstancedMesh && materialProperties.instancing === false) {
  16217. needsProgramChange = true;
  16218. } else if (!object.isInstancedMesh && materialProperties.instancing === true) {
  16219. needsProgramChange = true;
  16220. } else if (object.isSkinnedMesh && materialProperties.skinning === false) {
  16221. needsProgramChange = true;
  16222. } else if (!object.isSkinnedMesh && materialProperties.skinning === true) {
  16223. needsProgramChange = true;
  16224. } else if (materialProperties.envMap !== envMap) {
  16225. needsProgramChange = true;
  16226. } else if (material.fog && materialProperties.fog !== fog) {
  16227. needsProgramChange = true;
  16228. } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== clipping.numPlanes || materialProperties.numIntersection !== clipping.numIntersection)) {
  16229. needsProgramChange = true;
  16230. } else if (materialProperties.vertexAlphas !== vertexAlphas) {
  16231. needsProgramChange = true;
  16232. } else if (materialProperties.vertexTangents !== vertexTangents) {
  16233. needsProgramChange = true;
  16234. } else if (materialProperties.morphTargets !== morphTargets) {
  16235. needsProgramChange = true;
  16236. } else if (materialProperties.morphNormals !== morphNormals) {
  16237. needsProgramChange = true;
  16238. } else if (materialProperties.toneMapping !== toneMapping) {
  16239. needsProgramChange = true;
  16240. } else if (capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount) {
  16241. needsProgramChange = true;
  16242. }
  16243. } else {
  16244. needsProgramChange = true;
  16245. materialProperties.__version = material.version;
  16246. } //
  16247. let program = materialProperties.currentProgram;
  16248. if (needsProgramChange === true) {
  16249. program = getProgram(material, scene, object);
  16250. }
  16251. let refreshProgram = false;
  16252. let refreshMaterial = false;
  16253. let refreshLights = false;
  16254. const p_uniforms = program.getUniforms(),
  16255. m_uniforms = materialProperties.uniforms;
  16256. if (state.useProgram(program.program)) {
  16257. refreshProgram = true;
  16258. refreshMaterial = true;
  16259. refreshLights = true;
  16260. }
  16261. if (material.id !== _currentMaterialId) {
  16262. _currentMaterialId = material.id;
  16263. refreshMaterial = true;
  16264. }
  16265. if (refreshProgram || _currentCamera !== camera) {
  16266. p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);
  16267. if (capabilities.logarithmicDepthBuffer) {
  16268. p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  16269. }
  16270. if (_currentCamera !== camera) {
  16271. _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update
  16272. // now, in case this material supports lights - or later, when
  16273. // the next material that does gets activated:
  16274. refreshMaterial = true; // set to true on material change
  16275. refreshLights = true; // remains set until update done
  16276. } // load material specific uniforms
  16277. // (shader material also gets them for the sake of genericity)
  16278. if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshStandardMaterial || material.envMap) {
  16279. const uCamPos = p_uniforms.map.cameraPosition;
  16280. if (uCamPos !== undefined) {
  16281. uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));
  16282. }
  16283. }
  16284. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) {
  16285. p_uniforms.setValue(_gl, 'isOrthographic', camera.isOrthographicCamera === true);
  16286. }
  16287. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.isShadowMaterial || object.isSkinnedMesh) {
  16288. p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);
  16289. }
  16290. } // skinning and morph target uniforms must be set even if material didn't change
  16291. // auto-setting of texture unit for bone and morph texture must go before other textures
  16292. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  16293. if (object.isSkinnedMesh) {
  16294. p_uniforms.setOptional(_gl, object, 'bindMatrix');
  16295. p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');
  16296. const skeleton = object.skeleton;
  16297. if (skeleton) {
  16298. if (capabilities.floatVertexTextures) {
  16299. if (skeleton.boneTexture === null) skeleton.computeBoneTexture();
  16300. p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);
  16301. p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);
  16302. } else {
  16303. p_uniforms.setOptional(_gl, skeleton, 'boneMatrices');
  16304. }
  16305. }
  16306. }
  16307. if (!!geometry && (geometry.morphAttributes.position !== undefined || geometry.morphAttributes.normal !== undefined)) {
  16308. morphtargets.update(object, geometry, material, program);
  16309. }
  16310. if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
  16311. materialProperties.receiveShadow = object.receiveShadow;
  16312. p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow);
  16313. }
  16314. if (refreshMaterial) {
  16315. p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
  16316. if (materialProperties.needsLights) {
  16317. // the current material requires lighting info
  16318. // note: all lighting uniforms are always set correctly
  16319. // they simply reference the renderer's state for their
  16320. // values
  16321. //
  16322. // use the current material's .needsUpdate flags to set
  16323. // the GL state when required
  16324. markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
  16325. } // refresh uniforms common to several materials
  16326. if (fog && material.fog) {
  16327. materials.refreshFogUniforms(m_uniforms, fog);
  16328. }
  16329. materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget);
  16330. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  16331. }
  16332. if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
  16333. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  16334. material.uniformsNeedUpdate = false;
  16335. }
  16336. if (material.isSpriteMaterial) {
  16337. p_uniforms.setValue(_gl, 'center', object.center);
  16338. } // common matrices
  16339. p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
  16340. p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
  16341. p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld);
  16342. return program;
  16343. } // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  16344. function markUniformsLightsNeedsUpdate(uniforms, value) {
  16345. uniforms.ambientLightColor.needsUpdate = value;
  16346. uniforms.lightProbe.needsUpdate = value;
  16347. uniforms.directionalLights.needsUpdate = value;
  16348. uniforms.directionalLightShadows.needsUpdate = value;
  16349. uniforms.pointLights.needsUpdate = value;
  16350. uniforms.pointLightShadows.needsUpdate = value;
  16351. uniforms.spotLights.needsUpdate = value;
  16352. uniforms.spotLightShadows.needsUpdate = value;
  16353. uniforms.rectAreaLights.needsUpdate = value;
  16354. uniforms.hemisphereLights.needsUpdate = value;
  16355. }
  16356. function materialNeedsLights(material) {
  16357. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
  16358. }
  16359. this.getActiveCubeFace = function () {
  16360. return _currentActiveCubeFace;
  16361. };
  16362. this.getActiveMipmapLevel = function () {
  16363. return _currentActiveMipmapLevel;
  16364. };
  16365. this.getRenderTarget = function () {
  16366. return _currentRenderTarget;
  16367. };
  16368. this.setRenderTargetTextures = function (renderTarget, colorTexture, depthTexture) {
  16369. properties.get(renderTarget.texture).__webglTexture = colorTexture;
  16370. properties.get(renderTarget.depthTexture).__webglTexture = depthTexture;
  16371. const renderTargetProperties = properties.get(renderTarget);
  16372. renderTargetProperties.__hasExternalTextures = true;
  16373. if (renderTargetProperties.__hasExternalTextures) {
  16374. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  16375. if (!renderTargetProperties.__autoAllocateDepthBuffer) {
  16376. // The multisample_render_to_texture extension doesn't work properly if there
  16377. // are midframe flushes and an external depth buffer. Disable use of the extension.
  16378. if (renderTarget.useRenderToTexture) {
  16379. console.warn('render-to-texture extension was disabled because an external texture was provided');
  16380. renderTarget.useRenderToTexture = false;
  16381. renderTarget.useRenderbuffer = true;
  16382. }
  16383. }
  16384. }
  16385. };
  16386. this.setRenderTargetFramebuffer = function (renderTarget, defaultFramebuffer) {
  16387. const renderTargetProperties = properties.get(renderTarget);
  16388. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  16389. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  16390. };
  16391. this.setRenderTarget = function (renderTarget, activeCubeFace = 0, activeMipmapLevel = 0) {
  16392. _currentRenderTarget = renderTarget;
  16393. _currentActiveCubeFace = activeCubeFace;
  16394. _currentActiveMipmapLevel = activeMipmapLevel;
  16395. let useDefaultFramebuffer = true;
  16396. if (renderTarget) {
  16397. const renderTargetProperties = properties.get(renderTarget);
  16398. if (renderTargetProperties.__useDefaultFramebuffer !== undefined) {
  16399. // We need to make sure to rebind the framebuffer.
  16400. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  16401. useDefaultFramebuffer = false;
  16402. } else if (renderTargetProperties.__webglFramebuffer === undefined) {
  16403. textures.setupRenderTarget(renderTarget);
  16404. } else if (renderTargetProperties.__hasExternalTextures) {
  16405. // Color and depth texture must be rebound in order for the swapchain to update.
  16406. textures.rebindTextures(renderTarget, properties.get(renderTarget.texture).__webglTexture, properties.get(renderTarget.depthTexture).__webglTexture);
  16407. }
  16408. }
  16409. let framebuffer = null;
  16410. let isCube = false;
  16411. let isRenderTarget3D = false;
  16412. if (renderTarget) {
  16413. const texture = renderTarget.texture;
  16414. if (texture.isDataTexture3D || texture.isDataTexture2DArray) {
  16415. isRenderTarget3D = true;
  16416. }
  16417. const __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
  16418. if (renderTarget.isWebGLCubeRenderTarget) {
  16419. framebuffer = __webglFramebuffer[activeCubeFace];
  16420. isCube = true;
  16421. } else if (renderTarget.useRenderbuffer) {
  16422. framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
  16423. } else {
  16424. framebuffer = __webglFramebuffer;
  16425. }
  16426. _currentViewport.copy(renderTarget.viewport);
  16427. _currentScissor.copy(renderTarget.scissor);
  16428. _currentScissorTest = renderTarget.scissorTest;
  16429. } else {
  16430. _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();
  16431. _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
  16432. _currentScissorTest = _scissorTest;
  16433. }
  16434. const framebufferBound = state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  16435. if (framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer) {
  16436. let needsUpdate = false;
  16437. if (renderTarget) {
  16438. if (renderTarget.isWebGLMultipleRenderTargets) {
  16439. const textures = renderTarget.texture;
  16440. if (_currentDrawBuffers.length !== textures.length || _currentDrawBuffers[0] !== _gl.COLOR_ATTACHMENT0) {
  16441. for (let i = 0, il = textures.length; i < il; i++) {
  16442. _currentDrawBuffers[i] = _gl.COLOR_ATTACHMENT0 + i;
  16443. }
  16444. _currentDrawBuffers.length = textures.length;
  16445. needsUpdate = true;
  16446. }
  16447. } else {
  16448. if (_currentDrawBuffers.length !== 1 || _currentDrawBuffers[0] !== _gl.COLOR_ATTACHMENT0) {
  16449. _currentDrawBuffers[0] = _gl.COLOR_ATTACHMENT0;
  16450. _currentDrawBuffers.length = 1;
  16451. needsUpdate = true;
  16452. }
  16453. }
  16454. } else {
  16455. if (_currentDrawBuffers.length !== 1 || _currentDrawBuffers[0] !== _gl.BACK) {
  16456. _currentDrawBuffers[0] = _gl.BACK;
  16457. _currentDrawBuffers.length = 1;
  16458. needsUpdate = true;
  16459. }
  16460. }
  16461. if (needsUpdate) {
  16462. if (capabilities.isWebGL2) {
  16463. _gl.drawBuffers(_currentDrawBuffers);
  16464. } else {
  16465. extensions.get('WEBGL_draw_buffers').drawBuffersWEBGL(_currentDrawBuffers);
  16466. }
  16467. }
  16468. }
  16469. state.viewport(_currentViewport);
  16470. state.scissor(_currentScissor);
  16471. state.setScissorTest(_currentScissorTest);
  16472. if (isCube) {
  16473. const textureProperties = properties.get(renderTarget.texture);
  16474. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel);
  16475. } else if (isRenderTarget3D) {
  16476. const textureProperties = properties.get(renderTarget.texture);
  16477. const layer = activeCubeFace || 0;
  16478. _gl.framebufferTextureLayer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer);
  16479. }
  16480. _currentMaterialId = -1; // reset current material to ensure correct uniform bindings
  16481. };
  16482. this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
  16483. if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
  16484. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
  16485. return;
  16486. }
  16487. let framebuffer = properties.get(renderTarget).__webglFramebuffer;
  16488. if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) {
  16489. framebuffer = framebuffer[activeCubeFaceIndex];
  16490. }
  16491. if (framebuffer) {
  16492. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  16493. try {
  16494. const texture = renderTarget.texture;
  16495. const textureFormat = texture.format;
  16496. const textureType = texture.type;
  16497. if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_FORMAT)) {
  16498. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
  16499. return;
  16500. }
  16501. const halfFloatSupportedByExt = textureType === HalfFloatType && (extensions.has('EXT_color_buffer_half_float') || capabilities.isWebGL2 && extensions.has('EXT_color_buffer_float'));
  16502. if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_TYPE) && // Edge and Chrome Mac < 52 (#9513)
  16503. !(textureType === FloatType && (capabilities.isWebGL2 || extensions.has('OES_texture_float') || extensions.has('WEBGL_color_buffer_float'))) && // Chrome Mac >= 52 and Firefox
  16504. !halfFloatSupportedByExt) {
  16505. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
  16506. return;
  16507. }
  16508. if (_gl.checkFramebufferStatus(_gl.FRAMEBUFFER) === _gl.FRAMEBUFFER_COMPLETE) {
  16509. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  16510. if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {
  16511. _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
  16512. }
  16513. } else {
  16514. console.error('THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.');
  16515. }
  16516. } finally {
  16517. // restore framebuffer of current render target if necessary
  16518. const framebuffer = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null;
  16519. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  16520. }
  16521. }
  16522. };
  16523. this.copyFramebufferToTexture = function (position, texture, level = 0) {
  16524. if (texture.isFramebufferTexture !== true) {
  16525. console.error('THREE.WebGLRenderer: copyFramebufferToTexture() can only be used with FramebufferTexture.');
  16526. return;
  16527. }
  16528. const levelScale = Math.pow(2, -level);
  16529. const width = Math.floor(texture.image.width * levelScale);
  16530. const height = Math.floor(texture.image.height * levelScale);
  16531. textures.setTexture2D(texture, 0);
  16532. _gl.copyTexSubImage2D(_gl.TEXTURE_2D, level, 0, 0, position.x, position.y, width, height);
  16533. state.unbindTexture();
  16534. };
  16535. this.copyTextureToTexture = function (position, srcTexture, dstTexture, level = 0) {
  16536. const width = srcTexture.image.width;
  16537. const height = srcTexture.image.height;
  16538. const glFormat = utils.convert(dstTexture.format);
  16539. const glType = utils.convert(dstTexture.type);
  16540. textures.setTexture2D(dstTexture, 0); // As another texture upload may have changed pixelStorei
  16541. // parameters, make sure they are correct for the dstTexture
  16542. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  16543. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  16544. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  16545. if (srcTexture.isDataTexture) {
  16546. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
  16547. } else {
  16548. if (srcTexture.isCompressedTexture) {
  16549. _gl.compressedTexSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, srcTexture.mipmaps[0].width, srcTexture.mipmaps[0].height, glFormat, srcTexture.mipmaps[0].data);
  16550. } else {
  16551. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image);
  16552. }
  16553. } // Generate mipmaps only when copying level 0
  16554. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(_gl.TEXTURE_2D);
  16555. state.unbindTexture();
  16556. };
  16557. this.copyTextureToTexture3D = function (sourceBox, position, srcTexture, dstTexture, level = 0) {
  16558. if (_this.isWebGL1Renderer) {
  16559. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.');
  16560. return;
  16561. }
  16562. const width = sourceBox.max.x - sourceBox.min.x + 1;
  16563. const height = sourceBox.max.y - sourceBox.min.y + 1;
  16564. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  16565. const glFormat = utils.convert(dstTexture.format);
  16566. const glType = utils.convert(dstTexture.type);
  16567. let glTarget;
  16568. if (dstTexture.isDataTexture3D) {
  16569. textures.setTexture3D(dstTexture, 0);
  16570. glTarget = _gl.TEXTURE_3D;
  16571. } else if (dstTexture.isDataTexture2DArray) {
  16572. textures.setTexture2DArray(dstTexture, 0);
  16573. glTarget = _gl.TEXTURE_2D_ARRAY;
  16574. } else {
  16575. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.');
  16576. return;
  16577. }
  16578. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  16579. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  16580. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  16581. const unpackRowLen = _gl.getParameter(_gl.UNPACK_ROW_LENGTH);
  16582. const unpackImageHeight = _gl.getParameter(_gl.UNPACK_IMAGE_HEIGHT);
  16583. const unpackSkipPixels = _gl.getParameter(_gl.UNPACK_SKIP_PIXELS);
  16584. const unpackSkipRows = _gl.getParameter(_gl.UNPACK_SKIP_ROWS);
  16585. const unpackSkipImages = _gl.getParameter(_gl.UNPACK_SKIP_IMAGES);
  16586. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[0] : srcTexture.image;
  16587. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, image.width);
  16588. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, image.height);
  16589. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, sourceBox.min.x);
  16590. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, sourceBox.min.y);
  16591. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, sourceBox.min.z);
  16592. if (srcTexture.isDataTexture || srcTexture.isDataTexture3D) {
  16593. _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data);
  16594. } else {
  16595. if (srcTexture.isCompressedTexture) {
  16596. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.');
  16597. _gl.compressedTexSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data);
  16598. } else {
  16599. _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image);
  16600. }
  16601. }
  16602. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, unpackRowLen);
  16603. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, unpackImageHeight);
  16604. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, unpackSkipPixels);
  16605. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, unpackSkipRows);
  16606. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, unpackSkipImages); // Generate mipmaps only when copying level 0
  16607. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(glTarget);
  16608. state.unbindTexture();
  16609. };
  16610. this.initTexture = function (texture) {
  16611. textures.setTexture2D(texture, 0);
  16612. state.unbindTexture();
  16613. };
  16614. this.resetState = function () {
  16615. _currentActiveCubeFace = 0;
  16616. _currentActiveMipmapLevel = 0;
  16617. _currentRenderTarget = null;
  16618. state.reset();
  16619. bindingStates.reset();
  16620. };
  16621. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  16622. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  16623. detail: this
  16624. }));
  16625. }
  16626. }
  16627. WebGLRenderer.prototype.isWebGLRenderer = true;
  16628. class WebGL1Renderer extends WebGLRenderer {}
  16629. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  16630. class FogExp2 {
  16631. constructor(color, density = 0.00025) {
  16632. this.name = '';
  16633. this.color = new Color(color);
  16634. this.density = density;
  16635. }
  16636. clone() {
  16637. return new FogExp2(this.color, this.density);
  16638. }
  16639. toJSON() {
  16640. return {
  16641. type: 'FogExp2',
  16642. color: this.color.getHex(),
  16643. density: this.density
  16644. };
  16645. }
  16646. }
  16647. FogExp2.prototype.isFogExp2 = true;
  16648. class Fog {
  16649. constructor(color, near = 1, far = 1000) {
  16650. this.name = '';
  16651. this.color = new Color(color);
  16652. this.near = near;
  16653. this.far = far;
  16654. }
  16655. clone() {
  16656. return new Fog(this.color, this.near, this.far);
  16657. }
  16658. toJSON() {
  16659. return {
  16660. type: 'Fog',
  16661. color: this.color.getHex(),
  16662. near: this.near,
  16663. far: this.far
  16664. };
  16665. }
  16666. }
  16667. Fog.prototype.isFog = true;
  16668. class Scene extends Object3D {
  16669. constructor() {
  16670. super();
  16671. this.type = 'Scene';
  16672. this.background = null;
  16673. this.environment = null;
  16674. this.fog = null;
  16675. this.overrideMaterial = null;
  16676. this.autoUpdate = true; // checked by the renderer
  16677. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  16678. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  16679. detail: this
  16680. }));
  16681. }
  16682. }
  16683. copy(source, recursive) {
  16684. super.copy(source, recursive);
  16685. if (source.background !== null) this.background = source.background.clone();
  16686. if (source.environment !== null) this.environment = source.environment.clone();
  16687. if (source.fog !== null) this.fog = source.fog.clone();
  16688. if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
  16689. this.autoUpdate = source.autoUpdate;
  16690. this.matrixAutoUpdate = source.matrixAutoUpdate;
  16691. return this;
  16692. }
  16693. toJSON(meta) {
  16694. const data = super.toJSON(meta);
  16695. if (this.fog !== null) data.object.fog = this.fog.toJSON();
  16696. return data;
  16697. }
  16698. }
  16699. Scene.prototype.isScene = true;
  16700. class InterleavedBuffer {
  16701. constructor(array, stride) {
  16702. this.array = array;
  16703. this.stride = stride;
  16704. this.count = array !== undefined ? array.length / stride : 0;
  16705. this.usage = StaticDrawUsage;
  16706. this.updateRange = {
  16707. offset: 0,
  16708. count: -1
  16709. };
  16710. this.version = 0;
  16711. this.uuid = generateUUID();
  16712. }
  16713. onUploadCallback() {}
  16714. set needsUpdate(value) {
  16715. if (value === true) this.version++;
  16716. }
  16717. setUsage(value) {
  16718. this.usage = value;
  16719. return this;
  16720. }
  16721. copy(source) {
  16722. this.array = new source.array.constructor(source.array);
  16723. this.count = source.count;
  16724. this.stride = source.stride;
  16725. this.usage = source.usage;
  16726. return this;
  16727. }
  16728. copyAt(index1, attribute, index2) {
  16729. index1 *= this.stride;
  16730. index2 *= attribute.stride;
  16731. for (let i = 0, l = this.stride; i < l; i++) {
  16732. this.array[index1 + i] = attribute.array[index2 + i];
  16733. }
  16734. return this;
  16735. }
  16736. set(value, offset = 0) {
  16737. this.array.set(value, offset);
  16738. return this;
  16739. }
  16740. clone(data) {
  16741. if (data.arrayBuffers === undefined) {
  16742. data.arrayBuffers = {};
  16743. }
  16744. if (this.array.buffer._uuid === undefined) {
  16745. this.array.buffer._uuid = generateUUID();
  16746. }
  16747. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  16748. data.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer;
  16749. }
  16750. const array = new this.array.constructor(data.arrayBuffers[this.array.buffer._uuid]);
  16751. const ib = new this.constructor(array, this.stride);
  16752. ib.setUsage(this.usage);
  16753. return ib;
  16754. }
  16755. onUpload(callback) {
  16756. this.onUploadCallback = callback;
  16757. return this;
  16758. }
  16759. toJSON(data) {
  16760. if (data.arrayBuffers === undefined) {
  16761. data.arrayBuffers = {};
  16762. } // generate UUID for array buffer if necessary
  16763. if (this.array.buffer._uuid === undefined) {
  16764. this.array.buffer._uuid = generateUUID();
  16765. }
  16766. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  16767. data.arrayBuffers[this.array.buffer._uuid] = Array.prototype.slice.call(new Uint32Array(this.array.buffer));
  16768. } //
  16769. return {
  16770. uuid: this.uuid,
  16771. buffer: this.array.buffer._uuid,
  16772. type: this.array.constructor.name,
  16773. stride: this.stride
  16774. };
  16775. }
  16776. }
  16777. InterleavedBuffer.prototype.isInterleavedBuffer = true;
  16778. const _vector$6 = /*@__PURE__*/new Vector3();
  16779. class InterleavedBufferAttribute {
  16780. constructor(interleavedBuffer, itemSize, offset, normalized = false) {
  16781. this.name = '';
  16782. this.data = interleavedBuffer;
  16783. this.itemSize = itemSize;
  16784. this.offset = offset;
  16785. this.normalized = normalized === true;
  16786. }
  16787. get count() {
  16788. return this.data.count;
  16789. }
  16790. get array() {
  16791. return this.data.array;
  16792. }
  16793. set needsUpdate(value) {
  16794. this.data.needsUpdate = value;
  16795. }
  16796. applyMatrix4(m) {
  16797. for (let i = 0, l = this.data.count; i < l; i++) {
  16798. _vector$6.x = this.getX(i);
  16799. _vector$6.y = this.getY(i);
  16800. _vector$6.z = this.getZ(i);
  16801. _vector$6.applyMatrix4(m);
  16802. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  16803. }
  16804. return this;
  16805. }
  16806. applyNormalMatrix(m) {
  16807. for (let i = 0, l = this.count; i < l; i++) {
  16808. _vector$6.x = this.getX(i);
  16809. _vector$6.y = this.getY(i);
  16810. _vector$6.z = this.getZ(i);
  16811. _vector$6.applyNormalMatrix(m);
  16812. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  16813. }
  16814. return this;
  16815. }
  16816. transformDirection(m) {
  16817. for (let i = 0, l = this.count; i < l; i++) {
  16818. _vector$6.x = this.getX(i);
  16819. _vector$6.y = this.getY(i);
  16820. _vector$6.z = this.getZ(i);
  16821. _vector$6.transformDirection(m);
  16822. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  16823. }
  16824. return this;
  16825. }
  16826. setX(index, x) {
  16827. this.data.array[index * this.data.stride + this.offset] = x;
  16828. return this;
  16829. }
  16830. setY(index, y) {
  16831. this.data.array[index * this.data.stride + this.offset + 1] = y;
  16832. return this;
  16833. }
  16834. setZ(index, z) {
  16835. this.data.array[index * this.data.stride + this.offset + 2] = z;
  16836. return this;
  16837. }
  16838. setW(index, w) {
  16839. this.data.array[index * this.data.stride + this.offset + 3] = w;
  16840. return this;
  16841. }
  16842. getX(index) {
  16843. return this.data.array[index * this.data.stride + this.offset];
  16844. }
  16845. getY(index) {
  16846. return this.data.array[index * this.data.stride + this.offset + 1];
  16847. }
  16848. getZ(index) {
  16849. return this.data.array[index * this.data.stride + this.offset + 2];
  16850. }
  16851. getW(index) {
  16852. return this.data.array[index * this.data.stride + this.offset + 3];
  16853. }
  16854. setXY(index, x, y) {
  16855. index = index * this.data.stride + this.offset;
  16856. this.data.array[index + 0] = x;
  16857. this.data.array[index + 1] = y;
  16858. return this;
  16859. }
  16860. setXYZ(index, x, y, z) {
  16861. index = index * this.data.stride + this.offset;
  16862. this.data.array[index + 0] = x;
  16863. this.data.array[index + 1] = y;
  16864. this.data.array[index + 2] = z;
  16865. return this;
  16866. }
  16867. setXYZW(index, x, y, z, w) {
  16868. index = index * this.data.stride + this.offset;
  16869. this.data.array[index + 0] = x;
  16870. this.data.array[index + 1] = y;
  16871. this.data.array[index + 2] = z;
  16872. this.data.array[index + 3] = w;
  16873. return this;
  16874. }
  16875. clone(data) {
  16876. if (data === undefined) {
  16877. console.log('THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.');
  16878. const array = [];
  16879. for (let i = 0; i < this.count; i++) {
  16880. const index = i * this.data.stride + this.offset;
  16881. for (let j = 0; j < this.itemSize; j++) {
  16882. array.push(this.data.array[index + j]);
  16883. }
  16884. }
  16885. return new BufferAttribute(new this.array.constructor(array), this.itemSize, this.normalized);
  16886. } else {
  16887. if (data.interleavedBuffers === undefined) {
  16888. data.interleavedBuffers = {};
  16889. }
  16890. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  16891. data.interleavedBuffers[this.data.uuid] = this.data.clone(data);
  16892. }
  16893. return new InterleavedBufferAttribute(data.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized);
  16894. }
  16895. }
  16896. toJSON(data) {
  16897. if (data === undefined) {
  16898. console.log('THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.');
  16899. const array = [];
  16900. for (let i = 0; i < this.count; i++) {
  16901. const index = i * this.data.stride + this.offset;
  16902. for (let j = 0; j < this.itemSize; j++) {
  16903. array.push(this.data.array[index + j]);
  16904. }
  16905. } // deinterleave data and save it as an ordinary buffer attribute for now
  16906. return {
  16907. itemSize: this.itemSize,
  16908. type: this.array.constructor.name,
  16909. array: array,
  16910. normalized: this.normalized
  16911. };
  16912. } else {
  16913. // save as true interlaved attribtue
  16914. if (data.interleavedBuffers === undefined) {
  16915. data.interleavedBuffers = {};
  16916. }
  16917. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  16918. data.interleavedBuffers[this.data.uuid] = this.data.toJSON(data);
  16919. }
  16920. return {
  16921. isInterleavedBufferAttribute: true,
  16922. itemSize: this.itemSize,
  16923. data: this.data.uuid,
  16924. offset: this.offset,
  16925. normalized: this.normalized
  16926. };
  16927. }
  16928. }
  16929. }
  16930. InterleavedBufferAttribute.prototype.isInterleavedBufferAttribute = true;
  16931. /**
  16932. * parameters = {
  16933. * color: <hex>,
  16934. * map: new THREE.Texture( <Image> ),
  16935. * alphaMap: new THREE.Texture( <Image> ),
  16936. * rotation: <float>,
  16937. * sizeAttenuation: <bool>
  16938. * }
  16939. */
  16940. class SpriteMaterial extends Material {
  16941. constructor(parameters) {
  16942. super();
  16943. this.type = 'SpriteMaterial';
  16944. this.color = new Color(0xffffff);
  16945. this.map = null;
  16946. this.alphaMap = null;
  16947. this.rotation = 0;
  16948. this.sizeAttenuation = true;
  16949. this.transparent = true;
  16950. this.setValues(parameters);
  16951. }
  16952. copy(source) {
  16953. super.copy(source);
  16954. this.color.copy(source.color);
  16955. this.map = source.map;
  16956. this.alphaMap = source.alphaMap;
  16957. this.rotation = source.rotation;
  16958. this.sizeAttenuation = source.sizeAttenuation;
  16959. return this;
  16960. }
  16961. }
  16962. SpriteMaterial.prototype.isSpriteMaterial = true;
  16963. let _geometry;
  16964. const _intersectPoint = /*@__PURE__*/new Vector3();
  16965. const _worldScale = /*@__PURE__*/new Vector3();
  16966. const _mvPosition = /*@__PURE__*/new Vector3();
  16967. const _alignedPosition = /*@__PURE__*/new Vector2();
  16968. const _rotatedPosition = /*@__PURE__*/new Vector2();
  16969. const _viewWorldMatrix = /*@__PURE__*/new Matrix4();
  16970. const _vA = /*@__PURE__*/new Vector3();
  16971. const _vB = /*@__PURE__*/new Vector3();
  16972. const _vC = /*@__PURE__*/new Vector3();
  16973. const _uvA = /*@__PURE__*/new Vector2();
  16974. const _uvB = /*@__PURE__*/new Vector2();
  16975. const _uvC = /*@__PURE__*/new Vector2();
  16976. class Sprite extends Object3D {
  16977. constructor(material) {
  16978. super();
  16979. this.type = 'Sprite';
  16980. if (_geometry === undefined) {
  16981. _geometry = new BufferGeometry();
  16982. 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]);
  16983. const interleavedBuffer = new InterleavedBuffer(float32Array, 5);
  16984. _geometry.setIndex([0, 1, 2, 0, 2, 3]);
  16985. _geometry.setAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
  16986. _geometry.setAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
  16987. }
  16988. this.geometry = _geometry;
  16989. this.material = material !== undefined ? material : new SpriteMaterial();
  16990. this.center = new Vector2(0.5, 0.5);
  16991. }
  16992. raycast(raycaster, intersects) {
  16993. if (raycaster.camera === null) {
  16994. console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
  16995. }
  16996. _worldScale.setFromMatrixScale(this.matrixWorld);
  16997. _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
  16998. this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
  16999. _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
  17000. if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
  17001. _worldScale.multiplyScalar(-_mvPosition.z);
  17002. }
  17003. const rotation = this.material.rotation;
  17004. let sin, cos;
  17005. if (rotation !== 0) {
  17006. cos = Math.cos(rotation);
  17007. sin = Math.sin(rotation);
  17008. }
  17009. const center = this.center;
  17010. transformVertex(_vA.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17011. transformVertex(_vB.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17012. transformVertex(_vC.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17013. _uvA.set(0, 0);
  17014. _uvB.set(1, 0);
  17015. _uvC.set(1, 1); // check first triangle
  17016. let intersect = raycaster.ray.intersectTriangle(_vA, _vB, _vC, false, _intersectPoint);
  17017. if (intersect === null) {
  17018. // check second triangle
  17019. transformVertex(_vB.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17020. _uvB.set(0, 1);
  17021. intersect = raycaster.ray.intersectTriangle(_vA, _vC, _vB, false, _intersectPoint);
  17022. if (intersect === null) {
  17023. return;
  17024. }
  17025. }
  17026. const distance = raycaster.ray.origin.distanceTo(_intersectPoint);
  17027. if (distance < raycaster.near || distance > raycaster.far) return;
  17028. intersects.push({
  17029. distance: distance,
  17030. point: _intersectPoint.clone(),
  17031. uv: Triangle.getUV(_intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2()),
  17032. face: null,
  17033. object: this
  17034. });
  17035. }
  17036. copy(source) {
  17037. super.copy(source);
  17038. if (source.center !== undefined) this.center.copy(source.center);
  17039. this.material = source.material;
  17040. return this;
  17041. }
  17042. }
  17043. Sprite.prototype.isSprite = true;
  17044. function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
  17045. // compute position in camera space
  17046. _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); // to check if rotation is not zero
  17047. if (sin !== undefined) {
  17048. _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
  17049. _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
  17050. } else {
  17051. _rotatedPosition.copy(_alignedPosition);
  17052. }
  17053. vertexPosition.copy(mvPosition);
  17054. vertexPosition.x += _rotatedPosition.x;
  17055. vertexPosition.y += _rotatedPosition.y; // transform to world space
  17056. vertexPosition.applyMatrix4(_viewWorldMatrix);
  17057. }
  17058. const _v1$2 = /*@__PURE__*/new Vector3();
  17059. const _v2$1 = /*@__PURE__*/new Vector3();
  17060. class LOD extends Object3D {
  17061. constructor() {
  17062. super();
  17063. this._currentLevel = 0;
  17064. this.type = 'LOD';
  17065. Object.defineProperties(this, {
  17066. levels: {
  17067. enumerable: true,
  17068. value: []
  17069. },
  17070. isLOD: {
  17071. value: true
  17072. }
  17073. });
  17074. this.autoUpdate = true;
  17075. }
  17076. copy(source) {
  17077. super.copy(source, false);
  17078. const levels = source.levels;
  17079. for (let i = 0, l = levels.length; i < l; i++) {
  17080. const level = levels[i];
  17081. this.addLevel(level.object.clone(), level.distance);
  17082. }
  17083. this.autoUpdate = source.autoUpdate;
  17084. return this;
  17085. }
  17086. addLevel(object, distance = 0) {
  17087. distance = Math.abs(distance);
  17088. const levels = this.levels;
  17089. let l;
  17090. for (l = 0; l < levels.length; l++) {
  17091. if (distance < levels[l].distance) {
  17092. break;
  17093. }
  17094. }
  17095. levels.splice(l, 0, {
  17096. distance: distance,
  17097. object: object
  17098. });
  17099. this.add(object);
  17100. return this;
  17101. }
  17102. getCurrentLevel() {
  17103. return this._currentLevel;
  17104. }
  17105. getObjectForDistance(distance) {
  17106. const levels = this.levels;
  17107. if (levels.length > 0) {
  17108. let i, l;
  17109. for (i = 1, l = levels.length; i < l; i++) {
  17110. if (distance < levels[i].distance) {
  17111. break;
  17112. }
  17113. }
  17114. return levels[i - 1].object;
  17115. }
  17116. return null;
  17117. }
  17118. raycast(raycaster, intersects) {
  17119. const levels = this.levels;
  17120. if (levels.length > 0) {
  17121. _v1$2.setFromMatrixPosition(this.matrixWorld);
  17122. const distance = raycaster.ray.origin.distanceTo(_v1$2);
  17123. this.getObjectForDistance(distance).raycast(raycaster, intersects);
  17124. }
  17125. }
  17126. update(camera) {
  17127. const levels = this.levels;
  17128. if (levels.length > 1) {
  17129. _v1$2.setFromMatrixPosition(camera.matrixWorld);
  17130. _v2$1.setFromMatrixPosition(this.matrixWorld);
  17131. const distance = _v1$2.distanceTo(_v2$1) / camera.zoom;
  17132. levels[0].object.visible = true;
  17133. let i, l;
  17134. for (i = 1, l = levels.length; i < l; i++) {
  17135. if (distance >= levels[i].distance) {
  17136. levels[i - 1].object.visible = false;
  17137. levels[i].object.visible = true;
  17138. } else {
  17139. break;
  17140. }
  17141. }
  17142. this._currentLevel = i - 1;
  17143. for (; i < l; i++) {
  17144. levels[i].object.visible = false;
  17145. }
  17146. }
  17147. }
  17148. toJSON(meta) {
  17149. const data = super.toJSON(meta);
  17150. if (this.autoUpdate === false) data.object.autoUpdate = false;
  17151. data.object.levels = [];
  17152. const levels = this.levels;
  17153. for (let i = 0, l = levels.length; i < l; i++) {
  17154. const level = levels[i];
  17155. data.object.levels.push({
  17156. object: level.object.uuid,
  17157. distance: level.distance
  17158. });
  17159. }
  17160. return data;
  17161. }
  17162. }
  17163. const _basePosition = /*@__PURE__*/new Vector3();
  17164. const _skinIndex = /*@__PURE__*/new Vector4();
  17165. const _skinWeight = /*@__PURE__*/new Vector4();
  17166. const _vector$5 = /*@__PURE__*/new Vector3();
  17167. const _matrix = /*@__PURE__*/new Matrix4();
  17168. class SkinnedMesh extends Mesh {
  17169. constructor(geometry, material) {
  17170. super(geometry, material);
  17171. this.type = 'SkinnedMesh';
  17172. this.bindMode = 'attached';
  17173. this.bindMatrix = new Matrix4();
  17174. this.bindMatrixInverse = new Matrix4();
  17175. }
  17176. copy(source) {
  17177. super.copy(source);
  17178. this.bindMode = source.bindMode;
  17179. this.bindMatrix.copy(source.bindMatrix);
  17180. this.bindMatrixInverse.copy(source.bindMatrixInverse);
  17181. this.skeleton = source.skeleton;
  17182. return this;
  17183. }
  17184. bind(skeleton, bindMatrix) {
  17185. this.skeleton = skeleton;
  17186. if (bindMatrix === undefined) {
  17187. this.updateMatrixWorld(true);
  17188. this.skeleton.calculateInverses();
  17189. bindMatrix = this.matrixWorld;
  17190. }
  17191. this.bindMatrix.copy(bindMatrix);
  17192. this.bindMatrixInverse.copy(bindMatrix).invert();
  17193. }
  17194. pose() {
  17195. this.skeleton.pose();
  17196. }
  17197. normalizeSkinWeights() {
  17198. const vector = new Vector4();
  17199. const skinWeight = this.geometry.attributes.skinWeight;
  17200. for (let i = 0, l = skinWeight.count; i < l; i++) {
  17201. vector.x = skinWeight.getX(i);
  17202. vector.y = skinWeight.getY(i);
  17203. vector.z = skinWeight.getZ(i);
  17204. vector.w = skinWeight.getW(i);
  17205. const scale = 1.0 / vector.manhattanLength();
  17206. if (scale !== Infinity) {
  17207. vector.multiplyScalar(scale);
  17208. } else {
  17209. vector.set(1, 0, 0, 0); // do something reasonable
  17210. }
  17211. skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
  17212. }
  17213. }
  17214. updateMatrixWorld(force) {
  17215. super.updateMatrixWorld(force);
  17216. if (this.bindMode === 'attached') {
  17217. this.bindMatrixInverse.copy(this.matrixWorld).invert();
  17218. } else if (this.bindMode === 'detached') {
  17219. this.bindMatrixInverse.copy(this.bindMatrix).invert();
  17220. } else {
  17221. console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
  17222. }
  17223. }
  17224. boneTransform(index, target) {
  17225. const skeleton = this.skeleton;
  17226. const geometry = this.geometry;
  17227. _skinIndex.fromBufferAttribute(geometry.attributes.skinIndex, index);
  17228. _skinWeight.fromBufferAttribute(geometry.attributes.skinWeight, index);
  17229. _basePosition.copy(target).applyMatrix4(this.bindMatrix);
  17230. target.set(0, 0, 0);
  17231. for (let i = 0; i < 4; i++) {
  17232. const weight = _skinWeight.getComponent(i);
  17233. if (weight !== 0) {
  17234. const boneIndex = _skinIndex.getComponent(i);
  17235. _matrix.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld, skeleton.boneInverses[boneIndex]);
  17236. target.addScaledVector(_vector$5.copy(_basePosition).applyMatrix4(_matrix), weight);
  17237. }
  17238. }
  17239. return target.applyMatrix4(this.bindMatrixInverse);
  17240. }
  17241. }
  17242. SkinnedMesh.prototype.isSkinnedMesh = true;
  17243. class Bone extends Object3D {
  17244. constructor() {
  17245. super();
  17246. this.type = 'Bone';
  17247. }
  17248. }
  17249. Bone.prototype.isBone = true;
  17250. class DataTexture extends Texture {
  17251. constructor(data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding) {
  17252. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  17253. this.image = {
  17254. data: data,
  17255. width: width,
  17256. height: height
  17257. };
  17258. this.magFilter = magFilter;
  17259. this.minFilter = minFilter;
  17260. this.generateMipmaps = false;
  17261. this.flipY = false;
  17262. this.unpackAlignment = 1;
  17263. }
  17264. }
  17265. DataTexture.prototype.isDataTexture = true;
  17266. const _offsetMatrix = /*@__PURE__*/new Matrix4();
  17267. const _identityMatrix = /*@__PURE__*/new Matrix4();
  17268. class Skeleton {
  17269. constructor(bones = [], boneInverses = []) {
  17270. this.uuid = generateUUID();
  17271. this.bones = bones.slice(0);
  17272. this.boneInverses = boneInverses;
  17273. this.boneMatrices = null;
  17274. this.boneTexture = null;
  17275. this.boneTextureSize = 0;
  17276. this.frame = -1;
  17277. this.init();
  17278. }
  17279. init() {
  17280. const bones = this.bones;
  17281. const boneInverses = this.boneInverses;
  17282. this.boneMatrices = new Float32Array(bones.length * 16); // calculate inverse bone matrices if necessary
  17283. if (boneInverses.length === 0) {
  17284. this.calculateInverses();
  17285. } else {
  17286. // handle special case
  17287. if (bones.length !== boneInverses.length) {
  17288. console.warn('THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.');
  17289. this.boneInverses = [];
  17290. for (let i = 0, il = this.bones.length; i < il; i++) {
  17291. this.boneInverses.push(new Matrix4());
  17292. }
  17293. }
  17294. }
  17295. }
  17296. calculateInverses() {
  17297. this.boneInverses.length = 0;
  17298. for (let i = 0, il = this.bones.length; i < il; i++) {
  17299. const inverse = new Matrix4();
  17300. if (this.bones[i]) {
  17301. inverse.copy(this.bones[i].matrixWorld).invert();
  17302. }
  17303. this.boneInverses.push(inverse);
  17304. }
  17305. }
  17306. pose() {
  17307. // recover the bind-time world matrices
  17308. for (let i = 0, il = this.bones.length; i < il; i++) {
  17309. const bone = this.bones[i];
  17310. if (bone) {
  17311. bone.matrixWorld.copy(this.boneInverses[i]).invert();
  17312. }
  17313. } // compute the local matrices, positions, rotations and scales
  17314. for (let i = 0, il = this.bones.length; i < il; i++) {
  17315. const bone = this.bones[i];
  17316. if (bone) {
  17317. if (bone.parent && bone.parent.isBone) {
  17318. bone.matrix.copy(bone.parent.matrixWorld).invert();
  17319. bone.matrix.multiply(bone.matrixWorld);
  17320. } else {
  17321. bone.matrix.copy(bone.matrixWorld);
  17322. }
  17323. bone.matrix.decompose(bone.position, bone.quaternion, bone.scale);
  17324. }
  17325. }
  17326. }
  17327. update() {
  17328. const bones = this.bones;
  17329. const boneInverses = this.boneInverses;
  17330. const boneMatrices = this.boneMatrices;
  17331. const boneTexture = this.boneTexture; // flatten bone matrices to array
  17332. for (let i = 0, il = bones.length; i < il; i++) {
  17333. // compute the offset between the current and the original transform
  17334. const matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
  17335. _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
  17336. _offsetMatrix.toArray(boneMatrices, i * 16);
  17337. }
  17338. if (boneTexture !== null) {
  17339. boneTexture.needsUpdate = true;
  17340. }
  17341. }
  17342. clone() {
  17343. return new Skeleton(this.bones, this.boneInverses);
  17344. }
  17345. computeBoneTexture() {
  17346. // layout (1 matrix = 4 pixels)
  17347. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  17348. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  17349. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  17350. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  17351. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  17352. let size = Math.sqrt(this.bones.length * 4); // 4 pixels needed for 1 matrix
  17353. size = ceilPowerOfTwo(size);
  17354. size = Math.max(size, 4);
  17355. const boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
  17356. boneMatrices.set(this.boneMatrices); // copy current values
  17357. const boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
  17358. boneTexture.needsUpdate = true;
  17359. this.boneMatrices = boneMatrices;
  17360. this.boneTexture = boneTexture;
  17361. this.boneTextureSize = size;
  17362. return this;
  17363. }
  17364. getBoneByName(name) {
  17365. for (let i = 0, il = this.bones.length; i < il; i++) {
  17366. const bone = this.bones[i];
  17367. if (bone.name === name) {
  17368. return bone;
  17369. }
  17370. }
  17371. return undefined;
  17372. }
  17373. dispose() {
  17374. if (this.boneTexture !== null) {
  17375. this.boneTexture.dispose();
  17376. this.boneTexture = null;
  17377. }
  17378. }
  17379. fromJSON(json, bones) {
  17380. this.uuid = json.uuid;
  17381. for (let i = 0, l = json.bones.length; i < l; i++) {
  17382. const uuid = json.bones[i];
  17383. let bone = bones[uuid];
  17384. if (bone === undefined) {
  17385. console.warn('THREE.Skeleton: No bone found with UUID:', uuid);
  17386. bone = new Bone();
  17387. }
  17388. this.bones.push(bone);
  17389. this.boneInverses.push(new Matrix4().fromArray(json.boneInverses[i]));
  17390. }
  17391. this.init();
  17392. return this;
  17393. }
  17394. toJSON() {
  17395. const data = {
  17396. metadata: {
  17397. version: 4.5,
  17398. type: 'Skeleton',
  17399. generator: 'Skeleton.toJSON'
  17400. },
  17401. bones: [],
  17402. boneInverses: []
  17403. };
  17404. data.uuid = this.uuid;
  17405. const bones = this.bones;
  17406. const boneInverses = this.boneInverses;
  17407. for (let i = 0, l = bones.length; i < l; i++) {
  17408. const bone = bones[i];
  17409. data.bones.push(bone.uuid);
  17410. const boneInverse = boneInverses[i];
  17411. data.boneInverses.push(boneInverse.toArray());
  17412. }
  17413. return data;
  17414. }
  17415. }
  17416. class InstancedBufferAttribute extends BufferAttribute {
  17417. constructor(array, itemSize, normalized, meshPerAttribute = 1) {
  17418. if (typeof normalized === 'number') {
  17419. meshPerAttribute = normalized;
  17420. normalized = false;
  17421. console.error('THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.');
  17422. }
  17423. super(array, itemSize, normalized);
  17424. this.meshPerAttribute = meshPerAttribute;
  17425. }
  17426. copy(source) {
  17427. super.copy(source);
  17428. this.meshPerAttribute = source.meshPerAttribute;
  17429. return this;
  17430. }
  17431. toJSON() {
  17432. const data = super.toJSON();
  17433. data.meshPerAttribute = this.meshPerAttribute;
  17434. data.isInstancedBufferAttribute = true;
  17435. return data;
  17436. }
  17437. }
  17438. InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true;
  17439. const _instanceLocalMatrix = /*@__PURE__*/new Matrix4();
  17440. const _instanceWorldMatrix = /*@__PURE__*/new Matrix4();
  17441. const _instanceIntersects = [];
  17442. const _mesh = /*@__PURE__*/new Mesh();
  17443. class InstancedMesh extends Mesh {
  17444. constructor(geometry, material, count) {
  17445. super(geometry, material);
  17446. this.instanceMatrix = new InstancedBufferAttribute(new Float32Array(count * 16), 16);
  17447. this.instanceColor = null;
  17448. this.count = count;
  17449. this.frustumCulled = false;
  17450. }
  17451. copy(source) {
  17452. super.copy(source);
  17453. this.instanceMatrix.copy(source.instanceMatrix);
  17454. if (source.instanceColor !== null) this.instanceColor = source.instanceColor.clone();
  17455. this.count = source.count;
  17456. return this;
  17457. }
  17458. getColorAt(index, color) {
  17459. color.fromArray(this.instanceColor.array, index * 3);
  17460. }
  17461. getMatrixAt(index, matrix) {
  17462. matrix.fromArray(this.instanceMatrix.array, index * 16);
  17463. }
  17464. raycast(raycaster, intersects) {
  17465. const matrixWorld = this.matrixWorld;
  17466. const raycastTimes = this.count;
  17467. _mesh.geometry = this.geometry;
  17468. _mesh.material = this.material;
  17469. if (_mesh.material === undefined) return;
  17470. for (let instanceId = 0; instanceId < raycastTimes; instanceId++) {
  17471. // calculate the world matrix for each instance
  17472. this.getMatrixAt(instanceId, _instanceLocalMatrix);
  17473. _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix); // the mesh represents this single instance
  17474. _mesh.matrixWorld = _instanceWorldMatrix;
  17475. _mesh.raycast(raycaster, _instanceIntersects); // process the result of raycast
  17476. for (let i = 0, l = _instanceIntersects.length; i < l; i++) {
  17477. const intersect = _instanceIntersects[i];
  17478. intersect.instanceId = instanceId;
  17479. intersect.object = this;
  17480. intersects.push(intersect);
  17481. }
  17482. _instanceIntersects.length = 0;
  17483. }
  17484. }
  17485. setColorAt(index, color) {
  17486. if (this.instanceColor === null) {
  17487. this.instanceColor = new InstancedBufferAttribute(new Float32Array(this.instanceMatrix.count * 3), 3);
  17488. }
  17489. color.toArray(this.instanceColor.array, index * 3);
  17490. }
  17491. setMatrixAt(index, matrix) {
  17492. matrix.toArray(this.instanceMatrix.array, index * 16);
  17493. }
  17494. updateMorphTargets() {}
  17495. dispose() {
  17496. this.dispatchEvent({
  17497. type: 'dispose'
  17498. });
  17499. }
  17500. }
  17501. InstancedMesh.prototype.isInstancedMesh = true;
  17502. /**
  17503. * parameters = {
  17504. * color: <hex>,
  17505. * opacity: <float>,
  17506. *
  17507. * linewidth: <float>,
  17508. * linecap: "round",
  17509. * linejoin: "round"
  17510. * }
  17511. */
  17512. class LineBasicMaterial extends Material {
  17513. constructor(parameters) {
  17514. super();
  17515. this.type = 'LineBasicMaterial';
  17516. this.color = new Color(0xffffff);
  17517. this.linewidth = 1;
  17518. this.linecap = 'round';
  17519. this.linejoin = 'round';
  17520. this.setValues(parameters);
  17521. }
  17522. copy(source) {
  17523. super.copy(source);
  17524. this.color.copy(source.color);
  17525. this.linewidth = source.linewidth;
  17526. this.linecap = source.linecap;
  17527. this.linejoin = source.linejoin;
  17528. return this;
  17529. }
  17530. }
  17531. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  17532. const _start$1 = /*@__PURE__*/new Vector3();
  17533. const _end$1 = /*@__PURE__*/new Vector3();
  17534. const _inverseMatrix$1 = /*@__PURE__*/new Matrix4();
  17535. const _ray$1 = /*@__PURE__*/new Ray();
  17536. const _sphere$1 = /*@__PURE__*/new Sphere();
  17537. class Line extends Object3D {
  17538. constructor(geometry = new BufferGeometry(), material = new LineBasicMaterial()) {
  17539. super();
  17540. this.type = 'Line';
  17541. this.geometry = geometry;
  17542. this.material = material;
  17543. this.updateMorphTargets();
  17544. }
  17545. copy(source) {
  17546. super.copy(source);
  17547. this.material = source.material;
  17548. this.geometry = source.geometry;
  17549. return this;
  17550. }
  17551. computeLineDistances() {
  17552. const geometry = this.geometry;
  17553. if (geometry.isBufferGeometry) {
  17554. // we assume non-indexed geometry
  17555. if (geometry.index === null) {
  17556. const positionAttribute = geometry.attributes.position;
  17557. const lineDistances = [0];
  17558. for (let i = 1, l = positionAttribute.count; i < l; i++) {
  17559. _start$1.fromBufferAttribute(positionAttribute, i - 1);
  17560. _end$1.fromBufferAttribute(positionAttribute, i);
  17561. lineDistances[i] = lineDistances[i - 1];
  17562. lineDistances[i] += _start$1.distanceTo(_end$1);
  17563. }
  17564. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  17565. } else {
  17566. console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  17567. }
  17568. } else if (geometry.isGeometry) {
  17569. console.error('THREE.Line.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  17570. }
  17571. return this;
  17572. }
  17573. raycast(raycaster, intersects) {
  17574. const geometry = this.geometry;
  17575. const matrixWorld = this.matrixWorld;
  17576. const threshold = raycaster.params.Line.threshold;
  17577. const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
  17578. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  17579. _sphere$1.copy(geometry.boundingSphere);
  17580. _sphere$1.applyMatrix4(matrixWorld);
  17581. _sphere$1.radius += threshold;
  17582. if (raycaster.ray.intersectsSphere(_sphere$1) === false) return; //
  17583. _inverseMatrix$1.copy(matrixWorld).invert();
  17584. _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
  17585. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  17586. const localThresholdSq = localThreshold * localThreshold;
  17587. const vStart = new Vector3();
  17588. const vEnd = new Vector3();
  17589. const interSegment = new Vector3();
  17590. const interRay = new Vector3();
  17591. const step = this.isLineSegments ? 2 : 1;
  17592. if (geometry.isBufferGeometry) {
  17593. const index = geometry.index;
  17594. const attributes = geometry.attributes;
  17595. const positionAttribute = attributes.position;
  17596. if (index !== null) {
  17597. const start = Math.max(0, drawRange.start);
  17598. const end = Math.min(index.count, drawRange.start + drawRange.count);
  17599. for (let i = start, l = end - 1; i < l; i += step) {
  17600. const a = index.getX(i);
  17601. const b = index.getX(i + 1);
  17602. vStart.fromBufferAttribute(positionAttribute, a);
  17603. vEnd.fromBufferAttribute(positionAttribute, b);
  17604. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  17605. if (distSq > localThresholdSq) continue;
  17606. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  17607. const distance = raycaster.ray.origin.distanceTo(interRay);
  17608. if (distance < raycaster.near || distance > raycaster.far) continue;
  17609. intersects.push({
  17610. distance: distance,
  17611. // What do we want? intersection point on the ray or on the segment??
  17612. // point: raycaster.ray.at( distance ),
  17613. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  17614. index: i,
  17615. face: null,
  17616. faceIndex: null,
  17617. object: this
  17618. });
  17619. }
  17620. } else {
  17621. const start = Math.max(0, drawRange.start);
  17622. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  17623. for (let i = start, l = end - 1; i < l; i += step) {
  17624. vStart.fromBufferAttribute(positionAttribute, i);
  17625. vEnd.fromBufferAttribute(positionAttribute, i + 1);
  17626. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  17627. if (distSq > localThresholdSq) continue;
  17628. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  17629. const distance = raycaster.ray.origin.distanceTo(interRay);
  17630. if (distance < raycaster.near || distance > raycaster.far) continue;
  17631. intersects.push({
  17632. distance: distance,
  17633. // What do we want? intersection point on the ray or on the segment??
  17634. // point: raycaster.ray.at( distance ),
  17635. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  17636. index: i,
  17637. face: null,
  17638. faceIndex: null,
  17639. object: this
  17640. });
  17641. }
  17642. }
  17643. } else if (geometry.isGeometry) {
  17644. console.error('THREE.Line.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  17645. }
  17646. }
  17647. updateMorphTargets() {
  17648. const geometry = this.geometry;
  17649. if (geometry.isBufferGeometry) {
  17650. const morphAttributes = geometry.morphAttributes;
  17651. const keys = Object.keys(morphAttributes);
  17652. if (keys.length > 0) {
  17653. const morphAttribute = morphAttributes[keys[0]];
  17654. if (morphAttribute !== undefined) {
  17655. this.morphTargetInfluences = [];
  17656. this.morphTargetDictionary = {};
  17657. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  17658. const name = morphAttribute[m].name || String(m);
  17659. this.morphTargetInfluences.push(0);
  17660. this.morphTargetDictionary[name] = m;
  17661. }
  17662. }
  17663. }
  17664. } else {
  17665. const morphTargets = geometry.morphTargets;
  17666. if (morphTargets !== undefined && morphTargets.length > 0) {
  17667. console.error('THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  17668. }
  17669. }
  17670. }
  17671. }
  17672. Line.prototype.isLine = true;
  17673. const _start = /*@__PURE__*/new Vector3();
  17674. const _end = /*@__PURE__*/new Vector3();
  17675. class LineSegments extends Line {
  17676. constructor(geometry, material) {
  17677. super(geometry, material);
  17678. this.type = 'LineSegments';
  17679. }
  17680. computeLineDistances() {
  17681. const geometry = this.geometry;
  17682. if (geometry.isBufferGeometry) {
  17683. // we assume non-indexed geometry
  17684. if (geometry.index === null) {
  17685. const positionAttribute = geometry.attributes.position;
  17686. const lineDistances = [];
  17687. for (let i = 0, l = positionAttribute.count; i < l; i += 2) {
  17688. _start.fromBufferAttribute(positionAttribute, i);
  17689. _end.fromBufferAttribute(positionAttribute, i + 1);
  17690. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  17691. lineDistances[i + 1] = lineDistances[i] + _start.distanceTo(_end);
  17692. }
  17693. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  17694. } else {
  17695. console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  17696. }
  17697. } else if (geometry.isGeometry) {
  17698. console.error('THREE.LineSegments.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  17699. }
  17700. return this;
  17701. }
  17702. }
  17703. LineSegments.prototype.isLineSegments = true;
  17704. class LineLoop extends Line {
  17705. constructor(geometry, material) {
  17706. super(geometry, material);
  17707. this.type = 'LineLoop';
  17708. }
  17709. }
  17710. LineLoop.prototype.isLineLoop = true;
  17711. /**
  17712. * parameters = {
  17713. * color: <hex>,
  17714. * opacity: <float>,
  17715. * map: new THREE.Texture( <Image> ),
  17716. * alphaMap: new THREE.Texture( <Image> ),
  17717. *
  17718. * size: <float>,
  17719. * sizeAttenuation: <bool>
  17720. *
  17721. * }
  17722. */
  17723. class PointsMaterial extends Material {
  17724. constructor(parameters) {
  17725. super();
  17726. this.type = 'PointsMaterial';
  17727. this.color = new Color(0xffffff);
  17728. this.map = null;
  17729. this.alphaMap = null;
  17730. this.size = 1;
  17731. this.sizeAttenuation = true;
  17732. this.setValues(parameters);
  17733. }
  17734. copy(source) {
  17735. super.copy(source);
  17736. this.color.copy(source.color);
  17737. this.map = source.map;
  17738. this.alphaMap = source.alphaMap;
  17739. this.size = source.size;
  17740. this.sizeAttenuation = source.sizeAttenuation;
  17741. return this;
  17742. }
  17743. }
  17744. PointsMaterial.prototype.isPointsMaterial = true;
  17745. const _inverseMatrix = /*@__PURE__*/new Matrix4();
  17746. const _ray = /*@__PURE__*/new Ray();
  17747. const _sphere = /*@__PURE__*/new Sphere();
  17748. const _position$2 = /*@__PURE__*/new Vector3();
  17749. class Points extends Object3D {
  17750. constructor(geometry = new BufferGeometry(), material = new PointsMaterial()) {
  17751. super();
  17752. this.type = 'Points';
  17753. this.geometry = geometry;
  17754. this.material = material;
  17755. this.updateMorphTargets();
  17756. }
  17757. copy(source) {
  17758. super.copy(source);
  17759. this.material = source.material;
  17760. this.geometry = source.geometry;
  17761. return this;
  17762. }
  17763. raycast(raycaster, intersects) {
  17764. const geometry = this.geometry;
  17765. const matrixWorld = this.matrixWorld;
  17766. const threshold = raycaster.params.Points.threshold;
  17767. const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
  17768. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  17769. _sphere.copy(geometry.boundingSphere);
  17770. _sphere.applyMatrix4(matrixWorld);
  17771. _sphere.radius += threshold;
  17772. if (raycaster.ray.intersectsSphere(_sphere) === false) return; //
  17773. _inverseMatrix.copy(matrixWorld).invert();
  17774. _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix);
  17775. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  17776. const localThresholdSq = localThreshold * localThreshold;
  17777. if (geometry.isBufferGeometry) {
  17778. const index = geometry.index;
  17779. const attributes = geometry.attributes;
  17780. const positionAttribute = attributes.position;
  17781. if (index !== null) {
  17782. const start = Math.max(0, drawRange.start);
  17783. const end = Math.min(index.count, drawRange.start + drawRange.count);
  17784. for (let i = start, il = end; i < il; i++) {
  17785. const a = index.getX(i);
  17786. _position$2.fromBufferAttribute(positionAttribute, a);
  17787. testPoint(_position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17788. }
  17789. } else {
  17790. const start = Math.max(0, drawRange.start);
  17791. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  17792. for (let i = start, l = end; i < l; i++) {
  17793. _position$2.fromBufferAttribute(positionAttribute, i);
  17794. testPoint(_position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17795. }
  17796. }
  17797. } else {
  17798. console.error('THREE.Points.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  17799. }
  17800. }
  17801. updateMorphTargets() {
  17802. const geometry = this.geometry;
  17803. if (geometry.isBufferGeometry) {
  17804. const morphAttributes = geometry.morphAttributes;
  17805. const keys = Object.keys(morphAttributes);
  17806. if (keys.length > 0) {
  17807. const morphAttribute = morphAttributes[keys[0]];
  17808. if (morphAttribute !== undefined) {
  17809. this.morphTargetInfluences = [];
  17810. this.morphTargetDictionary = {};
  17811. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  17812. const name = morphAttribute[m].name || String(m);
  17813. this.morphTargetInfluences.push(0);
  17814. this.morphTargetDictionary[name] = m;
  17815. }
  17816. }
  17817. }
  17818. } else {
  17819. const morphTargets = geometry.morphTargets;
  17820. if (morphTargets !== undefined && morphTargets.length > 0) {
  17821. console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  17822. }
  17823. }
  17824. }
  17825. }
  17826. Points.prototype.isPoints = true;
  17827. function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
  17828. const rayPointDistanceSq = _ray.distanceSqToPoint(point);
  17829. if (rayPointDistanceSq < localThresholdSq) {
  17830. const intersectPoint = new Vector3();
  17831. _ray.closestPointToPoint(point, intersectPoint);
  17832. intersectPoint.applyMatrix4(matrixWorld);
  17833. const distance = raycaster.ray.origin.distanceTo(intersectPoint);
  17834. if (distance < raycaster.near || distance > raycaster.far) return;
  17835. intersects.push({
  17836. distance: distance,
  17837. distanceToRay: Math.sqrt(rayPointDistanceSq),
  17838. point: intersectPoint,
  17839. index: index,
  17840. face: null,
  17841. object: object
  17842. });
  17843. }
  17844. }
  17845. class VideoTexture extends Texture {
  17846. constructor(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  17847. super(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  17848. this.format = format !== undefined ? format : RGBFormat;
  17849. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  17850. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  17851. this.generateMipmaps = false;
  17852. const scope = this;
  17853. function updateVideo() {
  17854. scope.needsUpdate = true;
  17855. video.requestVideoFrameCallback(updateVideo);
  17856. }
  17857. if ('requestVideoFrameCallback' in video) {
  17858. video.requestVideoFrameCallback(updateVideo);
  17859. }
  17860. }
  17861. clone() {
  17862. return new this.constructor(this.image).copy(this);
  17863. }
  17864. update() {
  17865. const video = this.image;
  17866. const hasVideoFrameCallback = ('requestVideoFrameCallback' in video);
  17867. if (hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA) {
  17868. this.needsUpdate = true;
  17869. }
  17870. }
  17871. }
  17872. VideoTexture.prototype.isVideoTexture = true;
  17873. class FramebufferTexture extends Texture {
  17874. constructor(width, height, format) {
  17875. super({
  17876. width,
  17877. height
  17878. });
  17879. this.format = format;
  17880. this.magFilter = NearestFilter;
  17881. this.minFilter = NearestFilter;
  17882. this.generateMipmaps = false;
  17883. this.needsUpdate = true;
  17884. }
  17885. }
  17886. FramebufferTexture.prototype.isFramebufferTexture = true;
  17887. class CompressedTexture extends Texture {
  17888. constructor(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  17889. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  17890. this.image = {
  17891. width: width,
  17892. height: height
  17893. };
  17894. this.mipmaps = mipmaps; // no flipping for cube textures
  17895. // (also flipping doesn't work for compressed textures )
  17896. this.flipY = false; // can't generate mipmaps for compressed textures
  17897. // mips must be embedded in DDS files
  17898. this.generateMipmaps = false;
  17899. }
  17900. }
  17901. CompressedTexture.prototype.isCompressedTexture = true;
  17902. class CanvasTexture extends Texture {
  17903. constructor(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  17904. super(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  17905. this.needsUpdate = true;
  17906. }
  17907. }
  17908. CanvasTexture.prototype.isCanvasTexture = true;
  17909. class CircleGeometry extends BufferGeometry {
  17910. constructor(radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2) {
  17911. super();
  17912. this.type = 'CircleGeometry';
  17913. this.parameters = {
  17914. radius: radius,
  17915. segments: segments,
  17916. thetaStart: thetaStart,
  17917. thetaLength: thetaLength
  17918. };
  17919. segments = Math.max(3, segments); // buffers
  17920. const indices = [];
  17921. const vertices = [];
  17922. const normals = [];
  17923. const uvs = []; // helper variables
  17924. const vertex = new Vector3();
  17925. const uv = new Vector2(); // center point
  17926. vertices.push(0, 0, 0);
  17927. normals.push(0, 0, 1);
  17928. uvs.push(0.5, 0.5);
  17929. for (let s = 0, i = 3; s <= segments; s++, i += 3) {
  17930. const segment = thetaStart + s / segments * thetaLength; // vertex
  17931. vertex.x = radius * Math.cos(segment);
  17932. vertex.y = radius * Math.sin(segment);
  17933. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  17934. normals.push(0, 0, 1); // uvs
  17935. uv.x = (vertices[i] / radius + 1) / 2;
  17936. uv.y = (vertices[i + 1] / radius + 1) / 2;
  17937. uvs.push(uv.x, uv.y);
  17938. } // indices
  17939. for (let i = 1; i <= segments; i++) {
  17940. indices.push(i, i + 1, 0);
  17941. } // build geometry
  17942. this.setIndex(indices);
  17943. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17944. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  17945. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  17946. }
  17947. static fromJSON(data) {
  17948. return new CircleGeometry(data.radius, data.segments, data.thetaStart, data.thetaLength);
  17949. }
  17950. }
  17951. class CylinderGeometry extends BufferGeometry {
  17952. constructor(radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  17953. super();
  17954. this.type = 'CylinderGeometry';
  17955. this.parameters = {
  17956. radiusTop: radiusTop,
  17957. radiusBottom: radiusBottom,
  17958. height: height,
  17959. radialSegments: radialSegments,
  17960. heightSegments: heightSegments,
  17961. openEnded: openEnded,
  17962. thetaStart: thetaStart,
  17963. thetaLength: thetaLength
  17964. };
  17965. const scope = this;
  17966. radialSegments = Math.floor(radialSegments);
  17967. heightSegments = Math.floor(heightSegments); // buffers
  17968. const indices = [];
  17969. const vertices = [];
  17970. const normals = [];
  17971. const uvs = []; // helper variables
  17972. let index = 0;
  17973. const indexArray = [];
  17974. const halfHeight = height / 2;
  17975. let groupStart = 0; // generate geometry
  17976. generateTorso();
  17977. if (openEnded === false) {
  17978. if (radiusTop > 0) generateCap(true);
  17979. if (radiusBottom > 0) generateCap(false);
  17980. } // build geometry
  17981. this.setIndex(indices);
  17982. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17983. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  17984. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  17985. function generateTorso() {
  17986. const normal = new Vector3();
  17987. const vertex = new Vector3();
  17988. let groupCount = 0; // this will be used to calculate the normal
  17989. const slope = (radiusBottom - radiusTop) / height; // generate vertices, normals and uvs
  17990. for (let y = 0; y <= heightSegments; y++) {
  17991. const indexRow = [];
  17992. const v = y / heightSegments; // calculate the radius of the current row
  17993. const radius = v * (radiusBottom - radiusTop) + radiusTop;
  17994. for (let x = 0; x <= radialSegments; x++) {
  17995. const u = x / radialSegments;
  17996. const theta = u * thetaLength + thetaStart;
  17997. const sinTheta = Math.sin(theta);
  17998. const cosTheta = Math.cos(theta); // vertex
  17999. vertex.x = radius * sinTheta;
  18000. vertex.y = -v * height + halfHeight;
  18001. vertex.z = radius * cosTheta;
  18002. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  18003. normal.set(sinTheta, slope, cosTheta).normalize();
  18004. normals.push(normal.x, normal.y, normal.z); // uv
  18005. uvs.push(u, 1 - v); // save index of vertex in respective row
  18006. indexRow.push(index++);
  18007. } // now save vertices of the row in our index array
  18008. indexArray.push(indexRow);
  18009. } // generate indices
  18010. for (let x = 0; x < radialSegments; x++) {
  18011. for (let y = 0; y < heightSegments; y++) {
  18012. // we use the index array to access the correct indices
  18013. const a = indexArray[y][x];
  18014. const b = indexArray[y + 1][x];
  18015. const c = indexArray[y + 1][x + 1];
  18016. const d = indexArray[y][x + 1]; // faces
  18017. indices.push(a, b, d);
  18018. indices.push(b, c, d); // update group counter
  18019. groupCount += 6;
  18020. }
  18021. } // add a group to the geometry. this will ensure multi material support
  18022. scope.addGroup(groupStart, groupCount, 0); // calculate new start value for groups
  18023. groupStart += groupCount;
  18024. }
  18025. function generateCap(top) {
  18026. // save the index of the first center vertex
  18027. const centerIndexStart = index;
  18028. const uv = new Vector2();
  18029. const vertex = new Vector3();
  18030. let groupCount = 0;
  18031. const radius = top === true ? radiusTop : radiusBottom;
  18032. const sign = top === true ? 1 : -1; // first we generate the center vertex data of the cap.
  18033. // because the geometry needs one set of uvs per face,
  18034. // we must generate a center vertex per face/segment
  18035. for (let x = 1; x <= radialSegments; x++) {
  18036. // vertex
  18037. vertices.push(0, halfHeight * sign, 0); // normal
  18038. normals.push(0, sign, 0); // uv
  18039. uvs.push(0.5, 0.5); // increase index
  18040. index++;
  18041. } // save the index of the last center vertex
  18042. const centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvs
  18043. for (let x = 0; x <= radialSegments; x++) {
  18044. const u = x / radialSegments;
  18045. const theta = u * thetaLength + thetaStart;
  18046. const cosTheta = Math.cos(theta);
  18047. const sinTheta = Math.sin(theta); // vertex
  18048. vertex.x = radius * sinTheta;
  18049. vertex.y = halfHeight * sign;
  18050. vertex.z = radius * cosTheta;
  18051. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  18052. normals.push(0, sign, 0); // uv
  18053. uv.x = cosTheta * 0.5 + 0.5;
  18054. uv.y = sinTheta * 0.5 * sign + 0.5;
  18055. uvs.push(uv.x, uv.y); // increase index
  18056. index++;
  18057. } // generate indices
  18058. for (let x = 0; x < radialSegments; x++) {
  18059. const c = centerIndexStart + x;
  18060. const i = centerIndexEnd + x;
  18061. if (top === true) {
  18062. // face top
  18063. indices.push(i, i + 1, c);
  18064. } else {
  18065. // face bottom
  18066. indices.push(i + 1, i, c);
  18067. }
  18068. groupCount += 3;
  18069. } // add a group to the geometry. this will ensure multi material support
  18070. scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); // calculate new start value for groups
  18071. groupStart += groupCount;
  18072. }
  18073. }
  18074. static fromJSON(data) {
  18075. return new CylinderGeometry(data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  18076. }
  18077. }
  18078. class ConeGeometry extends CylinderGeometry {
  18079. constructor(radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  18080. super(0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  18081. this.type = 'ConeGeometry';
  18082. this.parameters = {
  18083. radius: radius,
  18084. height: height,
  18085. radialSegments: radialSegments,
  18086. heightSegments: heightSegments,
  18087. openEnded: openEnded,
  18088. thetaStart: thetaStart,
  18089. thetaLength: thetaLength
  18090. };
  18091. }
  18092. static fromJSON(data) {
  18093. return new ConeGeometry(data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  18094. }
  18095. }
  18096. class PolyhedronGeometry extends BufferGeometry {
  18097. constructor(vertices = [], indices = [], radius = 1, detail = 0) {
  18098. super();
  18099. this.type = 'PolyhedronGeometry';
  18100. this.parameters = {
  18101. vertices: vertices,
  18102. indices: indices,
  18103. radius: radius,
  18104. detail: detail
  18105. }; // default buffer data
  18106. const vertexBuffer = [];
  18107. const uvBuffer = []; // the subdivision creates the vertex buffer data
  18108. subdivide(detail); // all vertices should lie on a conceptual sphere with a given radius
  18109. applyRadius(radius); // finally, create the uv data
  18110. generateUVs(); // build non-indexed geometry
  18111. this.setAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));
  18112. this.setAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));
  18113. this.setAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));
  18114. if (detail === 0) {
  18115. this.computeVertexNormals(); // flat normals
  18116. } else {
  18117. this.normalizeNormals(); // smooth normals
  18118. } // helper functions
  18119. function subdivide(detail) {
  18120. const a = new Vector3();
  18121. const b = new Vector3();
  18122. const c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail value
  18123. for (let i = 0; i < indices.length; i += 3) {
  18124. // get the vertices of the face
  18125. getVertexByIndex(indices[i + 0], a);
  18126. getVertexByIndex(indices[i + 1], b);
  18127. getVertexByIndex(indices[i + 2], c); // perform subdivision
  18128. subdivideFace(a, b, c, detail);
  18129. }
  18130. }
  18131. function subdivideFace(a, b, c, detail) {
  18132. const cols = detail + 1; // we use this multidimensional array as a data structure for creating the subdivision
  18133. const v = []; // construct all of the vertices for this subdivision
  18134. for (let i = 0; i <= cols; i++) {
  18135. v[i] = [];
  18136. const aj = a.clone().lerp(c, i / cols);
  18137. const bj = b.clone().lerp(c, i / cols);
  18138. const rows = cols - i;
  18139. for (let j = 0; j <= rows; j++) {
  18140. if (j === 0 && i === cols) {
  18141. v[i][j] = aj;
  18142. } else {
  18143. v[i][j] = aj.clone().lerp(bj, j / rows);
  18144. }
  18145. }
  18146. } // construct all of the faces
  18147. for (let i = 0; i < cols; i++) {
  18148. for (let j = 0; j < 2 * (cols - i) - 1; j++) {
  18149. const k = Math.floor(j / 2);
  18150. if (j % 2 === 0) {
  18151. pushVertex(v[i][k + 1]);
  18152. pushVertex(v[i + 1][k]);
  18153. pushVertex(v[i][k]);
  18154. } else {
  18155. pushVertex(v[i][k + 1]);
  18156. pushVertex(v[i + 1][k + 1]);
  18157. pushVertex(v[i + 1][k]);
  18158. }
  18159. }
  18160. }
  18161. }
  18162. function applyRadius(radius) {
  18163. const vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertex
  18164. for (let i = 0; i < vertexBuffer.length; i += 3) {
  18165. vertex.x = vertexBuffer[i + 0];
  18166. vertex.y = vertexBuffer[i + 1];
  18167. vertex.z = vertexBuffer[i + 2];
  18168. vertex.normalize().multiplyScalar(radius);
  18169. vertexBuffer[i + 0] = vertex.x;
  18170. vertexBuffer[i + 1] = vertex.y;
  18171. vertexBuffer[i + 2] = vertex.z;
  18172. }
  18173. }
  18174. function generateUVs() {
  18175. const vertex = new Vector3();
  18176. for (let i = 0; i < vertexBuffer.length; i += 3) {
  18177. vertex.x = vertexBuffer[i + 0];
  18178. vertex.y = vertexBuffer[i + 1];
  18179. vertex.z = vertexBuffer[i + 2];
  18180. const u = azimuth(vertex) / 2 / Math.PI + 0.5;
  18181. const v = inclination(vertex) / Math.PI + 0.5;
  18182. uvBuffer.push(u, 1 - v);
  18183. }
  18184. correctUVs();
  18185. correctSeam();
  18186. }
  18187. function correctSeam() {
  18188. // handle case when face straddles the seam, see #3269
  18189. for (let i = 0; i < uvBuffer.length; i += 6) {
  18190. // uv data of a single face
  18191. const x0 = uvBuffer[i + 0];
  18192. const x1 = uvBuffer[i + 2];
  18193. const x2 = uvBuffer[i + 4];
  18194. const max = Math.max(x0, x1, x2);
  18195. const min = Math.min(x0, x1, x2); // 0.9 is somewhat arbitrary
  18196. if (max > 0.9 && min < 0.1) {
  18197. if (x0 < 0.2) uvBuffer[i + 0] += 1;
  18198. if (x1 < 0.2) uvBuffer[i + 2] += 1;
  18199. if (x2 < 0.2) uvBuffer[i + 4] += 1;
  18200. }
  18201. }
  18202. }
  18203. function pushVertex(vertex) {
  18204. vertexBuffer.push(vertex.x, vertex.y, vertex.z);
  18205. }
  18206. function getVertexByIndex(index, vertex) {
  18207. const stride = index * 3;
  18208. vertex.x = vertices[stride + 0];
  18209. vertex.y = vertices[stride + 1];
  18210. vertex.z = vertices[stride + 2];
  18211. }
  18212. function correctUVs() {
  18213. const a = new Vector3();
  18214. const b = new Vector3();
  18215. const c = new Vector3();
  18216. const centroid = new Vector3();
  18217. const uvA = new Vector2();
  18218. const uvB = new Vector2();
  18219. const uvC = new Vector2();
  18220. for (let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {
  18221. a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);
  18222. b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);
  18223. c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);
  18224. uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);
  18225. uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);
  18226. uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);
  18227. centroid.copy(a).add(b).add(c).divideScalar(3);
  18228. const azi = azimuth(centroid);
  18229. correctUV(uvA, j + 0, a, azi);
  18230. correctUV(uvB, j + 2, b, azi);
  18231. correctUV(uvC, j + 4, c, azi);
  18232. }
  18233. }
  18234. function correctUV(uv, stride, vector, azimuth) {
  18235. if (azimuth < 0 && uv.x === 1) {
  18236. uvBuffer[stride] = uv.x - 1;
  18237. }
  18238. if (vector.x === 0 && vector.z === 0) {
  18239. uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
  18240. }
  18241. } // Angle around the Y axis, counter-clockwise when looking from above.
  18242. function azimuth(vector) {
  18243. return Math.atan2(vector.z, -vector.x);
  18244. } // Angle above the XZ plane.
  18245. function inclination(vector) {
  18246. return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
  18247. }
  18248. }
  18249. static fromJSON(data) {
  18250. return new PolyhedronGeometry(data.vertices, data.indices, data.radius, data.details);
  18251. }
  18252. }
  18253. class DodecahedronGeometry extends PolyhedronGeometry {
  18254. constructor(radius = 1, detail = 0) {
  18255. const t = (1 + Math.sqrt(5)) / 2;
  18256. const r = 1 / t;
  18257. const vertices = [// (±1, ±1, ±1)
  18258. -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/φ, ±φ)
  18259. 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t, // (±1/φ, ±φ, 0)
  18260. -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0, // (±φ, 0, ±1/φ)
  18261. -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];
  18262. 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];
  18263. super(vertices, indices, radius, detail);
  18264. this.type = 'DodecahedronGeometry';
  18265. this.parameters = {
  18266. radius: radius,
  18267. detail: detail
  18268. };
  18269. }
  18270. static fromJSON(data) {
  18271. return new DodecahedronGeometry(data.radius, data.detail);
  18272. }
  18273. }
  18274. const _v0 = new Vector3();
  18275. const _v1$1 = new Vector3();
  18276. const _normal = new Vector3();
  18277. const _triangle = new Triangle();
  18278. class EdgesGeometry extends BufferGeometry {
  18279. constructor(geometry = null, thresholdAngle = 1) {
  18280. super();
  18281. this.type = 'EdgesGeometry';
  18282. this.parameters = {
  18283. geometry: geometry,
  18284. thresholdAngle: thresholdAngle
  18285. };
  18286. if (geometry !== null) {
  18287. const precisionPoints = 4;
  18288. const precision = Math.pow(10, precisionPoints);
  18289. const thresholdDot = Math.cos(DEG2RAD * thresholdAngle);
  18290. const indexAttr = geometry.getIndex();
  18291. const positionAttr = geometry.getAttribute('position');
  18292. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  18293. const indexArr = [0, 0, 0];
  18294. const vertKeys = ['a', 'b', 'c'];
  18295. const hashes = new Array(3);
  18296. const edgeData = {};
  18297. const vertices = [];
  18298. for (let i = 0; i < indexCount; i += 3) {
  18299. if (indexAttr) {
  18300. indexArr[0] = indexAttr.getX(i);
  18301. indexArr[1] = indexAttr.getX(i + 1);
  18302. indexArr[2] = indexAttr.getX(i + 2);
  18303. } else {
  18304. indexArr[0] = i;
  18305. indexArr[1] = i + 1;
  18306. indexArr[2] = i + 2;
  18307. }
  18308. const {
  18309. a,
  18310. b,
  18311. c
  18312. } = _triangle;
  18313. a.fromBufferAttribute(positionAttr, indexArr[0]);
  18314. b.fromBufferAttribute(positionAttr, indexArr[1]);
  18315. c.fromBufferAttribute(positionAttr, indexArr[2]);
  18316. _triangle.getNormal(_normal); // create hashes for the edge from the vertices
  18317. hashes[0] = `${Math.round(a.x * precision)},${Math.round(a.y * precision)},${Math.round(a.z * precision)}`;
  18318. hashes[1] = `${Math.round(b.x * precision)},${Math.round(b.y * precision)},${Math.round(b.z * precision)}`;
  18319. hashes[2] = `${Math.round(c.x * precision)},${Math.round(c.y * precision)},${Math.round(c.z * precision)}`; // skip degenerate triangles
  18320. if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) {
  18321. continue;
  18322. } // iterate over every edge
  18323. for (let j = 0; j < 3; j++) {
  18324. // get the first and next vertex making up the edge
  18325. const jNext = (j + 1) % 3;
  18326. const vecHash0 = hashes[j];
  18327. const vecHash1 = hashes[jNext];
  18328. const v0 = _triangle[vertKeys[j]];
  18329. const v1 = _triangle[vertKeys[jNext]];
  18330. const hash = `${vecHash0}_${vecHash1}`;
  18331. const reverseHash = `${vecHash1}_${vecHash0}`;
  18332. if (reverseHash in edgeData && edgeData[reverseHash]) {
  18333. // if we found a sibling edge add it into the vertex array if
  18334. // it meets the angle threshold and delete the edge from the map.
  18335. if (_normal.dot(edgeData[reverseHash].normal) <= thresholdDot) {
  18336. vertices.push(v0.x, v0.y, v0.z);
  18337. vertices.push(v1.x, v1.y, v1.z);
  18338. }
  18339. edgeData[reverseHash] = null;
  18340. } else if (!(hash in edgeData)) {
  18341. // if we've already got an edge here then skip adding a new one
  18342. edgeData[hash] = {
  18343. index0: indexArr[j],
  18344. index1: indexArr[jNext],
  18345. normal: _normal.clone()
  18346. };
  18347. }
  18348. }
  18349. } // iterate over all remaining, unmatched edges and add them to the vertex array
  18350. for (const key in edgeData) {
  18351. if (edgeData[key]) {
  18352. const {
  18353. index0,
  18354. index1
  18355. } = edgeData[key];
  18356. _v0.fromBufferAttribute(positionAttr, index0);
  18357. _v1$1.fromBufferAttribute(positionAttr, index1);
  18358. vertices.push(_v0.x, _v0.y, _v0.z);
  18359. vertices.push(_v1$1.x, _v1$1.y, _v1$1.z);
  18360. }
  18361. }
  18362. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18363. }
  18364. }
  18365. }
  18366. /**
  18367. * Extensible curve object.
  18368. *
  18369. * Some common of curve methods:
  18370. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  18371. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  18372. * .getPoints(), .getSpacedPoints()
  18373. * .getLength()
  18374. * .updateArcLengths()
  18375. *
  18376. * This following curves inherit from THREE.Curve:
  18377. *
  18378. * -- 2D curves --
  18379. * THREE.ArcCurve
  18380. * THREE.CubicBezierCurve
  18381. * THREE.EllipseCurve
  18382. * THREE.LineCurve
  18383. * THREE.QuadraticBezierCurve
  18384. * THREE.SplineCurve
  18385. *
  18386. * -- 3D curves --
  18387. * THREE.CatmullRomCurve3
  18388. * THREE.CubicBezierCurve3
  18389. * THREE.LineCurve3
  18390. * THREE.QuadraticBezierCurve3
  18391. *
  18392. * A series of curves can be represented as a THREE.CurvePath.
  18393. *
  18394. **/
  18395. class Curve {
  18396. constructor() {
  18397. this.type = 'Curve';
  18398. this.arcLengthDivisions = 200;
  18399. } // Virtual base class method to overwrite and implement in subclasses
  18400. // - t [0 .. 1]
  18401. getPoint() {
  18402. console.warn('THREE.Curve: .getPoint() not implemented.');
  18403. return null;
  18404. } // Get point at relative position in curve according to arc length
  18405. // - u [0 .. 1]
  18406. getPointAt(u, optionalTarget) {
  18407. const t = this.getUtoTmapping(u);
  18408. return this.getPoint(t, optionalTarget);
  18409. } // Get sequence of points using getPoint( t )
  18410. getPoints(divisions = 5) {
  18411. const points = [];
  18412. for (let d = 0; d <= divisions; d++) {
  18413. points.push(this.getPoint(d / divisions));
  18414. }
  18415. return points;
  18416. } // Get sequence of points using getPointAt( u )
  18417. getSpacedPoints(divisions = 5) {
  18418. const points = [];
  18419. for (let d = 0; d <= divisions; d++) {
  18420. points.push(this.getPointAt(d / divisions));
  18421. }
  18422. return points;
  18423. } // Get total curve arc length
  18424. getLength() {
  18425. const lengths = this.getLengths();
  18426. return lengths[lengths.length - 1];
  18427. } // Get list of cumulative segment lengths
  18428. getLengths(divisions = this.arcLengthDivisions) {
  18429. if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
  18430. return this.cacheArcLengths;
  18431. }
  18432. this.needsUpdate = false;
  18433. const cache = [];
  18434. let current,
  18435. last = this.getPoint(0);
  18436. let sum = 0;
  18437. cache.push(0);
  18438. for (let p = 1; p <= divisions; p++) {
  18439. current = this.getPoint(p / divisions);
  18440. sum += current.distanceTo(last);
  18441. cache.push(sum);
  18442. last = current;
  18443. }
  18444. this.cacheArcLengths = cache;
  18445. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  18446. }
  18447. updateArcLengths() {
  18448. this.needsUpdate = true;
  18449. this.getLengths();
  18450. } // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  18451. getUtoTmapping(u, distance) {
  18452. const arcLengths = this.getLengths();
  18453. let i = 0;
  18454. const il = arcLengths.length;
  18455. let targetArcLength; // The targeted u distance value to get
  18456. if (distance) {
  18457. targetArcLength = distance;
  18458. } else {
  18459. targetArcLength = u * arcLengths[il - 1];
  18460. } // binary search for the index with largest value smaller than target u distance
  18461. let low = 0,
  18462. high = il - 1,
  18463. comparison;
  18464. while (low <= high) {
  18465. 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
  18466. comparison = arcLengths[i] - targetArcLength;
  18467. if (comparison < 0) {
  18468. low = i + 1;
  18469. } else if (comparison > 0) {
  18470. high = i - 1;
  18471. } else {
  18472. high = i;
  18473. break; // DONE
  18474. }
  18475. }
  18476. i = high;
  18477. if (arcLengths[i] === targetArcLength) {
  18478. return i / (il - 1);
  18479. } // we could get finer grain at lengths, or use simple interpolation between two points
  18480. const lengthBefore = arcLengths[i];
  18481. const lengthAfter = arcLengths[i + 1];
  18482. const segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points
  18483. const segmentFraction = (targetArcLength - lengthBefore) / segmentLength; // add that fractional amount to t
  18484. const t = (i + segmentFraction) / (il - 1);
  18485. return t;
  18486. } // Returns a unit vector tangent at t
  18487. // In case any sub curve does not implement its tangent derivation,
  18488. // 2 points a small delta apart will be used to find its gradient
  18489. // which seems to give a reasonable approximation
  18490. getTangent(t, optionalTarget) {
  18491. const delta = 0.0001;
  18492. let t1 = t - delta;
  18493. let t2 = t + delta; // Capping in case of danger
  18494. if (t1 < 0) t1 = 0;
  18495. if (t2 > 1) t2 = 1;
  18496. const pt1 = this.getPoint(t1);
  18497. const pt2 = this.getPoint(t2);
  18498. const tangent = optionalTarget || (pt1.isVector2 ? new Vector2() : new Vector3());
  18499. tangent.copy(pt2).sub(pt1).normalize();
  18500. return tangent;
  18501. }
  18502. getTangentAt(u, optionalTarget) {
  18503. const t = this.getUtoTmapping(u);
  18504. return this.getTangent(t, optionalTarget);
  18505. }
  18506. computeFrenetFrames(segments, closed) {
  18507. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  18508. const normal = new Vector3();
  18509. const tangents = [];
  18510. const normals = [];
  18511. const binormals = [];
  18512. const vec = new Vector3();
  18513. const mat = new Matrix4(); // compute the tangent vectors for each segment on the curve
  18514. for (let i = 0; i <= segments; i++) {
  18515. const u = i / segments;
  18516. tangents[i] = this.getTangentAt(u, new Vector3());
  18517. } // select an initial normal vector perpendicular to the first tangent vector,
  18518. // and in the direction of the minimum tangent xyz component
  18519. normals[0] = new Vector3();
  18520. binormals[0] = new Vector3();
  18521. let min = Number.MAX_VALUE;
  18522. const tx = Math.abs(tangents[0].x);
  18523. const ty = Math.abs(tangents[0].y);
  18524. const tz = Math.abs(tangents[0].z);
  18525. if (tx <= min) {
  18526. min = tx;
  18527. normal.set(1, 0, 0);
  18528. }
  18529. if (ty <= min) {
  18530. min = ty;
  18531. normal.set(0, 1, 0);
  18532. }
  18533. if (tz <= min) {
  18534. normal.set(0, 0, 1);
  18535. }
  18536. vec.crossVectors(tangents[0], normal).normalize();
  18537. normals[0].crossVectors(tangents[0], vec);
  18538. binormals[0].crossVectors(tangents[0], normals[0]); // compute the slowly-varying normal and binormal vectors for each segment on the curve
  18539. for (let i = 1; i <= segments; i++) {
  18540. normals[i] = normals[i - 1].clone();
  18541. binormals[i] = binormals[i - 1].clone();
  18542. vec.crossVectors(tangents[i - 1], tangents[i]);
  18543. if (vec.length() > Number.EPSILON) {
  18544. vec.normalize();
  18545. const theta = Math.acos(clamp(tangents[i - 1].dot(tangents[i]), -1, 1)); // clamp for floating pt errors
  18546. normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta));
  18547. }
  18548. binormals[i].crossVectors(tangents[i], normals[i]);
  18549. } // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  18550. if (closed === true) {
  18551. let theta = Math.acos(clamp(normals[0].dot(normals[segments]), -1, 1));
  18552. theta /= segments;
  18553. if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
  18554. theta = -theta;
  18555. }
  18556. for (let i = 1; i <= segments; i++) {
  18557. // twist a little...
  18558. normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i));
  18559. binormals[i].crossVectors(tangents[i], normals[i]);
  18560. }
  18561. }
  18562. return {
  18563. tangents: tangents,
  18564. normals: normals,
  18565. binormals: binormals
  18566. };
  18567. }
  18568. clone() {
  18569. return new this.constructor().copy(this);
  18570. }
  18571. copy(source) {
  18572. this.arcLengthDivisions = source.arcLengthDivisions;
  18573. return this;
  18574. }
  18575. toJSON() {
  18576. const data = {
  18577. metadata: {
  18578. version: 4.5,
  18579. type: 'Curve',
  18580. generator: 'Curve.toJSON'
  18581. }
  18582. };
  18583. data.arcLengthDivisions = this.arcLengthDivisions;
  18584. data.type = this.type;
  18585. return data;
  18586. }
  18587. fromJSON(json) {
  18588. this.arcLengthDivisions = json.arcLengthDivisions;
  18589. return this;
  18590. }
  18591. }
  18592. class EllipseCurve extends Curve {
  18593. constructor(aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0) {
  18594. super();
  18595. this.type = 'EllipseCurve';
  18596. this.aX = aX;
  18597. this.aY = aY;
  18598. this.xRadius = xRadius;
  18599. this.yRadius = yRadius;
  18600. this.aStartAngle = aStartAngle;
  18601. this.aEndAngle = aEndAngle;
  18602. this.aClockwise = aClockwise;
  18603. this.aRotation = aRotation;
  18604. }
  18605. getPoint(t, optionalTarget) {
  18606. const point = optionalTarget || new Vector2();
  18607. const twoPi = Math.PI * 2;
  18608. let deltaAngle = this.aEndAngle - this.aStartAngle;
  18609. const samePoints = Math.abs(deltaAngle) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI
  18610. while (deltaAngle < 0) deltaAngle += twoPi;
  18611. while (deltaAngle > twoPi) deltaAngle -= twoPi;
  18612. if (deltaAngle < Number.EPSILON) {
  18613. if (samePoints) {
  18614. deltaAngle = 0;
  18615. } else {
  18616. deltaAngle = twoPi;
  18617. }
  18618. }
  18619. if (this.aClockwise === true && !samePoints) {
  18620. if (deltaAngle === twoPi) {
  18621. deltaAngle = -twoPi;
  18622. } else {
  18623. deltaAngle = deltaAngle - twoPi;
  18624. }
  18625. }
  18626. const angle = this.aStartAngle + t * deltaAngle;
  18627. let x = this.aX + this.xRadius * Math.cos(angle);
  18628. let y = this.aY + this.yRadius * Math.sin(angle);
  18629. if (this.aRotation !== 0) {
  18630. const cos = Math.cos(this.aRotation);
  18631. const sin = Math.sin(this.aRotation);
  18632. const tx = x - this.aX;
  18633. const ty = y - this.aY; // Rotate the point about the center of the ellipse.
  18634. x = tx * cos - ty * sin + this.aX;
  18635. y = tx * sin + ty * cos + this.aY;
  18636. }
  18637. return point.set(x, y);
  18638. }
  18639. copy(source) {
  18640. super.copy(source);
  18641. this.aX = source.aX;
  18642. this.aY = source.aY;
  18643. this.xRadius = source.xRadius;
  18644. this.yRadius = source.yRadius;
  18645. this.aStartAngle = source.aStartAngle;
  18646. this.aEndAngle = source.aEndAngle;
  18647. this.aClockwise = source.aClockwise;
  18648. this.aRotation = source.aRotation;
  18649. return this;
  18650. }
  18651. toJSON() {
  18652. const data = super.toJSON();
  18653. data.aX = this.aX;
  18654. data.aY = this.aY;
  18655. data.xRadius = this.xRadius;
  18656. data.yRadius = this.yRadius;
  18657. data.aStartAngle = this.aStartAngle;
  18658. data.aEndAngle = this.aEndAngle;
  18659. data.aClockwise = this.aClockwise;
  18660. data.aRotation = this.aRotation;
  18661. return data;
  18662. }
  18663. fromJSON(json) {
  18664. super.fromJSON(json);
  18665. this.aX = json.aX;
  18666. this.aY = json.aY;
  18667. this.xRadius = json.xRadius;
  18668. this.yRadius = json.yRadius;
  18669. this.aStartAngle = json.aStartAngle;
  18670. this.aEndAngle = json.aEndAngle;
  18671. this.aClockwise = json.aClockwise;
  18672. this.aRotation = json.aRotation;
  18673. return this;
  18674. }
  18675. }
  18676. EllipseCurve.prototype.isEllipseCurve = true;
  18677. class ArcCurve extends EllipseCurve {
  18678. constructor(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  18679. super(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  18680. this.type = 'ArcCurve';
  18681. }
  18682. }
  18683. ArcCurve.prototype.isArcCurve = true;
  18684. /**
  18685. * Centripetal CatmullRom Curve - which is useful for avoiding
  18686. * cusps and self-intersections in non-uniform catmull rom curves.
  18687. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  18688. *
  18689. * curve.type accepts centripetal(default), chordal and catmullrom
  18690. * curve.tension is used for catmullrom which defaults to 0.5
  18691. */
  18692. /*
  18693. Based on an optimized c++ solution in
  18694. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  18695. - http://ideone.com/NoEbVM
  18696. This CubicPoly class could be used for reusing some variables and calculations,
  18697. but for three.js curve use, it could be possible inlined and flatten into a single function call
  18698. which can be placed in CurveUtils.
  18699. */
  18700. function CubicPoly() {
  18701. let c0 = 0,
  18702. c1 = 0,
  18703. c2 = 0,
  18704. c3 = 0;
  18705. /*
  18706. * Compute coefficients for a cubic polynomial
  18707. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  18708. * such that
  18709. * p(0) = x0, p(1) = x1
  18710. * and
  18711. * p'(0) = t0, p'(1) = t1.
  18712. */
  18713. function init(x0, x1, t0, t1) {
  18714. c0 = x0;
  18715. c1 = t0;
  18716. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  18717. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  18718. }
  18719. return {
  18720. initCatmullRom: function (x0, x1, x2, x3, tension) {
  18721. init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
  18722. },
  18723. initNonuniformCatmullRom: function (x0, x1, x2, x3, dt0, dt1, dt2) {
  18724. // compute tangents when parameterized in [t1,t2]
  18725. let t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
  18726. let t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; // rescale tangents for parametrization in [0,1]
  18727. t1 *= dt1;
  18728. t2 *= dt1;
  18729. init(x1, x2, t1, t2);
  18730. },
  18731. calc: function (t) {
  18732. const t2 = t * t;
  18733. const t3 = t2 * t;
  18734. return c0 + c1 * t + c2 * t2 + c3 * t3;
  18735. }
  18736. };
  18737. } //
  18738. const tmp = new Vector3();
  18739. const px = new CubicPoly(),
  18740. py = new CubicPoly(),
  18741. pz = new CubicPoly();
  18742. class CatmullRomCurve3 extends Curve {
  18743. constructor(points = [], closed = false, curveType = 'centripetal', tension = 0.5) {
  18744. super();
  18745. this.type = 'CatmullRomCurve3';
  18746. this.points = points;
  18747. this.closed = closed;
  18748. this.curveType = curveType;
  18749. this.tension = tension;
  18750. }
  18751. getPoint(t, optionalTarget = new Vector3()) {
  18752. const point = optionalTarget;
  18753. const points = this.points;
  18754. const l = points.length;
  18755. const p = (l - (this.closed ? 0 : 1)) * t;
  18756. let intPoint = Math.floor(p);
  18757. let weight = p - intPoint;
  18758. if (this.closed) {
  18759. intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;
  18760. } else if (weight === 0 && intPoint === l - 1) {
  18761. intPoint = l - 2;
  18762. weight = 1;
  18763. }
  18764. let p0, p3; // 4 points (p1 & p2 defined below)
  18765. if (this.closed || intPoint > 0) {
  18766. p0 = points[(intPoint - 1) % l];
  18767. } else {
  18768. // extrapolate first point
  18769. tmp.subVectors(points[0], points[1]).add(points[0]);
  18770. p0 = tmp;
  18771. }
  18772. const p1 = points[intPoint % l];
  18773. const p2 = points[(intPoint + 1) % l];
  18774. if (this.closed || intPoint + 2 < l) {
  18775. p3 = points[(intPoint + 2) % l];
  18776. } else {
  18777. // extrapolate last point
  18778. tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
  18779. p3 = tmp;
  18780. }
  18781. if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
  18782. // init Centripetal / Chordal Catmull-Rom
  18783. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  18784. let dt0 = Math.pow(p0.distanceToSquared(p1), pow);
  18785. let dt1 = Math.pow(p1.distanceToSquared(p2), pow);
  18786. let dt2 = Math.pow(p2.distanceToSquared(p3), pow); // safety check for repeated points
  18787. if (dt1 < 1e-4) dt1 = 1.0;
  18788. if (dt0 < 1e-4) dt0 = dt1;
  18789. if (dt2 < 1e-4) dt2 = dt1;
  18790. px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);
  18791. py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);
  18792. pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);
  18793. } else if (this.curveType === 'catmullrom') {
  18794. px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);
  18795. py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);
  18796. pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);
  18797. }
  18798. point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
  18799. return point;
  18800. }
  18801. copy(source) {
  18802. super.copy(source);
  18803. this.points = [];
  18804. for (let i = 0, l = source.points.length; i < l; i++) {
  18805. const point = source.points[i];
  18806. this.points.push(point.clone());
  18807. }
  18808. this.closed = source.closed;
  18809. this.curveType = source.curveType;
  18810. this.tension = source.tension;
  18811. return this;
  18812. }
  18813. toJSON() {
  18814. const data = super.toJSON();
  18815. data.points = [];
  18816. for (let i = 0, l = this.points.length; i < l; i++) {
  18817. const point = this.points[i];
  18818. data.points.push(point.toArray());
  18819. }
  18820. data.closed = this.closed;
  18821. data.curveType = this.curveType;
  18822. data.tension = this.tension;
  18823. return data;
  18824. }
  18825. fromJSON(json) {
  18826. super.fromJSON(json);
  18827. this.points = [];
  18828. for (let i = 0, l = json.points.length; i < l; i++) {
  18829. const point = json.points[i];
  18830. this.points.push(new Vector3().fromArray(point));
  18831. }
  18832. this.closed = json.closed;
  18833. this.curveType = json.curveType;
  18834. this.tension = json.tension;
  18835. return this;
  18836. }
  18837. }
  18838. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  18839. /**
  18840. * Bezier Curves formulas obtained from
  18841. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  18842. */
  18843. function CatmullRom(t, p0, p1, p2, p3) {
  18844. const v0 = (p2 - p0) * 0.5;
  18845. const v1 = (p3 - p1) * 0.5;
  18846. const t2 = t * t;
  18847. const t3 = t * t2;
  18848. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  18849. } //
  18850. function QuadraticBezierP0(t, p) {
  18851. const k = 1 - t;
  18852. return k * k * p;
  18853. }
  18854. function QuadraticBezierP1(t, p) {
  18855. return 2 * (1 - t) * t * p;
  18856. }
  18857. function QuadraticBezierP2(t, p) {
  18858. return t * t * p;
  18859. }
  18860. function QuadraticBezier(t, p0, p1, p2) {
  18861. return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);
  18862. } //
  18863. function CubicBezierP0(t, p) {
  18864. const k = 1 - t;
  18865. return k * k * k * p;
  18866. }
  18867. function CubicBezierP1(t, p) {
  18868. const k = 1 - t;
  18869. return 3 * k * k * t * p;
  18870. }
  18871. function CubicBezierP2(t, p) {
  18872. return 3 * (1 - t) * t * t * p;
  18873. }
  18874. function CubicBezierP3(t, p) {
  18875. return t * t * t * p;
  18876. }
  18877. function CubicBezier(t, p0, p1, p2, p3) {
  18878. return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);
  18879. }
  18880. class CubicBezierCurve extends Curve {
  18881. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2()) {
  18882. super();
  18883. this.type = 'CubicBezierCurve';
  18884. this.v0 = v0;
  18885. this.v1 = v1;
  18886. this.v2 = v2;
  18887. this.v3 = v3;
  18888. }
  18889. getPoint(t, optionalTarget = new Vector2()) {
  18890. const point = optionalTarget;
  18891. const v0 = this.v0,
  18892. v1 = this.v1,
  18893. v2 = this.v2,
  18894. v3 = this.v3;
  18895. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
  18896. return point;
  18897. }
  18898. copy(source) {
  18899. super.copy(source);
  18900. this.v0.copy(source.v0);
  18901. this.v1.copy(source.v1);
  18902. this.v2.copy(source.v2);
  18903. this.v3.copy(source.v3);
  18904. return this;
  18905. }
  18906. toJSON() {
  18907. const data = super.toJSON();
  18908. data.v0 = this.v0.toArray();
  18909. data.v1 = this.v1.toArray();
  18910. data.v2 = this.v2.toArray();
  18911. data.v3 = this.v3.toArray();
  18912. return data;
  18913. }
  18914. fromJSON(json) {
  18915. super.fromJSON(json);
  18916. this.v0.fromArray(json.v0);
  18917. this.v1.fromArray(json.v1);
  18918. this.v2.fromArray(json.v2);
  18919. this.v3.fromArray(json.v3);
  18920. return this;
  18921. }
  18922. }
  18923. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  18924. class CubicBezierCurve3 extends Curve {
  18925. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3()) {
  18926. super();
  18927. this.type = 'CubicBezierCurve3';
  18928. this.v0 = v0;
  18929. this.v1 = v1;
  18930. this.v2 = v2;
  18931. this.v3 = v3;
  18932. }
  18933. getPoint(t, optionalTarget = new Vector3()) {
  18934. const point = optionalTarget;
  18935. const v0 = this.v0,
  18936. v1 = this.v1,
  18937. v2 = this.v2,
  18938. v3 = this.v3;
  18939. 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));
  18940. return point;
  18941. }
  18942. copy(source) {
  18943. super.copy(source);
  18944. this.v0.copy(source.v0);
  18945. this.v1.copy(source.v1);
  18946. this.v2.copy(source.v2);
  18947. this.v3.copy(source.v3);
  18948. return this;
  18949. }
  18950. toJSON() {
  18951. const data = super.toJSON();
  18952. data.v0 = this.v0.toArray();
  18953. data.v1 = this.v1.toArray();
  18954. data.v2 = this.v2.toArray();
  18955. data.v3 = this.v3.toArray();
  18956. return data;
  18957. }
  18958. fromJSON(json) {
  18959. super.fromJSON(json);
  18960. this.v0.fromArray(json.v0);
  18961. this.v1.fromArray(json.v1);
  18962. this.v2.fromArray(json.v2);
  18963. this.v3.fromArray(json.v3);
  18964. return this;
  18965. }
  18966. }
  18967. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  18968. class LineCurve extends Curve {
  18969. constructor(v1 = new Vector2(), v2 = new Vector2()) {
  18970. super();
  18971. this.type = 'LineCurve';
  18972. this.v1 = v1;
  18973. this.v2 = v2;
  18974. }
  18975. getPoint(t, optionalTarget = new Vector2()) {
  18976. const point = optionalTarget;
  18977. if (t === 1) {
  18978. point.copy(this.v2);
  18979. } else {
  18980. point.copy(this.v2).sub(this.v1);
  18981. point.multiplyScalar(t).add(this.v1);
  18982. }
  18983. return point;
  18984. } // Line curve is linear, so we can overwrite default getPointAt
  18985. getPointAt(u, optionalTarget) {
  18986. return this.getPoint(u, optionalTarget);
  18987. }
  18988. getTangent(t, optionalTarget) {
  18989. const tangent = optionalTarget || new Vector2();
  18990. tangent.copy(this.v2).sub(this.v1).normalize();
  18991. return tangent;
  18992. }
  18993. copy(source) {
  18994. super.copy(source);
  18995. this.v1.copy(source.v1);
  18996. this.v2.copy(source.v2);
  18997. return this;
  18998. }
  18999. toJSON() {
  19000. const data = super.toJSON();
  19001. data.v1 = this.v1.toArray();
  19002. data.v2 = this.v2.toArray();
  19003. return data;
  19004. }
  19005. fromJSON(json) {
  19006. super.fromJSON(json);
  19007. this.v1.fromArray(json.v1);
  19008. this.v2.fromArray(json.v2);
  19009. return this;
  19010. }
  19011. }
  19012. LineCurve.prototype.isLineCurve = true;
  19013. class LineCurve3 extends Curve {
  19014. constructor(v1 = new Vector3(), v2 = new Vector3()) {
  19015. super();
  19016. this.type = 'LineCurve3';
  19017. this.isLineCurve3 = true;
  19018. this.v1 = v1;
  19019. this.v2 = v2;
  19020. }
  19021. getPoint(t, optionalTarget = new Vector3()) {
  19022. const point = optionalTarget;
  19023. if (t === 1) {
  19024. point.copy(this.v2);
  19025. } else {
  19026. point.copy(this.v2).sub(this.v1);
  19027. point.multiplyScalar(t).add(this.v1);
  19028. }
  19029. return point;
  19030. } // Line curve is linear, so we can overwrite default getPointAt
  19031. getPointAt(u, optionalTarget) {
  19032. return this.getPoint(u, optionalTarget);
  19033. }
  19034. copy(source) {
  19035. super.copy(source);
  19036. this.v1.copy(source.v1);
  19037. this.v2.copy(source.v2);
  19038. return this;
  19039. }
  19040. toJSON() {
  19041. const data = super.toJSON();
  19042. data.v1 = this.v1.toArray();
  19043. data.v2 = this.v2.toArray();
  19044. return data;
  19045. }
  19046. fromJSON(json) {
  19047. super.fromJSON(json);
  19048. this.v1.fromArray(json.v1);
  19049. this.v2.fromArray(json.v2);
  19050. return this;
  19051. }
  19052. }
  19053. class QuadraticBezierCurve extends Curve {
  19054. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2()) {
  19055. super();
  19056. this.type = 'QuadraticBezierCurve';
  19057. this.v0 = v0;
  19058. this.v1 = v1;
  19059. this.v2 = v2;
  19060. }
  19061. getPoint(t, optionalTarget = new Vector2()) {
  19062. const point = optionalTarget;
  19063. const v0 = this.v0,
  19064. v1 = this.v1,
  19065. v2 = this.v2;
  19066. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
  19067. return point;
  19068. }
  19069. copy(source) {
  19070. super.copy(source);
  19071. this.v0.copy(source.v0);
  19072. this.v1.copy(source.v1);
  19073. this.v2.copy(source.v2);
  19074. return this;
  19075. }
  19076. toJSON() {
  19077. const data = super.toJSON();
  19078. data.v0 = this.v0.toArray();
  19079. data.v1 = this.v1.toArray();
  19080. data.v2 = this.v2.toArray();
  19081. return data;
  19082. }
  19083. fromJSON(json) {
  19084. super.fromJSON(json);
  19085. this.v0.fromArray(json.v0);
  19086. this.v1.fromArray(json.v1);
  19087. this.v2.fromArray(json.v2);
  19088. return this;
  19089. }
  19090. }
  19091. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  19092. class QuadraticBezierCurve3 extends Curve {
  19093. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3()) {
  19094. super();
  19095. this.type = 'QuadraticBezierCurve3';
  19096. this.v0 = v0;
  19097. this.v1 = v1;
  19098. this.v2 = v2;
  19099. }
  19100. getPoint(t, optionalTarget = new Vector3()) {
  19101. const point = optionalTarget;
  19102. const v0 = this.v0,
  19103. v1 = this.v1,
  19104. v2 = this.v2;
  19105. 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));
  19106. return point;
  19107. }
  19108. copy(source) {
  19109. super.copy(source);
  19110. this.v0.copy(source.v0);
  19111. this.v1.copy(source.v1);
  19112. this.v2.copy(source.v2);
  19113. return this;
  19114. }
  19115. toJSON() {
  19116. const data = super.toJSON();
  19117. data.v0 = this.v0.toArray();
  19118. data.v1 = this.v1.toArray();
  19119. data.v2 = this.v2.toArray();
  19120. return data;
  19121. }
  19122. fromJSON(json) {
  19123. super.fromJSON(json);
  19124. this.v0.fromArray(json.v0);
  19125. this.v1.fromArray(json.v1);
  19126. this.v2.fromArray(json.v2);
  19127. return this;
  19128. }
  19129. }
  19130. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  19131. class SplineCurve extends Curve {
  19132. constructor(points = []) {
  19133. super();
  19134. this.type = 'SplineCurve';
  19135. this.points = points;
  19136. }
  19137. getPoint(t, optionalTarget = new Vector2()) {
  19138. const point = optionalTarget;
  19139. const points = this.points;
  19140. const p = (points.length - 1) * t;
  19141. const intPoint = Math.floor(p);
  19142. const weight = p - intPoint;
  19143. const p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
  19144. const p1 = points[intPoint];
  19145. const p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
  19146. const p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
  19147. point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
  19148. return point;
  19149. }
  19150. copy(source) {
  19151. super.copy(source);
  19152. this.points = [];
  19153. for (let i = 0, l = source.points.length; i < l; i++) {
  19154. const point = source.points[i];
  19155. this.points.push(point.clone());
  19156. }
  19157. return this;
  19158. }
  19159. toJSON() {
  19160. const data = super.toJSON();
  19161. data.points = [];
  19162. for (let i = 0, l = this.points.length; i < l; i++) {
  19163. const point = this.points[i];
  19164. data.points.push(point.toArray());
  19165. }
  19166. return data;
  19167. }
  19168. fromJSON(json) {
  19169. super.fromJSON(json);
  19170. this.points = [];
  19171. for (let i = 0, l = json.points.length; i < l; i++) {
  19172. const point = json.points[i];
  19173. this.points.push(new Vector2().fromArray(point));
  19174. }
  19175. return this;
  19176. }
  19177. }
  19178. SplineCurve.prototype.isSplineCurve = true;
  19179. var Curves = /*#__PURE__*/Object.freeze({
  19180. __proto__: null,
  19181. ArcCurve: ArcCurve,
  19182. CatmullRomCurve3: CatmullRomCurve3,
  19183. CubicBezierCurve: CubicBezierCurve,
  19184. CubicBezierCurve3: CubicBezierCurve3,
  19185. EllipseCurve: EllipseCurve,
  19186. LineCurve: LineCurve,
  19187. LineCurve3: LineCurve3,
  19188. QuadraticBezierCurve: QuadraticBezierCurve,
  19189. QuadraticBezierCurve3: QuadraticBezierCurve3,
  19190. SplineCurve: SplineCurve
  19191. });
  19192. /**************************************************************
  19193. * Curved Path - a curve path is simply a array of connected
  19194. * curves, but retains the api of a curve
  19195. **************************************************************/
  19196. class CurvePath extends Curve {
  19197. constructor() {
  19198. super();
  19199. this.type = 'CurvePath';
  19200. this.curves = [];
  19201. this.autoClose = false; // Automatically closes the path
  19202. }
  19203. add(curve) {
  19204. this.curves.push(curve);
  19205. }
  19206. closePath() {
  19207. // Add a line curve if start and end of lines are not connected
  19208. const startPoint = this.curves[0].getPoint(0);
  19209. const endPoint = this.curves[this.curves.length - 1].getPoint(1);
  19210. if (!startPoint.equals(endPoint)) {
  19211. this.curves.push(new LineCurve(endPoint, startPoint));
  19212. }
  19213. } // To get accurate point with reference to
  19214. // entire path distance at time t,
  19215. // following has to be done:
  19216. // 1. Length of each sub path have to be known
  19217. // 2. Locate and identify type of curve
  19218. // 3. Get t for the curve
  19219. // 4. Return curve.getPointAt(t')
  19220. getPoint(t, optionalTarget) {
  19221. const d = t * this.getLength();
  19222. const curveLengths = this.getCurveLengths();
  19223. let i = 0; // To think about boundaries points.
  19224. while (i < curveLengths.length) {
  19225. if (curveLengths[i] >= d) {
  19226. const diff = curveLengths[i] - d;
  19227. const curve = this.curves[i];
  19228. const segmentLength = curve.getLength();
  19229. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  19230. return curve.getPointAt(u, optionalTarget);
  19231. }
  19232. i++;
  19233. }
  19234. return null; // loop where sum != 0, sum > d , sum+1 <d
  19235. } // We cannot use the default THREE.Curve getPoint() with getLength() because in
  19236. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  19237. // getPoint() depends on getLength
  19238. getLength() {
  19239. const lens = this.getCurveLengths();
  19240. return lens[lens.length - 1];
  19241. } // cacheLengths must be recalculated.
  19242. updateArcLengths() {
  19243. this.needsUpdate = true;
  19244. this.cacheLengths = null;
  19245. this.getCurveLengths();
  19246. } // Compute lengths and cache them
  19247. // We cannot overwrite getLengths() because UtoT mapping uses it.
  19248. getCurveLengths() {
  19249. // We use cache values if curves and cache array are same length
  19250. if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
  19251. return this.cacheLengths;
  19252. } // Get length of sub-curve
  19253. // Push sums into cached array
  19254. const lengths = [];
  19255. let sums = 0;
  19256. for (let i = 0, l = this.curves.length; i < l; i++) {
  19257. sums += this.curves[i].getLength();
  19258. lengths.push(sums);
  19259. }
  19260. this.cacheLengths = lengths;
  19261. return lengths;
  19262. }
  19263. getSpacedPoints(divisions = 40) {
  19264. const points = [];
  19265. for (let i = 0; i <= divisions; i++) {
  19266. points.push(this.getPoint(i / divisions));
  19267. }
  19268. if (this.autoClose) {
  19269. points.push(points[0]);
  19270. }
  19271. return points;
  19272. }
  19273. getPoints(divisions = 12) {
  19274. const points = [];
  19275. let last;
  19276. for (let i = 0, curves = this.curves; i < curves.length; i++) {
  19277. const curve = curves[i];
  19278. const resolution = curve && curve.isEllipseCurve ? divisions * 2 : curve && (curve.isLineCurve || curve.isLineCurve3) ? 1 : curve && curve.isSplineCurve ? divisions * curve.points.length : divisions;
  19279. const pts = curve.getPoints(resolution);
  19280. for (let j = 0; j < pts.length; j++) {
  19281. const point = pts[j];
  19282. if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
  19283. points.push(point);
  19284. last = point;
  19285. }
  19286. }
  19287. if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
  19288. points.push(points[0]);
  19289. }
  19290. return points;
  19291. }
  19292. copy(source) {
  19293. super.copy(source);
  19294. this.curves = [];
  19295. for (let i = 0, l = source.curves.length; i < l; i++) {
  19296. const curve = source.curves[i];
  19297. this.curves.push(curve.clone());
  19298. }
  19299. this.autoClose = source.autoClose;
  19300. return this;
  19301. }
  19302. toJSON() {
  19303. const data = super.toJSON();
  19304. data.autoClose = this.autoClose;
  19305. data.curves = [];
  19306. for (let i = 0, l = this.curves.length; i < l; i++) {
  19307. const curve = this.curves[i];
  19308. data.curves.push(curve.toJSON());
  19309. }
  19310. return data;
  19311. }
  19312. fromJSON(json) {
  19313. super.fromJSON(json);
  19314. this.autoClose = json.autoClose;
  19315. this.curves = [];
  19316. for (let i = 0, l = json.curves.length; i < l; i++) {
  19317. const curve = json.curves[i];
  19318. this.curves.push(new Curves[curve.type]().fromJSON(curve));
  19319. }
  19320. return this;
  19321. }
  19322. }
  19323. class Path extends CurvePath {
  19324. constructor(points) {
  19325. super();
  19326. this.type = 'Path';
  19327. this.currentPoint = new Vector2();
  19328. if (points) {
  19329. this.setFromPoints(points);
  19330. }
  19331. }
  19332. setFromPoints(points) {
  19333. this.moveTo(points[0].x, points[0].y);
  19334. for (let i = 1, l = points.length; i < l; i++) {
  19335. this.lineTo(points[i].x, points[i].y);
  19336. }
  19337. return this;
  19338. }
  19339. moveTo(x, y) {
  19340. this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
  19341. return this;
  19342. }
  19343. lineTo(x, y) {
  19344. const curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));
  19345. this.curves.push(curve);
  19346. this.currentPoint.set(x, y);
  19347. return this;
  19348. }
  19349. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  19350. const curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));
  19351. this.curves.push(curve);
  19352. this.currentPoint.set(aX, aY);
  19353. return this;
  19354. }
  19355. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  19356. const curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));
  19357. this.curves.push(curve);
  19358. this.currentPoint.set(aX, aY);
  19359. return this;
  19360. }
  19361. splineThru(pts
  19362. /*Array of Vector*/
  19363. ) {
  19364. const npts = [this.currentPoint.clone()].concat(pts);
  19365. const curve = new SplineCurve(npts);
  19366. this.curves.push(curve);
  19367. this.currentPoint.copy(pts[pts.length - 1]);
  19368. return this;
  19369. }
  19370. arc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  19371. const x0 = this.currentPoint.x;
  19372. const y0 = this.currentPoint.y;
  19373. this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);
  19374. return this;
  19375. }
  19376. absarc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  19377. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  19378. return this;
  19379. }
  19380. ellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  19381. const x0 = this.currentPoint.x;
  19382. const y0 = this.currentPoint.y;
  19383. this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  19384. return this;
  19385. }
  19386. absellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  19387. const curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  19388. if (this.curves.length > 0) {
  19389. // if a previous curve is present, attempt to join
  19390. const firstPoint = curve.getPoint(0);
  19391. if (!firstPoint.equals(this.currentPoint)) {
  19392. this.lineTo(firstPoint.x, firstPoint.y);
  19393. }
  19394. }
  19395. this.curves.push(curve);
  19396. const lastPoint = curve.getPoint(1);
  19397. this.currentPoint.copy(lastPoint);
  19398. return this;
  19399. }
  19400. copy(source) {
  19401. super.copy(source);
  19402. this.currentPoint.copy(source.currentPoint);
  19403. return this;
  19404. }
  19405. toJSON() {
  19406. const data = super.toJSON();
  19407. data.currentPoint = this.currentPoint.toArray();
  19408. return data;
  19409. }
  19410. fromJSON(json) {
  19411. super.fromJSON(json);
  19412. this.currentPoint.fromArray(json.currentPoint);
  19413. return this;
  19414. }
  19415. }
  19416. class Shape extends Path {
  19417. constructor(points) {
  19418. super(points);
  19419. this.uuid = generateUUID();
  19420. this.type = 'Shape';
  19421. this.holes = [];
  19422. }
  19423. getPointsHoles(divisions) {
  19424. const holesPts = [];
  19425. for (let i = 0, l = this.holes.length; i < l; i++) {
  19426. holesPts[i] = this.holes[i].getPoints(divisions);
  19427. }
  19428. return holesPts;
  19429. } // get points of shape and holes (keypoints based on segments parameter)
  19430. extractPoints(divisions) {
  19431. return {
  19432. shape: this.getPoints(divisions),
  19433. holes: this.getPointsHoles(divisions)
  19434. };
  19435. }
  19436. copy(source) {
  19437. super.copy(source);
  19438. this.holes = [];
  19439. for (let i = 0, l = source.holes.length; i < l; i++) {
  19440. const hole = source.holes[i];
  19441. this.holes.push(hole.clone());
  19442. }
  19443. return this;
  19444. }
  19445. toJSON() {
  19446. const data = super.toJSON();
  19447. data.uuid = this.uuid;
  19448. data.holes = [];
  19449. for (let i = 0, l = this.holes.length; i < l; i++) {
  19450. const hole = this.holes[i];
  19451. data.holes.push(hole.toJSON());
  19452. }
  19453. return data;
  19454. }
  19455. fromJSON(json) {
  19456. super.fromJSON(json);
  19457. this.uuid = json.uuid;
  19458. this.holes = [];
  19459. for (let i = 0, l = json.holes.length; i < l; i++) {
  19460. const hole = json.holes[i];
  19461. this.holes.push(new Path().fromJSON(hole));
  19462. }
  19463. return this;
  19464. }
  19465. }
  19466. /**
  19467. * Port from https://github.com/mapbox/earcut (v2.2.2)
  19468. */
  19469. const Earcut = {
  19470. triangulate: function (data, holeIndices, dim = 2) {
  19471. const hasHoles = holeIndices && holeIndices.length;
  19472. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  19473. let outerNode = linkedList(data, 0, outerLen, dim, true);
  19474. const triangles = [];
  19475. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  19476. let minX, minY, maxX, maxY, x, y, invSize;
  19477. 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
  19478. if (data.length > 80 * dim) {
  19479. minX = maxX = data[0];
  19480. minY = maxY = data[1];
  19481. for (let i = dim; i < outerLen; i += dim) {
  19482. x = data[i];
  19483. y = data[i + 1];
  19484. if (x < minX) minX = x;
  19485. if (y < minY) minY = y;
  19486. if (x > maxX) maxX = x;
  19487. if (y > maxY) maxY = y;
  19488. } // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  19489. invSize = Math.max(maxX - minX, maxY - minY);
  19490. invSize = invSize !== 0 ? 1 / invSize : 0;
  19491. }
  19492. earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
  19493. return triangles;
  19494. }
  19495. }; // create a circular doubly linked list from polygon points in the specified winding order
  19496. function linkedList(data, start, end, dim, clockwise) {
  19497. let i, last;
  19498. if (clockwise === signedArea(data, start, end, dim) > 0) {
  19499. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  19500. } else {
  19501. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  19502. }
  19503. if (last && equals(last, last.next)) {
  19504. removeNode(last);
  19505. last = last.next;
  19506. }
  19507. return last;
  19508. } // eliminate colinear or duplicate points
  19509. function filterPoints(start, end) {
  19510. if (!start) return start;
  19511. if (!end) end = start;
  19512. let p = start,
  19513. again;
  19514. do {
  19515. again = false;
  19516. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  19517. removeNode(p);
  19518. p = end = p.prev;
  19519. if (p === p.next) break;
  19520. again = true;
  19521. } else {
  19522. p = p.next;
  19523. }
  19524. } while (again || p !== end);
  19525. return end;
  19526. } // main ear slicing loop which triangulates a polygon (given as a linked list)
  19527. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  19528. if (!ear) return; // interlink polygon nodes in z-order
  19529. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  19530. let stop = ear,
  19531. prev,
  19532. next; // iterate through ears, slicing them one by one
  19533. while (ear.prev !== ear.next) {
  19534. prev = ear.prev;
  19535. next = ear.next;
  19536. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  19537. // cut off the triangle
  19538. triangles.push(prev.i / dim);
  19539. triangles.push(ear.i / dim);
  19540. triangles.push(next.i / dim);
  19541. removeNode(ear); // skipping the next vertex leads to less sliver triangles
  19542. ear = next.next;
  19543. stop = next.next;
  19544. continue;
  19545. }
  19546. ear = next; // if we looped through the whole remaining polygon and can't find any more ears
  19547. if (ear === stop) {
  19548. // try filtering points and slicing again
  19549. if (!pass) {
  19550. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally
  19551. } else if (pass === 1) {
  19552. ear = cureLocalIntersections(filterPoints(ear), triangles, dim);
  19553. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two
  19554. } else if (pass === 2) {
  19555. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  19556. }
  19557. break;
  19558. }
  19559. }
  19560. } // check whether a polygon node forms a valid ear with adjacent nodes
  19561. function isEar(ear) {
  19562. const a = ear.prev,
  19563. b = ear,
  19564. c = ear.next;
  19565. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  19566. // now make sure we don't have other points inside the potential ear
  19567. let p = ear.next.next;
  19568. while (p !== ear.prev) {
  19569. 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;
  19570. p = p.next;
  19571. }
  19572. return true;
  19573. }
  19574. function isEarHashed(ear, minX, minY, invSize) {
  19575. const a = ear.prev,
  19576. b = ear,
  19577. c = ear.next;
  19578. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  19579. // triangle bbox; min & max are calculated like this for speed
  19580. const minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x,
  19581. minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y,
  19582. maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x,
  19583. 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;
  19584. const minZ = zOrder(minTX, minTY, minX, minY, invSize),
  19585. maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
  19586. let p = ear.prevZ,
  19587. n = ear.nextZ; // look for points inside the triangle in both directions
  19588. while (p && p.z >= minZ && n && n.z <= maxZ) {
  19589. 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;
  19590. p = p.prevZ;
  19591. 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;
  19592. n = n.nextZ;
  19593. } // look for remaining points in decreasing z-order
  19594. while (p && p.z >= minZ) {
  19595. 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;
  19596. p = p.prevZ;
  19597. } // look for remaining points in increasing z-order
  19598. while (n && n.z <= maxZ) {
  19599. 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;
  19600. n = n.nextZ;
  19601. }
  19602. return true;
  19603. } // go through all polygon nodes and cure small local self-intersections
  19604. function cureLocalIntersections(start, triangles, dim) {
  19605. let p = start;
  19606. do {
  19607. const a = p.prev,
  19608. b = p.next.next;
  19609. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  19610. triangles.push(a.i / dim);
  19611. triangles.push(p.i / dim);
  19612. triangles.push(b.i / dim); // remove two nodes involved
  19613. removeNode(p);
  19614. removeNode(p.next);
  19615. p = start = b;
  19616. }
  19617. p = p.next;
  19618. } while (p !== start);
  19619. return filterPoints(p);
  19620. } // try splitting polygon into two and triangulate them independently
  19621. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  19622. // look for a valid diagonal that divides the polygon into two
  19623. let a = start;
  19624. do {
  19625. let b = a.next.next;
  19626. while (b !== a.prev) {
  19627. if (a.i !== b.i && isValidDiagonal(a, b)) {
  19628. // split the polygon in two by the diagonal
  19629. let c = splitPolygon(a, b); // filter colinear points around the cuts
  19630. a = filterPoints(a, a.next);
  19631. c = filterPoints(c, c.next); // run earcut on each half
  19632. earcutLinked(a, triangles, dim, minX, minY, invSize);
  19633. earcutLinked(c, triangles, dim, minX, minY, invSize);
  19634. return;
  19635. }
  19636. b = b.next;
  19637. }
  19638. a = a.next;
  19639. } while (a !== start);
  19640. } // link every hole into the outer loop, producing a single-ring polygon without holes
  19641. function eliminateHoles(data, holeIndices, outerNode, dim) {
  19642. const queue = [];
  19643. let i, len, start, end, list;
  19644. for (i = 0, len = holeIndices.length; i < len; i++) {
  19645. start = holeIndices[i] * dim;
  19646. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  19647. list = linkedList(data, start, end, dim, false);
  19648. if (list === list.next) list.steiner = true;
  19649. queue.push(getLeftmost(list));
  19650. }
  19651. queue.sort(compareX); // process holes from left to right
  19652. for (i = 0; i < queue.length; i++) {
  19653. eliminateHole(queue[i], outerNode);
  19654. outerNode = filterPoints(outerNode, outerNode.next);
  19655. }
  19656. return outerNode;
  19657. }
  19658. function compareX(a, b) {
  19659. return a.x - b.x;
  19660. } // find a bridge between vertices that connects hole with an outer ring and and link it
  19661. function eliminateHole(hole, outerNode) {
  19662. outerNode = findHoleBridge(hole, outerNode);
  19663. if (outerNode) {
  19664. const b = splitPolygon(outerNode, hole); // filter collinear points around the cuts
  19665. filterPoints(outerNode, outerNode.next);
  19666. filterPoints(b, b.next);
  19667. }
  19668. } // David Eberly's algorithm for finding a bridge between hole and outer polygon
  19669. function findHoleBridge(hole, outerNode) {
  19670. let p = outerNode;
  19671. const hx = hole.x;
  19672. const hy = hole.y;
  19673. let qx = -Infinity,
  19674. m; // find a segment intersected by a ray from the hole's leftmost point to the left;
  19675. // segment's endpoint with lesser x will be potential connection point
  19676. do {
  19677. if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  19678. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  19679. if (x <= hx && x > qx) {
  19680. qx = x;
  19681. if (x === hx) {
  19682. if (hy === p.y) return p;
  19683. if (hy === p.next.y) return p.next;
  19684. }
  19685. m = p.x < p.next.x ? p : p.next;
  19686. }
  19687. }
  19688. p = p.next;
  19689. } while (p !== outerNode);
  19690. if (!m) return null;
  19691. if (hx === qx) return m; // hole touches outer segment; pick leftmost endpoint
  19692. // look for points inside the triangle of hole point, segment intersection and endpoint;
  19693. // if there are no points found, we have a valid connection;
  19694. // otherwise choose the point of the minimum angle with the ray as connection point
  19695. const stop = m,
  19696. mx = m.x,
  19697. my = m.y;
  19698. let tanMin = Infinity,
  19699. tan;
  19700. p = m;
  19701. do {
  19702. 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)) {
  19703. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  19704. if (locallyInside(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) {
  19705. m = p;
  19706. tanMin = tan;
  19707. }
  19708. }
  19709. p = p.next;
  19710. } while (p !== stop);
  19711. return m;
  19712. } // whether sector in vertex m contains sector in vertex p in the same coordinates
  19713. function sectorContainsSector(m, p) {
  19714. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  19715. } // interlink polygon nodes in z-order
  19716. function indexCurve(start, minX, minY, invSize) {
  19717. let p = start;
  19718. do {
  19719. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  19720. p.prevZ = p.prev;
  19721. p.nextZ = p.next;
  19722. p = p.next;
  19723. } while (p !== start);
  19724. p.prevZ.nextZ = null;
  19725. p.prevZ = null;
  19726. sortLinked(p);
  19727. } // Simon Tatham's linked list merge sort algorithm
  19728. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  19729. function sortLinked(list) {
  19730. let i,
  19731. p,
  19732. q,
  19733. e,
  19734. tail,
  19735. numMerges,
  19736. pSize,
  19737. qSize,
  19738. inSize = 1;
  19739. do {
  19740. p = list;
  19741. list = null;
  19742. tail = null;
  19743. numMerges = 0;
  19744. while (p) {
  19745. numMerges++;
  19746. q = p;
  19747. pSize = 0;
  19748. for (i = 0; i < inSize; i++) {
  19749. pSize++;
  19750. q = q.nextZ;
  19751. if (!q) break;
  19752. }
  19753. qSize = inSize;
  19754. while (pSize > 0 || qSize > 0 && q) {
  19755. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  19756. e = p;
  19757. p = p.nextZ;
  19758. pSize--;
  19759. } else {
  19760. e = q;
  19761. q = q.nextZ;
  19762. qSize--;
  19763. }
  19764. if (tail) tail.nextZ = e;else list = e;
  19765. e.prevZ = tail;
  19766. tail = e;
  19767. }
  19768. p = q;
  19769. }
  19770. tail.nextZ = null;
  19771. inSize *= 2;
  19772. } while (numMerges > 1);
  19773. return list;
  19774. } // z-order of a point given coords and inverse of the longer side of data bbox
  19775. function zOrder(x, y, minX, minY, invSize) {
  19776. // coords are transformed into non-negative 15-bit integer range
  19777. x = 32767 * (x - minX) * invSize;
  19778. y = 32767 * (y - minY) * invSize;
  19779. x = (x | x << 8) & 0x00FF00FF;
  19780. x = (x | x << 4) & 0x0F0F0F0F;
  19781. x = (x | x << 2) & 0x33333333;
  19782. x = (x | x << 1) & 0x55555555;
  19783. y = (y | y << 8) & 0x00FF00FF;
  19784. y = (y | y << 4) & 0x0F0F0F0F;
  19785. y = (y | y << 2) & 0x33333333;
  19786. y = (y | y << 1) & 0x55555555;
  19787. return x | y << 1;
  19788. } // find the leftmost node of a polygon ring
  19789. function getLeftmost(start) {
  19790. let p = start,
  19791. leftmost = start;
  19792. do {
  19793. if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
  19794. p = p.next;
  19795. } while (p !== start);
  19796. return leftmost;
  19797. } // check if a point lies within a convex triangle
  19798. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  19799. 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;
  19800. } // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  19801. function isValidDiagonal(a, b) {
  19802. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && ( // dones't intersect other edges
  19803. locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && ( // locally visible
  19804. area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  19805. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  19806. } // signed area of a triangle
  19807. function area(p, q, r) {
  19808. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  19809. } // check if two points are equal
  19810. function equals(p1, p2) {
  19811. return p1.x === p2.x && p1.y === p2.y;
  19812. } // check if two segments intersect
  19813. function intersects(p1, q1, p2, q2) {
  19814. const o1 = sign(area(p1, q1, p2));
  19815. const o2 = sign(area(p1, q1, q2));
  19816. const o3 = sign(area(p2, q2, p1));
  19817. const o4 = sign(area(p2, q2, q1));
  19818. if (o1 !== o2 && o3 !== o4) return true; // general case
  19819. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  19820. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  19821. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  19822. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  19823. return false;
  19824. } // for collinear points p, q, r, check if point q lies on segment pr
  19825. function onSegment(p, q, r) {
  19826. 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);
  19827. }
  19828. function sign(num) {
  19829. return num > 0 ? 1 : num < 0 ? -1 : 0;
  19830. } // check if a polygon diagonal intersects any polygon segments
  19831. function intersectsPolygon(a, b) {
  19832. let p = a;
  19833. do {
  19834. 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;
  19835. p = p.next;
  19836. } while (p !== a);
  19837. return false;
  19838. } // check if a polygon diagonal is locally inside the polygon
  19839. function locallyInside(a, b) {
  19840. 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;
  19841. } // check if the middle point of a polygon diagonal is inside the polygon
  19842. function middleInside(a, b) {
  19843. let p = a,
  19844. inside = false;
  19845. const px = (a.x + b.x) / 2,
  19846. py = (a.y + b.y) / 2;
  19847. do {
  19848. 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;
  19849. p = p.next;
  19850. } while (p !== a);
  19851. return inside;
  19852. } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  19853. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  19854. function splitPolygon(a, b) {
  19855. const a2 = new Node(a.i, a.x, a.y),
  19856. b2 = new Node(b.i, b.x, b.y),
  19857. an = a.next,
  19858. bp = b.prev;
  19859. a.next = b;
  19860. b.prev = a;
  19861. a2.next = an;
  19862. an.prev = a2;
  19863. b2.next = a2;
  19864. a2.prev = b2;
  19865. bp.next = b2;
  19866. b2.prev = bp;
  19867. return b2;
  19868. } // create a node and optionally link it with previous one (in a circular doubly linked list)
  19869. function insertNode(i, x, y, last) {
  19870. const p = new Node(i, x, y);
  19871. if (!last) {
  19872. p.prev = p;
  19873. p.next = p;
  19874. } else {
  19875. p.next = last.next;
  19876. p.prev = last;
  19877. last.next.prev = p;
  19878. last.next = p;
  19879. }
  19880. return p;
  19881. }
  19882. function removeNode(p) {
  19883. p.next.prev = p.prev;
  19884. p.prev.next = p.next;
  19885. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  19886. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  19887. }
  19888. function Node(i, x, y) {
  19889. // vertex index in coordinates array
  19890. this.i = i; // vertex coordinates
  19891. this.x = x;
  19892. this.y = y; // previous and next vertex nodes in a polygon ring
  19893. this.prev = null;
  19894. this.next = null; // z-order curve value
  19895. this.z = null; // previous and next nodes in z-order
  19896. this.prevZ = null;
  19897. this.nextZ = null; // indicates whether this is a steiner point
  19898. this.steiner = false;
  19899. }
  19900. function signedArea(data, start, end, dim) {
  19901. let sum = 0;
  19902. for (let i = start, j = end - dim; i < end; i += dim) {
  19903. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  19904. j = i;
  19905. }
  19906. return sum;
  19907. }
  19908. class ShapeUtils {
  19909. // calculate area of the contour polygon
  19910. static area(contour) {
  19911. const n = contour.length;
  19912. let a = 0.0;
  19913. for (let p = n - 1, q = 0; q < n; p = q++) {
  19914. a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
  19915. }
  19916. return a * 0.5;
  19917. }
  19918. static isClockWise(pts) {
  19919. return ShapeUtils.area(pts) < 0;
  19920. }
  19921. static triangulateShape(contour, holes) {
  19922. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  19923. const holeIndices = []; // array of hole indices
  19924. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  19925. removeDupEndPts(contour);
  19926. addContour(vertices, contour); //
  19927. let holeIndex = contour.length;
  19928. holes.forEach(removeDupEndPts);
  19929. for (let i = 0; i < holes.length; i++) {
  19930. holeIndices.push(holeIndex);
  19931. holeIndex += holes[i].length;
  19932. addContour(vertices, holes[i]);
  19933. } //
  19934. const triangles = Earcut.triangulate(vertices, holeIndices); //
  19935. for (let i = 0; i < triangles.length; i += 3) {
  19936. faces.push(triangles.slice(i, i + 3));
  19937. }
  19938. return faces;
  19939. }
  19940. }
  19941. function removeDupEndPts(points) {
  19942. const l = points.length;
  19943. if (l > 2 && points[l - 1].equals(points[0])) {
  19944. points.pop();
  19945. }
  19946. }
  19947. function addContour(vertices, contour) {
  19948. for (let i = 0; i < contour.length; i++) {
  19949. vertices.push(contour[i].x);
  19950. vertices.push(contour[i].y);
  19951. }
  19952. }
  19953. /**
  19954. * Creates extruded geometry from a path shape.
  19955. *
  19956. * parameters = {
  19957. *
  19958. * curveSegments: <int>, // number of points on the curves
  19959. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  19960. * depth: <float>, // Depth to extrude the shape
  19961. *
  19962. * bevelEnabled: <bool>, // turn on bevel
  19963. * bevelThickness: <float>, // how deep into the original shape bevel goes
  19964. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  19965. * bevelOffset: <float>, // how far from shape outline does bevel start
  19966. * bevelSegments: <int>, // number of bevel layers
  19967. *
  19968. * extrudePath: <THREE.Curve> // curve to extrude shape along
  19969. *
  19970. * UVGenerator: <Object> // object that provides UV generator functions
  19971. *
  19972. * }
  19973. */
  19974. class ExtrudeGeometry extends BufferGeometry {
  19975. constructor(shapes = new Shape([new Vector2(0.5, 0.5), new Vector2(-0.5, 0.5), new Vector2(-0.5, -0.5), new Vector2(0.5, -0.5)]), options = {}) {
  19976. super();
  19977. this.type = 'ExtrudeGeometry';
  19978. this.parameters = {
  19979. shapes: shapes,
  19980. options: options
  19981. };
  19982. shapes = Array.isArray(shapes) ? shapes : [shapes];
  19983. const scope = this;
  19984. const verticesArray = [];
  19985. const uvArray = [];
  19986. for (let i = 0, l = shapes.length; i < l; i++) {
  19987. const shape = shapes[i];
  19988. addShape(shape);
  19989. } // build geometry
  19990. this.setAttribute('position', new Float32BufferAttribute(verticesArray, 3));
  19991. this.setAttribute('uv', new Float32BufferAttribute(uvArray, 2));
  19992. this.computeVertexNormals(); // functions
  19993. function addShape(shape) {
  19994. const placeholder = []; // options
  19995. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19996. const steps = options.steps !== undefined ? options.steps : 1;
  19997. let depth = options.depth !== undefined ? options.depth : 1;
  19998. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  19999. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  20000. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  20001. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  20002. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  20003. const extrudePath = options.extrudePath;
  20004. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; // deprecated options
  20005. if (options.amount !== undefined) {
  20006. console.warn('THREE.ExtrudeBufferGeometry: amount has been renamed to depth.');
  20007. depth = options.amount;
  20008. } //
  20009. let extrudePts,
  20010. extrudeByPath = false;
  20011. let splineTube, binormal, normal, position2;
  20012. if (extrudePath) {
  20013. extrudePts = extrudePath.getSpacedPoints(steps);
  20014. extrudeByPath = true;
  20015. bevelEnabled = false; // bevels not supported for path extrusion
  20016. // SETUP TNB variables
  20017. // TODO1 - have a .isClosed in spline?
  20018. splineTube = extrudePath.computeFrenetFrames(steps, false); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  20019. binormal = new Vector3();
  20020. normal = new Vector3();
  20021. position2 = new Vector3();
  20022. } // Safeguards if bevels are not enabled
  20023. if (!bevelEnabled) {
  20024. bevelSegments = 0;
  20025. bevelThickness = 0;
  20026. bevelSize = 0;
  20027. bevelOffset = 0;
  20028. } // Variables initialization
  20029. const shapePoints = shape.extractPoints(curveSegments);
  20030. let vertices = shapePoints.shape;
  20031. const holes = shapePoints.holes;
  20032. const reverse = !ShapeUtils.isClockWise(vertices);
  20033. if (reverse) {
  20034. vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  20035. for (let h = 0, hl = holes.length; h < hl; h++) {
  20036. const ahole = holes[h];
  20037. if (ShapeUtils.isClockWise(ahole)) {
  20038. holes[h] = ahole.reverse();
  20039. }
  20040. }
  20041. }
  20042. const faces = ShapeUtils.triangulateShape(vertices, holes);
  20043. /* Vertices */
  20044. const contour = vertices; // vertices has all points but contour has only points of circumference
  20045. for (let h = 0, hl = holes.length; h < hl; h++) {
  20046. const ahole = holes[h];
  20047. vertices = vertices.concat(ahole);
  20048. }
  20049. function scalePt2(pt, vec, size) {
  20050. if (!vec) console.error('THREE.ExtrudeGeometry: vec does not exist');
  20051. return vec.clone().multiplyScalar(size).add(pt);
  20052. }
  20053. const vlen = vertices.length,
  20054. flen = faces.length; // Find directions for point movement
  20055. function getBevelVec(inPt, inPrev, inNext) {
  20056. // computes for inPt the corresponding point inPt' on a new contour
  20057. // shifted by 1 unit (length of normalized vector) to the left
  20058. // if we walk along contour clockwise, this new contour is outside the old one
  20059. //
  20060. // inPt' is the intersection of the two lines parallel to the two
  20061. // adjacent edges of inPt at a distance of 1 unit on the left side.
  20062. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  20063. // good reading for geometry algorithms (here: line-line intersection)
  20064. // http://geomalgorithms.com/a05-_intersect-1.html
  20065. const v_prev_x = inPt.x - inPrev.x,
  20066. v_prev_y = inPt.y - inPrev.y;
  20067. const v_next_x = inNext.x - inPt.x,
  20068. v_next_y = inNext.y - inPt.y;
  20069. const v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; // check for collinear edges
  20070. const collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
  20071. if (Math.abs(collinear0) > Number.EPSILON) {
  20072. // not collinear
  20073. // length of vectors for normalizing
  20074. const v_prev_len = Math.sqrt(v_prev_lensq);
  20075. 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
  20076. const ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
  20077. const ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
  20078. const ptNextShift_x = inNext.x - v_next_y / v_next_len;
  20079. const ptNextShift_y = inNext.y + v_next_x / v_next_len; // scaling factor for v_prev to intersection point
  20080. 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
  20081. v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
  20082. v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; // Don't normalize!, otherwise sharp corners become ugly
  20083. // but prevent crazy spikes
  20084. const v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
  20085. if (v_trans_lensq <= 2) {
  20086. return new Vector2(v_trans_x, v_trans_y);
  20087. } else {
  20088. shrink_by = Math.sqrt(v_trans_lensq / 2);
  20089. }
  20090. } else {
  20091. // handle special case of collinear edges
  20092. let direction_eq = false; // assumes: opposite
  20093. if (v_prev_x > Number.EPSILON) {
  20094. if (v_next_x > Number.EPSILON) {
  20095. direction_eq = true;
  20096. }
  20097. } else {
  20098. if (v_prev_x < -Number.EPSILON) {
  20099. if (v_next_x < -Number.EPSILON) {
  20100. direction_eq = true;
  20101. }
  20102. } else {
  20103. if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
  20104. direction_eq = true;
  20105. }
  20106. }
  20107. }
  20108. if (direction_eq) {
  20109. // console.log("Warning: lines are a straight sequence");
  20110. v_trans_x = -v_prev_y;
  20111. v_trans_y = v_prev_x;
  20112. shrink_by = Math.sqrt(v_prev_lensq);
  20113. } else {
  20114. // console.log("Warning: lines are a straight spike");
  20115. v_trans_x = v_prev_x;
  20116. v_trans_y = v_prev_y;
  20117. shrink_by = Math.sqrt(v_prev_lensq / 2);
  20118. }
  20119. }
  20120. return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
  20121. }
  20122. const contourMovements = [];
  20123. for (let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  20124. if (j === il) j = 0;
  20125. if (k === il) k = 0; // (j)---(i)---(k)
  20126. // console.log('i,j,k', i, j , k)
  20127. contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]);
  20128. }
  20129. const holesMovements = [];
  20130. let oneHoleMovements,
  20131. verticesMovements = contourMovements.concat();
  20132. for (let h = 0, hl = holes.length; h < hl; h++) {
  20133. const ahole = holes[h];
  20134. oneHoleMovements = [];
  20135. for (let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  20136. if (j === il) j = 0;
  20137. if (k === il) k = 0; // (j)---(i)---(k)
  20138. oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]);
  20139. }
  20140. holesMovements.push(oneHoleMovements);
  20141. verticesMovements = verticesMovements.concat(oneHoleMovements);
  20142. } // Loop bevelSegments, 1 for the front, 1 for the back
  20143. for (let b = 0; b < bevelSegments; b++) {
  20144. //for ( b = bevelSegments; b > 0; b -- ) {
  20145. const t = b / bevelSegments;
  20146. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  20147. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  20148. for (let i = 0, il = contour.length; i < il; i++) {
  20149. const vert = scalePt2(contour[i], contourMovements[i], bs);
  20150. v(vert.x, vert.y, -z);
  20151. } // expand holes
  20152. for (let h = 0, hl = holes.length; h < hl; h++) {
  20153. const ahole = holes[h];
  20154. oneHoleMovements = holesMovements[h];
  20155. for (let i = 0, il = ahole.length; i < il; i++) {
  20156. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  20157. v(vert.x, vert.y, -z);
  20158. }
  20159. }
  20160. }
  20161. const bs = bevelSize + bevelOffset; // Back facing vertices
  20162. for (let i = 0; i < vlen; i++) {
  20163. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  20164. if (!extrudeByPath) {
  20165. v(vert.x, vert.y, 0);
  20166. } else {
  20167. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  20168. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  20169. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  20170. position2.copy(extrudePts[0]).add(normal).add(binormal);
  20171. v(position2.x, position2.y, position2.z);
  20172. }
  20173. } // Add stepped vertices...
  20174. // Including front facing vertices
  20175. for (let s = 1; s <= steps; s++) {
  20176. for (let i = 0; i < vlen; i++) {
  20177. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  20178. if (!extrudeByPath) {
  20179. v(vert.x, vert.y, depth / steps * s);
  20180. } else {
  20181. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  20182. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  20183. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  20184. position2.copy(extrudePts[s]).add(normal).add(binormal);
  20185. v(position2.x, position2.y, position2.z);
  20186. }
  20187. }
  20188. } // Add bevel segments planes
  20189. //for ( b = 1; b <= bevelSegments; b ++ ) {
  20190. for (let b = bevelSegments - 1; b >= 0; b--) {
  20191. const t = b / bevelSegments;
  20192. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  20193. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  20194. for (let i = 0, il = contour.length; i < il; i++) {
  20195. const vert = scalePt2(contour[i], contourMovements[i], bs);
  20196. v(vert.x, vert.y, depth + z);
  20197. } // expand holes
  20198. for (let h = 0, hl = holes.length; h < hl; h++) {
  20199. const ahole = holes[h];
  20200. oneHoleMovements = holesMovements[h];
  20201. for (let i = 0, il = ahole.length; i < il; i++) {
  20202. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  20203. if (!extrudeByPath) {
  20204. v(vert.x, vert.y, depth + z);
  20205. } else {
  20206. v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z);
  20207. }
  20208. }
  20209. }
  20210. }
  20211. /* Faces */
  20212. // Top and bottom faces
  20213. buildLidFaces(); // Sides faces
  20214. buildSideFaces(); ///// Internal functions
  20215. function buildLidFaces() {
  20216. const start = verticesArray.length / 3;
  20217. if (bevelEnabled) {
  20218. let layer = 0; // steps + 1
  20219. let offset = vlen * layer; // Bottom faces
  20220. for (let i = 0; i < flen; i++) {
  20221. const face = faces[i];
  20222. f3(face[2] + offset, face[1] + offset, face[0] + offset);
  20223. }
  20224. layer = steps + bevelSegments * 2;
  20225. offset = vlen * layer; // Top faces
  20226. for (let i = 0; i < flen; i++) {
  20227. const face = faces[i];
  20228. f3(face[0] + offset, face[1] + offset, face[2] + offset);
  20229. }
  20230. } else {
  20231. // Bottom faces
  20232. for (let i = 0; i < flen; i++) {
  20233. const face = faces[i];
  20234. f3(face[2], face[1], face[0]);
  20235. } // Top faces
  20236. for (let i = 0; i < flen; i++) {
  20237. const face = faces[i];
  20238. f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps);
  20239. }
  20240. }
  20241. scope.addGroup(start, verticesArray.length / 3 - start, 0);
  20242. } // Create faces for the z-sides of the shape
  20243. function buildSideFaces() {
  20244. const start = verticesArray.length / 3;
  20245. let layeroffset = 0;
  20246. sidewalls(contour, layeroffset);
  20247. layeroffset += contour.length;
  20248. for (let h = 0, hl = holes.length; h < hl; h++) {
  20249. const ahole = holes[h];
  20250. sidewalls(ahole, layeroffset); //, true
  20251. layeroffset += ahole.length;
  20252. }
  20253. scope.addGroup(start, verticesArray.length / 3 - start, 1);
  20254. }
  20255. function sidewalls(contour, layeroffset) {
  20256. let i = contour.length;
  20257. while (--i >= 0) {
  20258. const j = i;
  20259. let k = i - 1;
  20260. if (k < 0) k = contour.length - 1; //console.log('b', i,j, i-1, k,vertices.length);
  20261. for (let s = 0, sl = steps + bevelSegments * 2; s < sl; s++) {
  20262. const slen1 = vlen * s;
  20263. const slen2 = vlen * (s + 1);
  20264. const a = layeroffset + j + slen1,
  20265. b = layeroffset + k + slen1,
  20266. c = layeroffset + k + slen2,
  20267. d = layeroffset + j + slen2;
  20268. f4(a, b, c, d);
  20269. }
  20270. }
  20271. }
  20272. function v(x, y, z) {
  20273. placeholder.push(x);
  20274. placeholder.push(y);
  20275. placeholder.push(z);
  20276. }
  20277. function f3(a, b, c) {
  20278. addVertex(a);
  20279. addVertex(b);
  20280. addVertex(c);
  20281. const nextIndex = verticesArray.length / 3;
  20282. const uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  20283. addUV(uvs[0]);
  20284. addUV(uvs[1]);
  20285. addUV(uvs[2]);
  20286. }
  20287. function f4(a, b, c, d) {
  20288. addVertex(a);
  20289. addVertex(b);
  20290. addVertex(d);
  20291. addVertex(b);
  20292. addVertex(c);
  20293. addVertex(d);
  20294. const nextIndex = verticesArray.length / 3;
  20295. const uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  20296. addUV(uvs[0]);
  20297. addUV(uvs[1]);
  20298. addUV(uvs[3]);
  20299. addUV(uvs[1]);
  20300. addUV(uvs[2]);
  20301. addUV(uvs[3]);
  20302. }
  20303. function addVertex(index) {
  20304. verticesArray.push(placeholder[index * 3 + 0]);
  20305. verticesArray.push(placeholder[index * 3 + 1]);
  20306. verticesArray.push(placeholder[index * 3 + 2]);
  20307. }
  20308. function addUV(vector2) {
  20309. uvArray.push(vector2.x);
  20310. uvArray.push(vector2.y);
  20311. }
  20312. }
  20313. }
  20314. toJSON() {
  20315. const data = super.toJSON();
  20316. const shapes = this.parameters.shapes;
  20317. const options = this.parameters.options;
  20318. return toJSON$1(shapes, options, data);
  20319. }
  20320. static fromJSON(data, shapes) {
  20321. const geometryShapes = [];
  20322. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  20323. const shape = shapes[data.shapes[j]];
  20324. geometryShapes.push(shape);
  20325. }
  20326. const extrudePath = data.options.extrudePath;
  20327. if (extrudePath !== undefined) {
  20328. data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
  20329. }
  20330. return new ExtrudeGeometry(geometryShapes, data.options);
  20331. }
  20332. }
  20333. const WorldUVGenerator = {
  20334. generateTopUV: function (geometry, vertices, indexA, indexB, indexC) {
  20335. const a_x = vertices[indexA * 3];
  20336. const a_y = vertices[indexA * 3 + 1];
  20337. const b_x = vertices[indexB * 3];
  20338. const b_y = vertices[indexB * 3 + 1];
  20339. const c_x = vertices[indexC * 3];
  20340. const c_y = vertices[indexC * 3 + 1];
  20341. return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];
  20342. },
  20343. generateSideWallUV: function (geometry, vertices, indexA, indexB, indexC, indexD) {
  20344. const a_x = vertices[indexA * 3];
  20345. const a_y = vertices[indexA * 3 + 1];
  20346. const a_z = vertices[indexA * 3 + 2];
  20347. const b_x = vertices[indexB * 3];
  20348. const b_y = vertices[indexB * 3 + 1];
  20349. const b_z = vertices[indexB * 3 + 2];
  20350. const c_x = vertices[indexC * 3];
  20351. const c_y = vertices[indexC * 3 + 1];
  20352. const c_z = vertices[indexC * 3 + 2];
  20353. const d_x = vertices[indexD * 3];
  20354. const d_y = vertices[indexD * 3 + 1];
  20355. const d_z = vertices[indexD * 3 + 2];
  20356. if (Math.abs(a_y - b_y) < Math.abs(a_x - b_x)) {
  20357. 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)];
  20358. } else {
  20359. 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)];
  20360. }
  20361. }
  20362. };
  20363. function toJSON$1(shapes, options, data) {
  20364. data.shapes = [];
  20365. if (Array.isArray(shapes)) {
  20366. for (let i = 0, l = shapes.length; i < l; i++) {
  20367. const shape = shapes[i];
  20368. data.shapes.push(shape.uuid);
  20369. }
  20370. } else {
  20371. data.shapes.push(shapes.uuid);
  20372. }
  20373. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  20374. return data;
  20375. }
  20376. class IcosahedronGeometry extends PolyhedronGeometry {
  20377. constructor(radius = 1, detail = 0) {
  20378. const t = (1 + Math.sqrt(5)) / 2;
  20379. 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];
  20380. 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];
  20381. super(vertices, indices, radius, detail);
  20382. this.type = 'IcosahedronGeometry';
  20383. this.parameters = {
  20384. radius: radius,
  20385. detail: detail
  20386. };
  20387. }
  20388. static fromJSON(data) {
  20389. return new IcosahedronGeometry(data.radius, data.detail);
  20390. }
  20391. }
  20392. class LatheGeometry extends BufferGeometry {
  20393. constructor(points = [new Vector2(0, 0.5), new Vector2(0.5, 0), new Vector2(0, -0.5)], segments = 12, phiStart = 0, phiLength = Math.PI * 2) {
  20394. super();
  20395. this.type = 'LatheGeometry';
  20396. this.parameters = {
  20397. points: points,
  20398. segments: segments,
  20399. phiStart: phiStart,
  20400. phiLength: phiLength
  20401. };
  20402. segments = Math.floor(segments); // clamp phiLength so it's in range of [ 0, 2PI ]
  20403. phiLength = clamp(phiLength, 0, Math.PI * 2); // buffers
  20404. const indices = [];
  20405. const vertices = [];
  20406. const uvs = [];
  20407. const initNormals = [];
  20408. const normals = []; // helper variables
  20409. const inverseSegments = 1.0 / segments;
  20410. const vertex = new Vector3();
  20411. const uv = new Vector2();
  20412. const normal = new Vector3();
  20413. const curNormal = new Vector3();
  20414. const prevNormal = new Vector3();
  20415. let dx = 0;
  20416. let dy = 0; // pre-compute normals for initial "meridian"
  20417. for (let j = 0; j <= points.length - 1; j++) {
  20418. switch (j) {
  20419. case 0:
  20420. // special handling for 1st vertex on path
  20421. dx = points[j + 1].x - points[j].x;
  20422. dy = points[j + 1].y - points[j].y;
  20423. normal.x = dy * 1.0;
  20424. normal.y = -dx;
  20425. normal.z = dy * 0.0;
  20426. prevNormal.copy(normal);
  20427. normal.normalize();
  20428. initNormals.push(normal.x, normal.y, normal.z);
  20429. break;
  20430. case points.length - 1:
  20431. // special handling for last Vertex on path
  20432. initNormals.push(prevNormal.x, prevNormal.y, prevNormal.z);
  20433. break;
  20434. default:
  20435. // default handling for all vertices in between
  20436. dx = points[j + 1].x - points[j].x;
  20437. dy = points[j + 1].y - points[j].y;
  20438. normal.x = dy * 1.0;
  20439. normal.y = -dx;
  20440. normal.z = dy * 0.0;
  20441. curNormal.copy(normal);
  20442. normal.x += prevNormal.x;
  20443. normal.y += prevNormal.y;
  20444. normal.z += prevNormal.z;
  20445. normal.normalize();
  20446. initNormals.push(normal.x, normal.y, normal.z);
  20447. prevNormal.copy(curNormal);
  20448. }
  20449. } // generate vertices, uvs and normals
  20450. for (let i = 0; i <= segments; i++) {
  20451. const phi = phiStart + i * inverseSegments * phiLength;
  20452. const sin = Math.sin(phi);
  20453. const cos = Math.cos(phi);
  20454. for (let j = 0; j <= points.length - 1; j++) {
  20455. // vertex
  20456. vertex.x = points[j].x * sin;
  20457. vertex.y = points[j].y;
  20458. vertex.z = points[j].x * cos;
  20459. vertices.push(vertex.x, vertex.y, vertex.z); // uv
  20460. uv.x = i / segments;
  20461. uv.y = j / (points.length - 1);
  20462. uvs.push(uv.x, uv.y); // normal
  20463. const x = initNormals[3 * j + 0] * sin;
  20464. const y = initNormals[3 * j + 1];
  20465. const z = initNormals[3 * j + 0] * cos;
  20466. normals.push(x, y, z);
  20467. }
  20468. } // indices
  20469. for (let i = 0; i < segments; i++) {
  20470. for (let j = 0; j < points.length - 1; j++) {
  20471. const base = j + i * points.length;
  20472. const a = base;
  20473. const b = base + points.length;
  20474. const c = base + points.length + 1;
  20475. const d = base + 1; // faces
  20476. indices.push(a, b, d);
  20477. indices.push(b, c, d);
  20478. }
  20479. } // build geometry
  20480. this.setIndex(indices);
  20481. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20482. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20483. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20484. }
  20485. static fromJSON(data) {
  20486. return new LatheGeometry(data.points, data.segments, data.phiStart, data.phiLength);
  20487. }
  20488. }
  20489. class OctahedronGeometry extends PolyhedronGeometry {
  20490. constructor(radius = 1, detail = 0) {
  20491. const vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
  20492. 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];
  20493. super(vertices, indices, radius, detail);
  20494. this.type = 'OctahedronGeometry';
  20495. this.parameters = {
  20496. radius: radius,
  20497. detail: detail
  20498. };
  20499. }
  20500. static fromJSON(data) {
  20501. return new OctahedronGeometry(data.radius, data.detail);
  20502. }
  20503. }
  20504. class RingGeometry extends BufferGeometry {
  20505. constructor(innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2) {
  20506. super();
  20507. this.type = 'RingGeometry';
  20508. this.parameters = {
  20509. innerRadius: innerRadius,
  20510. outerRadius: outerRadius,
  20511. thetaSegments: thetaSegments,
  20512. phiSegments: phiSegments,
  20513. thetaStart: thetaStart,
  20514. thetaLength: thetaLength
  20515. };
  20516. thetaSegments = Math.max(3, thetaSegments);
  20517. phiSegments = Math.max(1, phiSegments); // buffers
  20518. const indices = [];
  20519. const vertices = [];
  20520. const normals = [];
  20521. const uvs = []; // some helper variables
  20522. let radius = innerRadius;
  20523. const radiusStep = (outerRadius - innerRadius) / phiSegments;
  20524. const vertex = new Vector3();
  20525. const uv = new Vector2(); // generate vertices, normals and uvs
  20526. for (let j = 0; j <= phiSegments; j++) {
  20527. for (let i = 0; i <= thetaSegments; i++) {
  20528. // values are generate from the inside of the ring to the outside
  20529. const segment = thetaStart + i / thetaSegments * thetaLength; // vertex
  20530. vertex.x = radius * Math.cos(segment);
  20531. vertex.y = radius * Math.sin(segment);
  20532. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  20533. normals.push(0, 0, 1); // uv
  20534. uv.x = (vertex.x / outerRadius + 1) / 2;
  20535. uv.y = (vertex.y / outerRadius + 1) / 2;
  20536. uvs.push(uv.x, uv.y);
  20537. } // increase the radius for next row of vertices
  20538. radius += radiusStep;
  20539. } // indices
  20540. for (let j = 0; j < phiSegments; j++) {
  20541. const thetaSegmentLevel = j * (thetaSegments + 1);
  20542. for (let i = 0; i < thetaSegments; i++) {
  20543. const segment = i + thetaSegmentLevel;
  20544. const a = segment;
  20545. const b = segment + thetaSegments + 1;
  20546. const c = segment + thetaSegments + 2;
  20547. const d = segment + 1; // faces
  20548. indices.push(a, b, d);
  20549. indices.push(b, c, d);
  20550. }
  20551. } // build geometry
  20552. this.setIndex(indices);
  20553. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20554. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20555. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20556. }
  20557. static fromJSON(data) {
  20558. return new RingGeometry(data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
  20559. }
  20560. }
  20561. class ShapeGeometry extends BufferGeometry {
  20562. constructor(shapes = new Shape([new Vector2(0, 0.5), new Vector2(-0.5, -0.5), new Vector2(0.5, -0.5)]), curveSegments = 12) {
  20563. super();
  20564. this.type = 'ShapeGeometry';
  20565. this.parameters = {
  20566. shapes: shapes,
  20567. curveSegments: curveSegments
  20568. }; // buffers
  20569. const indices = [];
  20570. const vertices = [];
  20571. const normals = [];
  20572. const uvs = []; // helper variables
  20573. let groupStart = 0;
  20574. let groupCount = 0; // allow single and array values for "shapes" parameter
  20575. if (Array.isArray(shapes) === false) {
  20576. addShape(shapes);
  20577. } else {
  20578. for (let i = 0; i < shapes.length; i++) {
  20579. addShape(shapes[i]);
  20580. this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
  20581. groupStart += groupCount;
  20582. groupCount = 0;
  20583. }
  20584. } // build geometry
  20585. this.setIndex(indices);
  20586. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20587. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20588. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // helper functions
  20589. function addShape(shape) {
  20590. const indexOffset = vertices.length / 3;
  20591. const points = shape.extractPoints(curveSegments);
  20592. let shapeVertices = points.shape;
  20593. const shapeHoles = points.holes; // check direction of vertices
  20594. if (ShapeUtils.isClockWise(shapeVertices) === false) {
  20595. shapeVertices = shapeVertices.reverse();
  20596. }
  20597. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  20598. const shapeHole = shapeHoles[i];
  20599. if (ShapeUtils.isClockWise(shapeHole) === true) {
  20600. shapeHoles[i] = shapeHole.reverse();
  20601. }
  20602. }
  20603. const faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); // join vertices of inner and outer paths to a single array
  20604. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  20605. const shapeHole = shapeHoles[i];
  20606. shapeVertices = shapeVertices.concat(shapeHole);
  20607. } // vertices, normals, uvs
  20608. for (let i = 0, l = shapeVertices.length; i < l; i++) {
  20609. const vertex = shapeVertices[i];
  20610. vertices.push(vertex.x, vertex.y, 0);
  20611. normals.push(0, 0, 1);
  20612. uvs.push(vertex.x, vertex.y); // world uvs
  20613. } // incides
  20614. for (let i = 0, l = faces.length; i < l; i++) {
  20615. const face = faces[i];
  20616. const a = face[0] + indexOffset;
  20617. const b = face[1] + indexOffset;
  20618. const c = face[2] + indexOffset;
  20619. indices.push(a, b, c);
  20620. groupCount += 3;
  20621. }
  20622. }
  20623. }
  20624. toJSON() {
  20625. const data = super.toJSON();
  20626. const shapes = this.parameters.shapes;
  20627. return toJSON(shapes, data);
  20628. }
  20629. static fromJSON(data, shapes) {
  20630. const geometryShapes = [];
  20631. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  20632. const shape = shapes[data.shapes[j]];
  20633. geometryShapes.push(shape);
  20634. }
  20635. return new ShapeGeometry(geometryShapes, data.curveSegments);
  20636. }
  20637. }
  20638. function toJSON(shapes, data) {
  20639. data.shapes = [];
  20640. if (Array.isArray(shapes)) {
  20641. for (let i = 0, l = shapes.length; i < l; i++) {
  20642. const shape = shapes[i];
  20643. data.shapes.push(shape.uuid);
  20644. }
  20645. } else {
  20646. data.shapes.push(shapes.uuid);
  20647. }
  20648. return data;
  20649. }
  20650. class SphereGeometry extends BufferGeometry {
  20651. constructor(radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI) {
  20652. super();
  20653. this.type = 'SphereGeometry';
  20654. this.parameters = {
  20655. radius: radius,
  20656. widthSegments: widthSegments,
  20657. heightSegments: heightSegments,
  20658. phiStart: phiStart,
  20659. phiLength: phiLength,
  20660. thetaStart: thetaStart,
  20661. thetaLength: thetaLength
  20662. };
  20663. widthSegments = Math.max(3, Math.floor(widthSegments));
  20664. heightSegments = Math.max(2, Math.floor(heightSegments));
  20665. const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
  20666. let index = 0;
  20667. const grid = [];
  20668. const vertex = new Vector3();
  20669. const normal = new Vector3(); // buffers
  20670. const indices = [];
  20671. const vertices = [];
  20672. const normals = [];
  20673. const uvs = []; // generate vertices, normals and uvs
  20674. for (let iy = 0; iy <= heightSegments; iy++) {
  20675. const verticesRow = [];
  20676. const v = iy / heightSegments; // special case for the poles
  20677. let uOffset = 0;
  20678. if (iy == 0 && thetaStart == 0) {
  20679. uOffset = 0.5 / widthSegments;
  20680. } else if (iy == heightSegments && thetaEnd == Math.PI) {
  20681. uOffset = -0.5 / widthSegments;
  20682. }
  20683. for (let ix = 0; ix <= widthSegments; ix++) {
  20684. const u = ix / widthSegments; // vertex
  20685. vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  20686. vertex.y = radius * Math.cos(thetaStart + v * thetaLength);
  20687. vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  20688. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  20689. normal.copy(vertex).normalize();
  20690. normals.push(normal.x, normal.y, normal.z); // uv
  20691. uvs.push(u + uOffset, 1 - v);
  20692. verticesRow.push(index++);
  20693. }
  20694. grid.push(verticesRow);
  20695. } // indices
  20696. for (let iy = 0; iy < heightSegments; iy++) {
  20697. for (let ix = 0; ix < widthSegments; ix++) {
  20698. const a = grid[iy][ix + 1];
  20699. const b = grid[iy][ix];
  20700. const c = grid[iy + 1][ix];
  20701. const d = grid[iy + 1][ix + 1];
  20702. if (iy !== 0 || thetaStart > 0) indices.push(a, b, d);
  20703. if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
  20704. }
  20705. } // build geometry
  20706. this.setIndex(indices);
  20707. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20708. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20709. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20710. }
  20711. static fromJSON(data) {
  20712. return new SphereGeometry(data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
  20713. }
  20714. }
  20715. class TetrahedronGeometry extends PolyhedronGeometry {
  20716. constructor(radius = 1, detail = 0) {
  20717. const vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
  20718. const indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
  20719. super(vertices, indices, radius, detail);
  20720. this.type = 'TetrahedronGeometry';
  20721. this.parameters = {
  20722. radius: radius,
  20723. detail: detail
  20724. };
  20725. }
  20726. static fromJSON(data) {
  20727. return new TetrahedronGeometry(data.radius, data.detail);
  20728. }
  20729. }
  20730. class TorusGeometry extends BufferGeometry {
  20731. constructor(radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2) {
  20732. super();
  20733. this.type = 'TorusGeometry';
  20734. this.parameters = {
  20735. radius: radius,
  20736. tube: tube,
  20737. radialSegments: radialSegments,
  20738. tubularSegments: tubularSegments,
  20739. arc: arc
  20740. };
  20741. radialSegments = Math.floor(radialSegments);
  20742. tubularSegments = Math.floor(tubularSegments); // buffers
  20743. const indices = [];
  20744. const vertices = [];
  20745. const normals = [];
  20746. const uvs = []; // helper variables
  20747. const center = new Vector3();
  20748. const vertex = new Vector3();
  20749. const normal = new Vector3(); // generate vertices, normals and uvs
  20750. for (let j = 0; j <= radialSegments; j++) {
  20751. for (let i = 0; i <= tubularSegments; i++) {
  20752. const u = i / tubularSegments * arc;
  20753. const v = j / radialSegments * Math.PI * 2; // vertex
  20754. vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
  20755. vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
  20756. vertex.z = tube * Math.sin(v);
  20757. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  20758. center.x = radius * Math.cos(u);
  20759. center.y = radius * Math.sin(u);
  20760. normal.subVectors(vertex, center).normalize();
  20761. normals.push(normal.x, normal.y, normal.z); // uv
  20762. uvs.push(i / tubularSegments);
  20763. uvs.push(j / radialSegments);
  20764. }
  20765. } // generate indices
  20766. for (let j = 1; j <= radialSegments; j++) {
  20767. for (let i = 1; i <= tubularSegments; i++) {
  20768. // indices
  20769. const a = (tubularSegments + 1) * j + i - 1;
  20770. const b = (tubularSegments + 1) * (j - 1) + i - 1;
  20771. const c = (tubularSegments + 1) * (j - 1) + i;
  20772. const d = (tubularSegments + 1) * j + i; // faces
  20773. indices.push(a, b, d);
  20774. indices.push(b, c, d);
  20775. }
  20776. } // build geometry
  20777. this.setIndex(indices);
  20778. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20779. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20780. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20781. }
  20782. static fromJSON(data) {
  20783. return new TorusGeometry(data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
  20784. }
  20785. }
  20786. class TorusKnotGeometry extends BufferGeometry {
  20787. constructor(radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3) {
  20788. super();
  20789. this.type = 'TorusKnotGeometry';
  20790. this.parameters = {
  20791. radius: radius,
  20792. tube: tube,
  20793. tubularSegments: tubularSegments,
  20794. radialSegments: radialSegments,
  20795. p: p,
  20796. q: q
  20797. };
  20798. tubularSegments = Math.floor(tubularSegments);
  20799. radialSegments = Math.floor(radialSegments); // buffers
  20800. const indices = [];
  20801. const vertices = [];
  20802. const normals = [];
  20803. const uvs = []; // helper variables
  20804. const vertex = new Vector3();
  20805. const normal = new Vector3();
  20806. const P1 = new Vector3();
  20807. const P2 = new Vector3();
  20808. const B = new Vector3();
  20809. const T = new Vector3();
  20810. const N = new Vector3(); // generate vertices, normals and uvs
  20811. for (let i = 0; i <= tubularSegments; ++i) {
  20812. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  20813. 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.
  20814. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  20815. calculatePositionOnCurve(u, p, q, radius, P1);
  20816. calculatePositionOnCurve(u + 0.01, p, q, radius, P2); // calculate orthonormal basis
  20817. T.subVectors(P2, P1);
  20818. N.addVectors(P2, P1);
  20819. B.crossVectors(T, N);
  20820. N.crossVectors(B, T); // normalize B, N. T can be ignored, we don't use it
  20821. B.normalize();
  20822. N.normalize();
  20823. for (let j = 0; j <= radialSegments; ++j) {
  20824. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  20825. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  20826. const v = j / radialSegments * Math.PI * 2;
  20827. const cx = -tube * Math.cos(v);
  20828. const cy = tube * Math.sin(v); // now calculate the final vertex position.
  20829. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  20830. vertex.x = P1.x + (cx * N.x + cy * B.x);
  20831. vertex.y = P1.y + (cx * N.y + cy * B.y);
  20832. vertex.z = P1.z + (cx * N.z + cy * B.z);
  20833. 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)
  20834. normal.subVectors(vertex, P1).normalize();
  20835. normals.push(normal.x, normal.y, normal.z); // uv
  20836. uvs.push(i / tubularSegments);
  20837. uvs.push(j / radialSegments);
  20838. }
  20839. } // generate indices
  20840. for (let j = 1; j <= tubularSegments; j++) {
  20841. for (let i = 1; i <= radialSegments; i++) {
  20842. // indices
  20843. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  20844. const b = (radialSegments + 1) * j + (i - 1);
  20845. const c = (radialSegments + 1) * j + i;
  20846. const d = (radialSegments + 1) * (j - 1) + i; // faces
  20847. indices.push(a, b, d);
  20848. indices.push(b, c, d);
  20849. }
  20850. } // build geometry
  20851. this.setIndex(indices);
  20852. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20853. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20854. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // this function calculates the current position on the torus curve
  20855. function calculatePositionOnCurve(u, p, q, radius, position) {
  20856. const cu = Math.cos(u);
  20857. const su = Math.sin(u);
  20858. const quOverP = q / p * u;
  20859. const cs = Math.cos(quOverP);
  20860. position.x = radius * (2 + cs) * 0.5 * cu;
  20861. position.y = radius * (2 + cs) * su * 0.5;
  20862. position.z = radius * Math.sin(quOverP) * 0.5;
  20863. }
  20864. }
  20865. static fromJSON(data) {
  20866. return new TorusKnotGeometry(data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
  20867. }
  20868. }
  20869. class TubeGeometry extends BufferGeometry {
  20870. constructor(path = new QuadraticBezierCurve3(new Vector3(-1, -1, 0), new Vector3(-1, 1, 0), new Vector3(1, 1, 0)), tubularSegments = 64, radius = 1, radialSegments = 8, closed = false) {
  20871. super();
  20872. this.type = 'TubeGeometry';
  20873. this.parameters = {
  20874. path: path,
  20875. tubularSegments: tubularSegments,
  20876. radius: radius,
  20877. radialSegments: radialSegments,
  20878. closed: closed
  20879. };
  20880. const frames = path.computeFrenetFrames(tubularSegments, closed); // expose internals
  20881. this.tangents = frames.tangents;
  20882. this.normals = frames.normals;
  20883. this.binormals = frames.binormals; // helper variables
  20884. const vertex = new Vector3();
  20885. const normal = new Vector3();
  20886. const uv = new Vector2();
  20887. let P = new Vector3(); // buffer
  20888. const vertices = [];
  20889. const normals = [];
  20890. const uvs = [];
  20891. const indices = []; // create buffer data
  20892. generateBufferData(); // build geometry
  20893. this.setIndex(indices);
  20894. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20895. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20896. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // functions
  20897. function generateBufferData() {
  20898. for (let i = 0; i < tubularSegments; i++) {
  20899. generateSegment(i);
  20900. } // if the geometry is not closed, generate the last row of vertices and normals
  20901. // at the regular position on the given path
  20902. //
  20903. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  20904. generateSegment(closed === false ? tubularSegments : 0); // uvs are generated in a separate function.
  20905. // this makes it easy compute correct values for closed geometries
  20906. generateUVs(); // finally create faces
  20907. generateIndices();
  20908. }
  20909. function generateSegment(i) {
  20910. // we use getPointAt to sample evenly distributed points from the given path
  20911. P = path.getPointAt(i / tubularSegments, P); // retrieve corresponding normal and binormal
  20912. const N = frames.normals[i];
  20913. const B = frames.binormals[i]; // generate normals and vertices for the current segment
  20914. for (let j = 0; j <= radialSegments; j++) {
  20915. const v = j / radialSegments * Math.PI * 2;
  20916. const sin = Math.sin(v);
  20917. const cos = -Math.cos(v); // normal
  20918. normal.x = cos * N.x + sin * B.x;
  20919. normal.y = cos * N.y + sin * B.y;
  20920. normal.z = cos * N.z + sin * B.z;
  20921. normal.normalize();
  20922. normals.push(normal.x, normal.y, normal.z); // vertex
  20923. vertex.x = P.x + radius * normal.x;
  20924. vertex.y = P.y + radius * normal.y;
  20925. vertex.z = P.z + radius * normal.z;
  20926. vertices.push(vertex.x, vertex.y, vertex.z);
  20927. }
  20928. }
  20929. function generateIndices() {
  20930. for (let j = 1; j <= tubularSegments; j++) {
  20931. for (let i = 1; i <= radialSegments; i++) {
  20932. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  20933. const b = (radialSegments + 1) * j + (i - 1);
  20934. const c = (radialSegments + 1) * j + i;
  20935. const d = (radialSegments + 1) * (j - 1) + i; // faces
  20936. indices.push(a, b, d);
  20937. indices.push(b, c, d);
  20938. }
  20939. }
  20940. }
  20941. function generateUVs() {
  20942. for (let i = 0; i <= tubularSegments; i++) {
  20943. for (let j = 0; j <= radialSegments; j++) {
  20944. uv.x = i / tubularSegments;
  20945. uv.y = j / radialSegments;
  20946. uvs.push(uv.x, uv.y);
  20947. }
  20948. }
  20949. }
  20950. }
  20951. toJSON() {
  20952. const data = super.toJSON();
  20953. data.path = this.parameters.path.toJSON();
  20954. return data;
  20955. }
  20956. static fromJSON(data) {
  20957. // This only works for built-in curves (e.g. CatmullRomCurve3).
  20958. // User defined curves or instances of CurvePath will not be deserialized.
  20959. return new TubeGeometry(new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
  20960. }
  20961. }
  20962. class WireframeGeometry extends BufferGeometry {
  20963. constructor(geometry = null) {
  20964. super();
  20965. this.type = 'WireframeGeometry';
  20966. this.parameters = {
  20967. geometry: geometry
  20968. };
  20969. if (geometry !== null) {
  20970. // buffer
  20971. const vertices = [];
  20972. const edges = new Set(); // helper variables
  20973. const start = new Vector3();
  20974. const end = new Vector3();
  20975. if (geometry.index !== null) {
  20976. // indexed BufferGeometry
  20977. const position = geometry.attributes.position;
  20978. const indices = geometry.index;
  20979. let groups = geometry.groups;
  20980. if (groups.length === 0) {
  20981. groups = [{
  20982. start: 0,
  20983. count: indices.count,
  20984. materialIndex: 0
  20985. }];
  20986. } // create a data structure that contains all eges without duplicates
  20987. for (let o = 0, ol = groups.length; o < ol; ++o) {
  20988. const group = groups[o];
  20989. const groupStart = group.start;
  20990. const groupCount = group.count;
  20991. for (let i = groupStart, l = groupStart + groupCount; i < l; i += 3) {
  20992. for (let j = 0; j < 3; j++) {
  20993. const index1 = indices.getX(i + j);
  20994. const index2 = indices.getX(i + (j + 1) % 3);
  20995. start.fromBufferAttribute(position, index1);
  20996. end.fromBufferAttribute(position, index2);
  20997. if (isUniqueEdge(start, end, edges) === true) {
  20998. vertices.push(start.x, start.y, start.z);
  20999. vertices.push(end.x, end.y, end.z);
  21000. }
  21001. }
  21002. }
  21003. }
  21004. } else {
  21005. // non-indexed BufferGeometry
  21006. const position = geometry.attributes.position;
  21007. for (let i = 0, l = position.count / 3; i < l; i++) {
  21008. for (let j = 0; j < 3; j++) {
  21009. // three edges per triangle, an edge is represented as (index1, index2)
  21010. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  21011. const index1 = 3 * i + j;
  21012. const index2 = 3 * i + (j + 1) % 3;
  21013. start.fromBufferAttribute(position, index1);
  21014. end.fromBufferAttribute(position, index2);
  21015. if (isUniqueEdge(start, end, edges) === true) {
  21016. vertices.push(start.x, start.y, start.z);
  21017. vertices.push(end.x, end.y, end.z);
  21018. }
  21019. }
  21020. }
  21021. } // build geometry
  21022. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  21023. }
  21024. }
  21025. }
  21026. function isUniqueEdge(start, end, edges) {
  21027. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  21028. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  21029. if (edges.has(hash1) === true || edges.has(hash2) === true) {
  21030. return false;
  21031. } else {
  21032. edges.add(hash1, hash2);
  21033. return true;
  21034. }
  21035. }
  21036. var Geometries = /*#__PURE__*/Object.freeze({
  21037. __proto__: null,
  21038. BoxGeometry: BoxGeometry,
  21039. BoxBufferGeometry: BoxGeometry,
  21040. CircleGeometry: CircleGeometry,
  21041. CircleBufferGeometry: CircleGeometry,
  21042. ConeGeometry: ConeGeometry,
  21043. ConeBufferGeometry: ConeGeometry,
  21044. CylinderGeometry: CylinderGeometry,
  21045. CylinderBufferGeometry: CylinderGeometry,
  21046. DodecahedronGeometry: DodecahedronGeometry,
  21047. DodecahedronBufferGeometry: DodecahedronGeometry,
  21048. EdgesGeometry: EdgesGeometry,
  21049. ExtrudeGeometry: ExtrudeGeometry,
  21050. ExtrudeBufferGeometry: ExtrudeGeometry,
  21051. IcosahedronGeometry: IcosahedronGeometry,
  21052. IcosahedronBufferGeometry: IcosahedronGeometry,
  21053. LatheGeometry: LatheGeometry,
  21054. LatheBufferGeometry: LatheGeometry,
  21055. OctahedronGeometry: OctahedronGeometry,
  21056. OctahedronBufferGeometry: OctahedronGeometry,
  21057. PlaneGeometry: PlaneGeometry,
  21058. PlaneBufferGeometry: PlaneGeometry,
  21059. PolyhedronGeometry: PolyhedronGeometry,
  21060. PolyhedronBufferGeometry: PolyhedronGeometry,
  21061. RingGeometry: RingGeometry,
  21062. RingBufferGeometry: RingGeometry,
  21063. ShapeGeometry: ShapeGeometry,
  21064. ShapeBufferGeometry: ShapeGeometry,
  21065. SphereGeometry: SphereGeometry,
  21066. SphereBufferGeometry: SphereGeometry,
  21067. TetrahedronGeometry: TetrahedronGeometry,
  21068. TetrahedronBufferGeometry: TetrahedronGeometry,
  21069. TorusGeometry: TorusGeometry,
  21070. TorusBufferGeometry: TorusGeometry,
  21071. TorusKnotGeometry: TorusKnotGeometry,
  21072. TorusKnotBufferGeometry: TorusKnotGeometry,
  21073. TubeGeometry: TubeGeometry,
  21074. TubeBufferGeometry: TubeGeometry,
  21075. WireframeGeometry: WireframeGeometry
  21076. });
  21077. /**
  21078. * parameters = {
  21079. * color: <THREE.Color>
  21080. * }
  21081. */
  21082. class ShadowMaterial extends Material {
  21083. constructor(parameters) {
  21084. super();
  21085. this.type = 'ShadowMaterial';
  21086. this.color = new Color(0x000000);
  21087. this.transparent = true;
  21088. this.setValues(parameters);
  21089. }
  21090. copy(source) {
  21091. super.copy(source);
  21092. this.color.copy(source.color);
  21093. return this;
  21094. }
  21095. }
  21096. ShadowMaterial.prototype.isShadowMaterial = true;
  21097. /**
  21098. * parameters = {
  21099. * color: <hex>,
  21100. * roughness: <float>,
  21101. * metalness: <float>,
  21102. * opacity: <float>,
  21103. *
  21104. * map: new THREE.Texture( <Image> ),
  21105. *
  21106. * lightMap: new THREE.Texture( <Image> ),
  21107. * lightMapIntensity: <float>
  21108. *
  21109. * aoMap: new THREE.Texture( <Image> ),
  21110. * aoMapIntensity: <float>
  21111. *
  21112. * emissive: <hex>,
  21113. * emissiveIntensity: <float>
  21114. * emissiveMap: new THREE.Texture( <Image> ),
  21115. *
  21116. * bumpMap: new THREE.Texture( <Image> ),
  21117. * bumpScale: <float>,
  21118. *
  21119. * normalMap: new THREE.Texture( <Image> ),
  21120. * normalMapType: THREE.TangentSpaceNormalMap,
  21121. * normalScale: <Vector2>,
  21122. *
  21123. * displacementMap: new THREE.Texture( <Image> ),
  21124. * displacementScale: <float>,
  21125. * displacementBias: <float>,
  21126. *
  21127. * roughnessMap: new THREE.Texture( <Image> ),
  21128. *
  21129. * metalnessMap: new THREE.Texture( <Image> ),
  21130. *
  21131. * alphaMap: new THREE.Texture( <Image> ),
  21132. *
  21133. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  21134. * envMapIntensity: <float>
  21135. *
  21136. * refractionRatio: <float>,
  21137. *
  21138. * wireframe: <boolean>,
  21139. * wireframeLinewidth: <float>,
  21140. *
  21141. * flatShading: <bool>
  21142. * }
  21143. */
  21144. class MeshStandardMaterial extends Material {
  21145. constructor(parameters) {
  21146. super();
  21147. this.defines = {
  21148. 'STANDARD': ''
  21149. };
  21150. this.type = 'MeshStandardMaterial';
  21151. this.color = new Color(0xffffff); // diffuse
  21152. this.roughness = 1.0;
  21153. this.metalness = 0.0;
  21154. this.map = null;
  21155. this.lightMap = null;
  21156. this.lightMapIntensity = 1.0;
  21157. this.aoMap = null;
  21158. this.aoMapIntensity = 1.0;
  21159. this.emissive = new Color(0x000000);
  21160. this.emissiveIntensity = 1.0;
  21161. this.emissiveMap = null;
  21162. this.bumpMap = null;
  21163. this.bumpScale = 1;
  21164. this.normalMap = null;
  21165. this.normalMapType = TangentSpaceNormalMap;
  21166. this.normalScale = new Vector2(1, 1);
  21167. this.displacementMap = null;
  21168. this.displacementScale = 1;
  21169. this.displacementBias = 0;
  21170. this.roughnessMap = null;
  21171. this.metalnessMap = null;
  21172. this.alphaMap = null;
  21173. this.envMap = null;
  21174. this.envMapIntensity = 1.0;
  21175. this.refractionRatio = 0.98;
  21176. this.wireframe = false;
  21177. this.wireframeLinewidth = 1;
  21178. this.wireframeLinecap = 'round';
  21179. this.wireframeLinejoin = 'round';
  21180. this.flatShading = false;
  21181. this.setValues(parameters);
  21182. }
  21183. copy(source) {
  21184. super.copy(source);
  21185. this.defines = {
  21186. 'STANDARD': ''
  21187. };
  21188. this.color.copy(source.color);
  21189. this.roughness = source.roughness;
  21190. this.metalness = source.metalness;
  21191. this.map = source.map;
  21192. this.lightMap = source.lightMap;
  21193. this.lightMapIntensity = source.lightMapIntensity;
  21194. this.aoMap = source.aoMap;
  21195. this.aoMapIntensity = source.aoMapIntensity;
  21196. this.emissive.copy(source.emissive);
  21197. this.emissiveMap = source.emissiveMap;
  21198. this.emissiveIntensity = source.emissiveIntensity;
  21199. this.bumpMap = source.bumpMap;
  21200. this.bumpScale = source.bumpScale;
  21201. this.normalMap = source.normalMap;
  21202. this.normalMapType = source.normalMapType;
  21203. this.normalScale.copy(source.normalScale);
  21204. this.displacementMap = source.displacementMap;
  21205. this.displacementScale = source.displacementScale;
  21206. this.displacementBias = source.displacementBias;
  21207. this.roughnessMap = source.roughnessMap;
  21208. this.metalnessMap = source.metalnessMap;
  21209. this.alphaMap = source.alphaMap;
  21210. this.envMap = source.envMap;
  21211. this.envMapIntensity = source.envMapIntensity;
  21212. this.refractionRatio = source.refractionRatio;
  21213. this.wireframe = source.wireframe;
  21214. this.wireframeLinewidth = source.wireframeLinewidth;
  21215. this.wireframeLinecap = source.wireframeLinecap;
  21216. this.wireframeLinejoin = source.wireframeLinejoin;
  21217. this.flatShading = source.flatShading;
  21218. return this;
  21219. }
  21220. }
  21221. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  21222. /**
  21223. * parameters = {
  21224. * clearcoat: <float>,
  21225. * clearcoatMap: new THREE.Texture( <Image> ),
  21226. * clearcoatRoughness: <float>,
  21227. * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
  21228. * clearcoatNormalScale: <Vector2>,
  21229. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  21230. *
  21231. * ior: <float>,
  21232. * reflectivity: <float>,
  21233. *
  21234. * sheen: <float>,
  21235. * sheenColor: <Color>,
  21236. * sheenColorMap: new THREE.Texture( <Image> ),
  21237. * sheenRoughness: <float>,
  21238. * sheenRoughnessMap: new THREE.Texture( <Image> ),
  21239. *
  21240. * transmission: <float>,
  21241. * transmissionMap: new THREE.Texture( <Image> ),
  21242. *
  21243. * thickness: <float>,
  21244. * thicknessMap: new THREE.Texture( <Image> ),
  21245. * attenuationDistance: <float>,
  21246. * attenuationColor: <Color>,
  21247. *
  21248. * specularIntensity: <float>,
  21249. * specularIntensityMap: new THREE.Texture( <Image> ),
  21250. * specularColor: <Color>,
  21251. * specularColorMap: new THREE.Texture( <Image> )
  21252. * }
  21253. */
  21254. class MeshPhysicalMaterial extends MeshStandardMaterial {
  21255. constructor(parameters) {
  21256. super();
  21257. this.defines = {
  21258. 'STANDARD': '',
  21259. 'PHYSICAL': ''
  21260. };
  21261. this.type = 'MeshPhysicalMaterial';
  21262. this.clearcoatMap = null;
  21263. this.clearcoatRoughness = 0.0;
  21264. this.clearcoatRoughnessMap = null;
  21265. this.clearcoatNormalScale = new Vector2(1, 1);
  21266. this.clearcoatNormalMap = null;
  21267. this.ior = 1.5;
  21268. Object.defineProperty(this, 'reflectivity', {
  21269. get: function () {
  21270. return clamp(2.5 * (this.ior - 1) / (this.ior + 1), 0, 1);
  21271. },
  21272. set: function (reflectivity) {
  21273. this.ior = (1 + 0.4 * reflectivity) / (1 - 0.4 * reflectivity);
  21274. }
  21275. });
  21276. this.sheenColor = new Color(0x000000);
  21277. this.sheenColorMap = null;
  21278. this.sheenRoughness = 1.0;
  21279. this.sheenRoughnessMap = null;
  21280. this.transmissionMap = null;
  21281. this.thickness = 0;
  21282. this.thicknessMap = null;
  21283. this.attenuationDistance = 0.0;
  21284. this.attenuationColor = new Color(1, 1, 1);
  21285. this.specularIntensity = 1.0;
  21286. this.specularIntensityMap = null;
  21287. this.specularColor = new Color(1, 1, 1);
  21288. this.specularColorMap = null;
  21289. this._sheen = 0.0;
  21290. this._clearcoat = 0;
  21291. this._transmission = 0;
  21292. this.setValues(parameters);
  21293. }
  21294. get sheen() {
  21295. return this._sheen;
  21296. }
  21297. set sheen(value) {
  21298. if (this._sheen > 0 !== value > 0) {
  21299. this.version++;
  21300. }
  21301. this._sheen = value;
  21302. }
  21303. get clearcoat() {
  21304. return this._clearcoat;
  21305. }
  21306. set clearcoat(value) {
  21307. if (this._clearcoat > 0 !== value > 0) {
  21308. this.version++;
  21309. }
  21310. this._clearcoat = value;
  21311. }
  21312. get transmission() {
  21313. return this._transmission;
  21314. }
  21315. set transmission(value) {
  21316. if (this._transmission > 0 !== value > 0) {
  21317. this.version++;
  21318. }
  21319. this._transmission = value;
  21320. }
  21321. copy(source) {
  21322. super.copy(source);
  21323. this.defines = {
  21324. 'STANDARD': '',
  21325. 'PHYSICAL': ''
  21326. };
  21327. this.clearcoat = source.clearcoat;
  21328. this.clearcoatMap = source.clearcoatMap;
  21329. this.clearcoatRoughness = source.clearcoatRoughness;
  21330. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  21331. this.clearcoatNormalMap = source.clearcoatNormalMap;
  21332. this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
  21333. this.ior = source.ior;
  21334. this.sheen = source.sheen;
  21335. this.sheenColor.copy(source.sheenColor);
  21336. this.sheenColorMap = source.sheenColorMap;
  21337. this.sheenRoughness = source.sheenRoughness;
  21338. this.sheenRoughnessMap = source.sheenRoughnessMap;
  21339. this.transmission = source.transmission;
  21340. this.transmissionMap = source.transmissionMap;
  21341. this.thickness = source.thickness;
  21342. this.thicknessMap = source.thicknessMap;
  21343. this.attenuationDistance = source.attenuationDistance;
  21344. this.attenuationColor.copy(source.attenuationColor);
  21345. this.specularIntensity = source.specularIntensity;
  21346. this.specularIntensityMap = source.specularIntensityMap;
  21347. this.specularColor.copy(source.specularColor);
  21348. this.specularColorMap = source.specularColorMap;
  21349. return this;
  21350. }
  21351. }
  21352. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  21353. /**
  21354. * parameters = {
  21355. * color: <hex>,
  21356. * specular: <hex>,
  21357. * shininess: <float>,
  21358. * opacity: <float>,
  21359. *
  21360. * map: new THREE.Texture( <Image> ),
  21361. *
  21362. * lightMap: new THREE.Texture( <Image> ),
  21363. * lightMapIntensity: <float>
  21364. *
  21365. * aoMap: new THREE.Texture( <Image> ),
  21366. * aoMapIntensity: <float>
  21367. *
  21368. * emissive: <hex>,
  21369. * emissiveIntensity: <float>
  21370. * emissiveMap: new THREE.Texture( <Image> ),
  21371. *
  21372. * bumpMap: new THREE.Texture( <Image> ),
  21373. * bumpScale: <float>,
  21374. *
  21375. * normalMap: new THREE.Texture( <Image> ),
  21376. * normalMapType: THREE.TangentSpaceNormalMap,
  21377. * normalScale: <Vector2>,
  21378. *
  21379. * displacementMap: new THREE.Texture( <Image> ),
  21380. * displacementScale: <float>,
  21381. * displacementBias: <float>,
  21382. *
  21383. * specularMap: new THREE.Texture( <Image> ),
  21384. *
  21385. * alphaMap: new THREE.Texture( <Image> ),
  21386. *
  21387. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  21388. * combine: THREE.MultiplyOperation,
  21389. * reflectivity: <float>,
  21390. * refractionRatio: <float>,
  21391. *
  21392. * wireframe: <boolean>,
  21393. * wireframeLinewidth: <float>,
  21394. *
  21395. * flatShading: <bool>
  21396. * }
  21397. */
  21398. class MeshPhongMaterial extends Material {
  21399. constructor(parameters) {
  21400. super();
  21401. this.type = 'MeshPhongMaterial';
  21402. this.color = new Color(0xffffff); // diffuse
  21403. this.specular = new Color(0x111111);
  21404. this.shininess = 30;
  21405. this.map = null;
  21406. this.lightMap = null;
  21407. this.lightMapIntensity = 1.0;
  21408. this.aoMap = null;
  21409. this.aoMapIntensity = 1.0;
  21410. this.emissive = new Color(0x000000);
  21411. this.emissiveIntensity = 1.0;
  21412. this.emissiveMap = null;
  21413. this.bumpMap = null;
  21414. this.bumpScale = 1;
  21415. this.normalMap = null;
  21416. this.normalMapType = TangentSpaceNormalMap;
  21417. this.normalScale = new Vector2(1, 1);
  21418. this.displacementMap = null;
  21419. this.displacementScale = 1;
  21420. this.displacementBias = 0;
  21421. this.specularMap = null;
  21422. this.alphaMap = null;
  21423. this.envMap = null;
  21424. this.combine = MultiplyOperation;
  21425. this.reflectivity = 1;
  21426. this.refractionRatio = 0.98;
  21427. this.wireframe = false;
  21428. this.wireframeLinewidth = 1;
  21429. this.wireframeLinecap = 'round';
  21430. this.wireframeLinejoin = 'round';
  21431. this.flatShading = false;
  21432. this.setValues(parameters);
  21433. }
  21434. copy(source) {
  21435. super.copy(source);
  21436. this.color.copy(source.color);
  21437. this.specular.copy(source.specular);
  21438. this.shininess = source.shininess;
  21439. this.map = source.map;
  21440. this.lightMap = source.lightMap;
  21441. this.lightMapIntensity = source.lightMapIntensity;
  21442. this.aoMap = source.aoMap;
  21443. this.aoMapIntensity = source.aoMapIntensity;
  21444. this.emissive.copy(source.emissive);
  21445. this.emissiveMap = source.emissiveMap;
  21446. this.emissiveIntensity = source.emissiveIntensity;
  21447. this.bumpMap = source.bumpMap;
  21448. this.bumpScale = source.bumpScale;
  21449. this.normalMap = source.normalMap;
  21450. this.normalMapType = source.normalMapType;
  21451. this.normalScale.copy(source.normalScale);
  21452. this.displacementMap = source.displacementMap;
  21453. this.displacementScale = source.displacementScale;
  21454. this.displacementBias = source.displacementBias;
  21455. this.specularMap = source.specularMap;
  21456. this.alphaMap = source.alphaMap;
  21457. this.envMap = source.envMap;
  21458. this.combine = source.combine;
  21459. this.reflectivity = source.reflectivity;
  21460. this.refractionRatio = source.refractionRatio;
  21461. this.wireframe = source.wireframe;
  21462. this.wireframeLinewidth = source.wireframeLinewidth;
  21463. this.wireframeLinecap = source.wireframeLinecap;
  21464. this.wireframeLinejoin = source.wireframeLinejoin;
  21465. this.flatShading = source.flatShading;
  21466. return this;
  21467. }
  21468. }
  21469. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  21470. /**
  21471. * parameters = {
  21472. * color: <hex>,
  21473. *
  21474. * map: new THREE.Texture( <Image> ),
  21475. * gradientMap: new THREE.Texture( <Image> ),
  21476. *
  21477. * lightMap: new THREE.Texture( <Image> ),
  21478. * lightMapIntensity: <float>
  21479. *
  21480. * aoMap: new THREE.Texture( <Image> ),
  21481. * aoMapIntensity: <float>
  21482. *
  21483. * emissive: <hex>,
  21484. * emissiveIntensity: <float>
  21485. * emissiveMap: new THREE.Texture( <Image> ),
  21486. *
  21487. * bumpMap: new THREE.Texture( <Image> ),
  21488. * bumpScale: <float>,
  21489. *
  21490. * normalMap: new THREE.Texture( <Image> ),
  21491. * normalMapType: THREE.TangentSpaceNormalMap,
  21492. * normalScale: <Vector2>,
  21493. *
  21494. * displacementMap: new THREE.Texture( <Image> ),
  21495. * displacementScale: <float>,
  21496. * displacementBias: <float>,
  21497. *
  21498. * alphaMap: new THREE.Texture( <Image> ),
  21499. *
  21500. * wireframe: <boolean>,
  21501. * wireframeLinewidth: <float>,
  21502. *
  21503. * }
  21504. */
  21505. class MeshToonMaterial extends Material {
  21506. constructor(parameters) {
  21507. super();
  21508. this.defines = {
  21509. 'TOON': ''
  21510. };
  21511. this.type = 'MeshToonMaterial';
  21512. this.color = new Color(0xffffff);
  21513. this.map = null;
  21514. this.gradientMap = null;
  21515. this.lightMap = null;
  21516. this.lightMapIntensity = 1.0;
  21517. this.aoMap = null;
  21518. this.aoMapIntensity = 1.0;
  21519. this.emissive = new Color(0x000000);
  21520. this.emissiveIntensity = 1.0;
  21521. this.emissiveMap = null;
  21522. this.bumpMap = null;
  21523. this.bumpScale = 1;
  21524. this.normalMap = null;
  21525. this.normalMapType = TangentSpaceNormalMap;
  21526. this.normalScale = new Vector2(1, 1);
  21527. this.displacementMap = null;
  21528. this.displacementScale = 1;
  21529. this.displacementBias = 0;
  21530. this.alphaMap = null;
  21531. this.wireframe = false;
  21532. this.wireframeLinewidth = 1;
  21533. this.wireframeLinecap = 'round';
  21534. this.wireframeLinejoin = 'round';
  21535. this.setValues(parameters);
  21536. }
  21537. copy(source) {
  21538. super.copy(source);
  21539. this.color.copy(source.color);
  21540. this.map = source.map;
  21541. this.gradientMap = source.gradientMap;
  21542. this.lightMap = source.lightMap;
  21543. this.lightMapIntensity = source.lightMapIntensity;
  21544. this.aoMap = source.aoMap;
  21545. this.aoMapIntensity = source.aoMapIntensity;
  21546. this.emissive.copy(source.emissive);
  21547. this.emissiveMap = source.emissiveMap;
  21548. this.emissiveIntensity = source.emissiveIntensity;
  21549. this.bumpMap = source.bumpMap;
  21550. this.bumpScale = source.bumpScale;
  21551. this.normalMap = source.normalMap;
  21552. this.normalMapType = source.normalMapType;
  21553. this.normalScale.copy(source.normalScale);
  21554. this.displacementMap = source.displacementMap;
  21555. this.displacementScale = source.displacementScale;
  21556. this.displacementBias = source.displacementBias;
  21557. this.alphaMap = source.alphaMap;
  21558. this.wireframe = source.wireframe;
  21559. this.wireframeLinewidth = source.wireframeLinewidth;
  21560. this.wireframeLinecap = source.wireframeLinecap;
  21561. this.wireframeLinejoin = source.wireframeLinejoin;
  21562. return this;
  21563. }
  21564. }
  21565. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  21566. /**
  21567. * parameters = {
  21568. * opacity: <float>,
  21569. *
  21570. * bumpMap: new THREE.Texture( <Image> ),
  21571. * bumpScale: <float>,
  21572. *
  21573. * normalMap: new THREE.Texture( <Image> ),
  21574. * normalMapType: THREE.TangentSpaceNormalMap,
  21575. * normalScale: <Vector2>,
  21576. *
  21577. * displacementMap: new THREE.Texture( <Image> ),
  21578. * displacementScale: <float>,
  21579. * displacementBias: <float>,
  21580. *
  21581. * wireframe: <boolean>,
  21582. * wireframeLinewidth: <float>
  21583. *
  21584. * flatShading: <bool>
  21585. * }
  21586. */
  21587. class MeshNormalMaterial extends Material {
  21588. constructor(parameters) {
  21589. super();
  21590. this.type = 'MeshNormalMaterial';
  21591. this.bumpMap = null;
  21592. this.bumpScale = 1;
  21593. this.normalMap = null;
  21594. this.normalMapType = TangentSpaceNormalMap;
  21595. this.normalScale = new Vector2(1, 1);
  21596. this.displacementMap = null;
  21597. this.displacementScale = 1;
  21598. this.displacementBias = 0;
  21599. this.wireframe = false;
  21600. this.wireframeLinewidth = 1;
  21601. this.fog = false;
  21602. this.flatShading = false;
  21603. this.setValues(parameters);
  21604. }
  21605. copy(source) {
  21606. super.copy(source);
  21607. this.bumpMap = source.bumpMap;
  21608. this.bumpScale = source.bumpScale;
  21609. this.normalMap = source.normalMap;
  21610. this.normalMapType = source.normalMapType;
  21611. this.normalScale.copy(source.normalScale);
  21612. this.displacementMap = source.displacementMap;
  21613. this.displacementScale = source.displacementScale;
  21614. this.displacementBias = source.displacementBias;
  21615. this.wireframe = source.wireframe;
  21616. this.wireframeLinewidth = source.wireframeLinewidth;
  21617. this.flatShading = source.flatShading;
  21618. return this;
  21619. }
  21620. }
  21621. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  21622. /**
  21623. * parameters = {
  21624. * color: <hex>,
  21625. * opacity: <float>,
  21626. *
  21627. * map: new THREE.Texture( <Image> ),
  21628. *
  21629. * lightMap: new THREE.Texture( <Image> ),
  21630. * lightMapIntensity: <float>
  21631. *
  21632. * aoMap: new THREE.Texture( <Image> ),
  21633. * aoMapIntensity: <float>
  21634. *
  21635. * emissive: <hex>,
  21636. * emissiveIntensity: <float>
  21637. * emissiveMap: new THREE.Texture( <Image> ),
  21638. *
  21639. * specularMap: new THREE.Texture( <Image> ),
  21640. *
  21641. * alphaMap: new THREE.Texture( <Image> ),
  21642. *
  21643. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  21644. * combine: THREE.Multiply,
  21645. * reflectivity: <float>,
  21646. * refractionRatio: <float>,
  21647. *
  21648. * wireframe: <boolean>,
  21649. * wireframeLinewidth: <float>,
  21650. *
  21651. * }
  21652. */
  21653. class MeshLambertMaterial extends Material {
  21654. constructor(parameters) {
  21655. super();
  21656. this.type = 'MeshLambertMaterial';
  21657. this.color = new Color(0xffffff); // diffuse
  21658. this.map = null;
  21659. this.lightMap = null;
  21660. this.lightMapIntensity = 1.0;
  21661. this.aoMap = null;
  21662. this.aoMapIntensity = 1.0;
  21663. this.emissive = new Color(0x000000);
  21664. this.emissiveIntensity = 1.0;
  21665. this.emissiveMap = null;
  21666. this.specularMap = null;
  21667. this.alphaMap = null;
  21668. this.envMap = null;
  21669. this.combine = MultiplyOperation;
  21670. this.reflectivity = 1;
  21671. this.refractionRatio = 0.98;
  21672. this.wireframe = false;
  21673. this.wireframeLinewidth = 1;
  21674. this.wireframeLinecap = 'round';
  21675. this.wireframeLinejoin = 'round';
  21676. this.setValues(parameters);
  21677. }
  21678. copy(source) {
  21679. super.copy(source);
  21680. this.color.copy(source.color);
  21681. this.map = source.map;
  21682. this.lightMap = source.lightMap;
  21683. this.lightMapIntensity = source.lightMapIntensity;
  21684. this.aoMap = source.aoMap;
  21685. this.aoMapIntensity = source.aoMapIntensity;
  21686. this.emissive.copy(source.emissive);
  21687. this.emissiveMap = source.emissiveMap;
  21688. this.emissiveIntensity = source.emissiveIntensity;
  21689. this.specularMap = source.specularMap;
  21690. this.alphaMap = source.alphaMap;
  21691. this.envMap = source.envMap;
  21692. this.combine = source.combine;
  21693. this.reflectivity = source.reflectivity;
  21694. this.refractionRatio = source.refractionRatio;
  21695. this.wireframe = source.wireframe;
  21696. this.wireframeLinewidth = source.wireframeLinewidth;
  21697. this.wireframeLinecap = source.wireframeLinecap;
  21698. this.wireframeLinejoin = source.wireframeLinejoin;
  21699. return this;
  21700. }
  21701. }
  21702. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  21703. /**
  21704. * parameters = {
  21705. * color: <hex>,
  21706. * opacity: <float>,
  21707. *
  21708. * matcap: new THREE.Texture( <Image> ),
  21709. *
  21710. * map: new THREE.Texture( <Image> ),
  21711. *
  21712. * bumpMap: new THREE.Texture( <Image> ),
  21713. * bumpScale: <float>,
  21714. *
  21715. * normalMap: new THREE.Texture( <Image> ),
  21716. * normalMapType: THREE.TangentSpaceNormalMap,
  21717. * normalScale: <Vector2>,
  21718. *
  21719. * displacementMap: new THREE.Texture( <Image> ),
  21720. * displacementScale: <float>,
  21721. * displacementBias: <float>,
  21722. *
  21723. * alphaMap: new THREE.Texture( <Image> ),
  21724. *
  21725. * flatShading: <bool>
  21726. * }
  21727. */
  21728. class MeshMatcapMaterial extends Material {
  21729. constructor(parameters) {
  21730. super();
  21731. this.defines = {
  21732. 'MATCAP': ''
  21733. };
  21734. this.type = 'MeshMatcapMaterial';
  21735. this.color = new Color(0xffffff); // diffuse
  21736. this.matcap = null;
  21737. this.map = null;
  21738. this.bumpMap = null;
  21739. this.bumpScale = 1;
  21740. this.normalMap = null;
  21741. this.normalMapType = TangentSpaceNormalMap;
  21742. this.normalScale = new Vector2(1, 1);
  21743. this.displacementMap = null;
  21744. this.displacementScale = 1;
  21745. this.displacementBias = 0;
  21746. this.alphaMap = null;
  21747. this.flatShading = false;
  21748. this.setValues(parameters);
  21749. }
  21750. copy(source) {
  21751. super.copy(source);
  21752. this.defines = {
  21753. 'MATCAP': ''
  21754. };
  21755. this.color.copy(source.color);
  21756. this.matcap = source.matcap;
  21757. this.map = source.map;
  21758. this.bumpMap = source.bumpMap;
  21759. this.bumpScale = source.bumpScale;
  21760. this.normalMap = source.normalMap;
  21761. this.normalMapType = source.normalMapType;
  21762. this.normalScale.copy(source.normalScale);
  21763. this.displacementMap = source.displacementMap;
  21764. this.displacementScale = source.displacementScale;
  21765. this.displacementBias = source.displacementBias;
  21766. this.alphaMap = source.alphaMap;
  21767. this.flatShading = source.flatShading;
  21768. return this;
  21769. }
  21770. }
  21771. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  21772. /**
  21773. * parameters = {
  21774. * color: <hex>,
  21775. * opacity: <float>,
  21776. *
  21777. * linewidth: <float>,
  21778. *
  21779. * scale: <float>,
  21780. * dashSize: <float>,
  21781. * gapSize: <float>
  21782. * }
  21783. */
  21784. class LineDashedMaterial extends LineBasicMaterial {
  21785. constructor(parameters) {
  21786. super();
  21787. this.type = 'LineDashedMaterial';
  21788. this.scale = 1;
  21789. this.dashSize = 3;
  21790. this.gapSize = 1;
  21791. this.setValues(parameters);
  21792. }
  21793. copy(source) {
  21794. super.copy(source);
  21795. this.scale = source.scale;
  21796. this.dashSize = source.dashSize;
  21797. this.gapSize = source.gapSize;
  21798. return this;
  21799. }
  21800. }
  21801. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  21802. var Materials = /*#__PURE__*/Object.freeze({
  21803. __proto__: null,
  21804. ShadowMaterial: ShadowMaterial,
  21805. SpriteMaterial: SpriteMaterial,
  21806. RawShaderMaterial: RawShaderMaterial,
  21807. ShaderMaterial: ShaderMaterial,
  21808. PointsMaterial: PointsMaterial,
  21809. MeshPhysicalMaterial: MeshPhysicalMaterial,
  21810. MeshStandardMaterial: MeshStandardMaterial,
  21811. MeshPhongMaterial: MeshPhongMaterial,
  21812. MeshToonMaterial: MeshToonMaterial,
  21813. MeshNormalMaterial: MeshNormalMaterial,
  21814. MeshLambertMaterial: MeshLambertMaterial,
  21815. MeshDepthMaterial: MeshDepthMaterial,
  21816. MeshDistanceMaterial: MeshDistanceMaterial,
  21817. MeshBasicMaterial: MeshBasicMaterial,
  21818. MeshMatcapMaterial: MeshMatcapMaterial,
  21819. LineDashedMaterial: LineDashedMaterial,
  21820. LineBasicMaterial: LineBasicMaterial,
  21821. Material: Material
  21822. });
  21823. const AnimationUtils = {
  21824. // same as Array.prototype.slice, but also works on typed arrays
  21825. arraySlice: function (array, from, to) {
  21826. if (AnimationUtils.isTypedArray(array)) {
  21827. // in ios9 array.subarray(from, undefined) will return empty array
  21828. // but array.subarray(from) or array.subarray(from, len) is correct
  21829. return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
  21830. }
  21831. return array.slice(from, to);
  21832. },
  21833. // converts an array to a specific type
  21834. convertArray: function (array, type, forceClone) {
  21835. if (!array || // let 'undefined' and 'null' pass
  21836. !forceClone && array.constructor === type) return array;
  21837. if (typeof type.BYTES_PER_ELEMENT === 'number') {
  21838. return new type(array); // create typed array
  21839. }
  21840. return Array.prototype.slice.call(array); // create Array
  21841. },
  21842. isTypedArray: function (object) {
  21843. return ArrayBuffer.isView(object) && !(object instanceof DataView);
  21844. },
  21845. // returns an array by which times and values can be sorted
  21846. getKeyframeOrder: function (times) {
  21847. function compareTime(i, j) {
  21848. return times[i] - times[j];
  21849. }
  21850. const n = times.length;
  21851. const result = new Array(n);
  21852. for (let i = 0; i !== n; ++i) result[i] = i;
  21853. result.sort(compareTime);
  21854. return result;
  21855. },
  21856. // uses the array previously returned by 'getKeyframeOrder' to sort data
  21857. sortedArray: function (values, stride, order) {
  21858. const nValues = values.length;
  21859. const result = new values.constructor(nValues);
  21860. for (let i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {
  21861. const srcOffset = order[i] * stride;
  21862. for (let j = 0; j !== stride; ++j) {
  21863. result[dstOffset++] = values[srcOffset + j];
  21864. }
  21865. }
  21866. return result;
  21867. },
  21868. // function for parsing AOS keyframe formats
  21869. flattenJSON: function (jsonKeys, times, values, valuePropertyName) {
  21870. let i = 1,
  21871. key = jsonKeys[0];
  21872. while (key !== undefined && key[valuePropertyName] === undefined) {
  21873. key = jsonKeys[i++];
  21874. }
  21875. if (key === undefined) return; // no data
  21876. let value = key[valuePropertyName];
  21877. if (value === undefined) return; // no data
  21878. if (Array.isArray(value)) {
  21879. do {
  21880. value = key[valuePropertyName];
  21881. if (value !== undefined) {
  21882. times.push(key.time);
  21883. values.push.apply(values, value); // push all elements
  21884. }
  21885. key = jsonKeys[i++];
  21886. } while (key !== undefined);
  21887. } else if (value.toArray !== undefined) {
  21888. // ...assume THREE.Math-ish
  21889. do {
  21890. value = key[valuePropertyName];
  21891. if (value !== undefined) {
  21892. times.push(key.time);
  21893. value.toArray(values, values.length);
  21894. }
  21895. key = jsonKeys[i++];
  21896. } while (key !== undefined);
  21897. } else {
  21898. // otherwise push as-is
  21899. do {
  21900. value = key[valuePropertyName];
  21901. if (value !== undefined) {
  21902. times.push(key.time);
  21903. values.push(value);
  21904. }
  21905. key = jsonKeys[i++];
  21906. } while (key !== undefined);
  21907. }
  21908. },
  21909. subclip: function (sourceClip, name, startFrame, endFrame, fps = 30) {
  21910. const clip = sourceClip.clone();
  21911. clip.name = name;
  21912. const tracks = [];
  21913. for (let i = 0; i < clip.tracks.length; ++i) {
  21914. const track = clip.tracks[i];
  21915. const valueSize = track.getValueSize();
  21916. const times = [];
  21917. const values = [];
  21918. for (let j = 0; j < track.times.length; ++j) {
  21919. const frame = track.times[j] * fps;
  21920. if (frame < startFrame || frame >= endFrame) continue;
  21921. times.push(track.times[j]);
  21922. for (let k = 0; k < valueSize; ++k) {
  21923. values.push(track.values[j * valueSize + k]);
  21924. }
  21925. }
  21926. if (times.length === 0) continue;
  21927. track.times = AnimationUtils.convertArray(times, track.times.constructor);
  21928. track.values = AnimationUtils.convertArray(values, track.values.constructor);
  21929. tracks.push(track);
  21930. }
  21931. clip.tracks = tracks; // find minimum .times value across all tracks in the trimmed clip
  21932. let minStartTime = Infinity;
  21933. for (let i = 0; i < clip.tracks.length; ++i) {
  21934. if (minStartTime > clip.tracks[i].times[0]) {
  21935. minStartTime = clip.tracks[i].times[0];
  21936. }
  21937. } // shift all tracks such that clip begins at t=0
  21938. for (let i = 0; i < clip.tracks.length; ++i) {
  21939. clip.tracks[i].shift(-1 * minStartTime);
  21940. }
  21941. clip.resetDuration();
  21942. return clip;
  21943. },
  21944. makeClipAdditive: function (targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30) {
  21945. if (fps <= 0) fps = 30;
  21946. const numTracks = referenceClip.tracks.length;
  21947. const referenceTime = referenceFrame / fps; // Make each track's values relative to the values at the reference frame
  21948. for (let i = 0; i < numTracks; ++i) {
  21949. const referenceTrack = referenceClip.tracks[i];
  21950. const referenceTrackType = referenceTrack.ValueTypeName; // Skip this track if it's non-numeric
  21951. if (referenceTrackType === 'bool' || referenceTrackType === 'string') continue; // Find the track in the target clip whose name and type matches the reference track
  21952. const targetTrack = targetClip.tracks.find(function (track) {
  21953. return track.name === referenceTrack.name && track.ValueTypeName === referenceTrackType;
  21954. });
  21955. if (targetTrack === undefined) continue;
  21956. let referenceOffset = 0;
  21957. const referenceValueSize = referenceTrack.getValueSize();
  21958. if (referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  21959. referenceOffset = referenceValueSize / 3;
  21960. }
  21961. let targetOffset = 0;
  21962. const targetValueSize = targetTrack.getValueSize();
  21963. if (targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  21964. targetOffset = targetValueSize / 3;
  21965. }
  21966. const lastIndex = referenceTrack.times.length - 1;
  21967. let referenceValue; // Find the value to subtract out of the track
  21968. if (referenceTime <= referenceTrack.times[0]) {
  21969. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  21970. const startIndex = referenceOffset;
  21971. const endIndex = referenceValueSize - referenceOffset;
  21972. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
  21973. } else if (referenceTime >= referenceTrack.times[lastIndex]) {
  21974. // Reference frame is after the last keyframe, so just use the last keyframe
  21975. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  21976. const endIndex = startIndex + referenceValueSize - referenceOffset;
  21977. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
  21978. } else {
  21979. // Interpolate to the reference value
  21980. const interpolant = referenceTrack.createInterpolant();
  21981. const startIndex = referenceOffset;
  21982. const endIndex = referenceValueSize - referenceOffset;
  21983. interpolant.evaluate(referenceTime);
  21984. referenceValue = AnimationUtils.arraySlice(interpolant.resultBuffer, startIndex, endIndex);
  21985. } // Conjugate the quaternion
  21986. if (referenceTrackType === 'quaternion') {
  21987. const referenceQuat = new Quaternion().fromArray(referenceValue).normalize().conjugate();
  21988. referenceQuat.toArray(referenceValue);
  21989. } // Subtract the reference value from all of the track values
  21990. const numTimes = targetTrack.times.length;
  21991. for (let j = 0; j < numTimes; ++j) {
  21992. const valueStart = j * targetValueSize + targetOffset;
  21993. if (referenceTrackType === 'quaternion') {
  21994. // Multiply the conjugate for quaternion track types
  21995. Quaternion.multiplyQuaternionsFlat(targetTrack.values, valueStart, referenceValue, 0, targetTrack.values, valueStart);
  21996. } else {
  21997. const valueEnd = targetValueSize - targetOffset * 2; // Subtract each value for all other numeric track types
  21998. for (let k = 0; k < valueEnd; ++k) {
  21999. targetTrack.values[valueStart + k] -= referenceValue[k];
  22000. }
  22001. }
  22002. }
  22003. }
  22004. targetClip.blendMode = AdditiveAnimationBlendMode;
  22005. return targetClip;
  22006. }
  22007. };
  22008. /**
  22009. * Abstract base class of interpolants over parametric samples.
  22010. *
  22011. * The parameter domain is one dimensional, typically the time or a path
  22012. * along a curve defined by the data.
  22013. *
  22014. * The sample values can have any dimensionality and derived classes may
  22015. * apply special interpretations to the data.
  22016. *
  22017. * This class provides the interval seek in a Template Method, deferring
  22018. * the actual interpolation to derived classes.
  22019. *
  22020. * Time complexity is O(1) for linear access crossing at most two points
  22021. * and O(log N) for random access, where N is the number of positions.
  22022. *
  22023. * References:
  22024. *
  22025. * http://www.oodesign.com/template-method-pattern.html
  22026. *
  22027. */
  22028. class Interpolant {
  22029. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  22030. this.parameterPositions = parameterPositions;
  22031. this._cachedIndex = 0;
  22032. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
  22033. this.sampleValues = sampleValues;
  22034. this.valueSize = sampleSize;
  22035. this.settings = null;
  22036. this.DefaultSettings_ = {};
  22037. }
  22038. evaluate(t) {
  22039. const pp = this.parameterPositions;
  22040. let i1 = this._cachedIndex,
  22041. t1 = pp[i1],
  22042. t0 = pp[i1 - 1];
  22043. validate_interval: {
  22044. seek: {
  22045. let right;
  22046. linear_scan: {
  22047. //- See http://jsperf.com/comparison-to-undefined/3
  22048. //- slower code:
  22049. //-
  22050. //- if ( t >= t1 || t1 === undefined ) {
  22051. forward_scan: if (!(t < t1)) {
  22052. for (let giveUpAt = i1 + 2;;) {
  22053. if (t1 === undefined) {
  22054. if (t < t0) break forward_scan; // after end
  22055. i1 = pp.length;
  22056. this._cachedIndex = i1;
  22057. return this.afterEnd_(i1 - 1, t, t0);
  22058. }
  22059. if (i1 === giveUpAt) break; // this loop
  22060. t0 = t1;
  22061. t1 = pp[++i1];
  22062. if (t < t1) {
  22063. // we have arrived at the sought interval
  22064. break seek;
  22065. }
  22066. } // prepare binary search on the right side of the index
  22067. right = pp.length;
  22068. break linear_scan;
  22069. } //- slower code:
  22070. //- if ( t < t0 || t0 === undefined ) {
  22071. if (!(t >= t0)) {
  22072. // looping?
  22073. const t1global = pp[1];
  22074. if (t < t1global) {
  22075. i1 = 2; // + 1, using the scan for the details
  22076. t0 = t1global;
  22077. } // linear reverse scan
  22078. for (let giveUpAt = i1 - 2;;) {
  22079. if (t0 === undefined) {
  22080. // before start
  22081. this._cachedIndex = 0;
  22082. return this.beforeStart_(0, t, t1);
  22083. }
  22084. if (i1 === giveUpAt) break; // this loop
  22085. t1 = t0;
  22086. t0 = pp[--i1 - 1];
  22087. if (t >= t0) {
  22088. // we have arrived at the sought interval
  22089. break seek;
  22090. }
  22091. } // prepare binary search on the left side of the index
  22092. right = i1;
  22093. i1 = 0;
  22094. break linear_scan;
  22095. } // the interval is valid
  22096. break validate_interval;
  22097. } // linear scan
  22098. // binary search
  22099. while (i1 < right) {
  22100. const mid = i1 + right >>> 1;
  22101. if (t < pp[mid]) {
  22102. right = mid;
  22103. } else {
  22104. i1 = mid + 1;
  22105. }
  22106. }
  22107. t1 = pp[i1];
  22108. t0 = pp[i1 - 1]; // check boundary cases, again
  22109. if (t0 === undefined) {
  22110. this._cachedIndex = 0;
  22111. return this.beforeStart_(0, t, t1);
  22112. }
  22113. if (t1 === undefined) {
  22114. i1 = pp.length;
  22115. this._cachedIndex = i1;
  22116. return this.afterEnd_(i1 - 1, t0, t);
  22117. }
  22118. } // seek
  22119. this._cachedIndex = i1;
  22120. this.intervalChanged_(i1, t0, t1);
  22121. } // validate_interval
  22122. return this.interpolate_(i1, t0, t, t1);
  22123. }
  22124. getSettings_() {
  22125. return this.settings || this.DefaultSettings_;
  22126. }
  22127. copySampleValue_(index) {
  22128. // copies a sample value to the result buffer
  22129. const result = this.resultBuffer,
  22130. values = this.sampleValues,
  22131. stride = this.valueSize,
  22132. offset = index * stride;
  22133. for (let i = 0; i !== stride; ++i) {
  22134. result[i] = values[offset + i];
  22135. }
  22136. return result;
  22137. } // Template methods for derived classes:
  22138. interpolate_() {
  22139. throw new Error('call to abstract method'); // implementations shall return this.resultBuffer
  22140. }
  22141. intervalChanged_() {// empty
  22142. }
  22143. } // ALIAS DEFINITIONS
  22144. Interpolant.prototype.beforeStart_ = Interpolant.prototype.copySampleValue_;
  22145. Interpolant.prototype.afterEnd_ = Interpolant.prototype.copySampleValue_;
  22146. /**
  22147. * Fast and simple cubic spline interpolant.
  22148. *
  22149. * It was derived from a Hermitian construction setting the first derivative
  22150. * at each sample position to the linear slope between neighboring positions
  22151. * over their parameter interval.
  22152. */
  22153. class CubicInterpolant extends Interpolant {
  22154. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  22155. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  22156. this._weightPrev = -0;
  22157. this._offsetPrev = -0;
  22158. this._weightNext = -0;
  22159. this._offsetNext = -0;
  22160. this.DefaultSettings_ = {
  22161. endingStart: ZeroCurvatureEnding,
  22162. endingEnd: ZeroCurvatureEnding
  22163. };
  22164. }
  22165. intervalChanged_(i1, t0, t1) {
  22166. const pp = this.parameterPositions;
  22167. let iPrev = i1 - 2,
  22168. iNext = i1 + 1,
  22169. tPrev = pp[iPrev],
  22170. tNext = pp[iNext];
  22171. if (tPrev === undefined) {
  22172. switch (this.getSettings_().endingStart) {
  22173. case ZeroSlopeEnding:
  22174. // f'(t0) = 0
  22175. iPrev = i1;
  22176. tPrev = 2 * t0 - t1;
  22177. break;
  22178. case WrapAroundEnding:
  22179. // use the other end of the curve
  22180. iPrev = pp.length - 2;
  22181. tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
  22182. break;
  22183. default:
  22184. // ZeroCurvatureEnding
  22185. // f''(t0) = 0 a.k.a. Natural Spline
  22186. iPrev = i1;
  22187. tPrev = t1;
  22188. }
  22189. }
  22190. if (tNext === undefined) {
  22191. switch (this.getSettings_().endingEnd) {
  22192. case ZeroSlopeEnding:
  22193. // f'(tN) = 0
  22194. iNext = i1;
  22195. tNext = 2 * t1 - t0;
  22196. break;
  22197. case WrapAroundEnding:
  22198. // use the other end of the curve
  22199. iNext = 1;
  22200. tNext = t1 + pp[1] - pp[0];
  22201. break;
  22202. default:
  22203. // ZeroCurvatureEnding
  22204. // f''(tN) = 0, a.k.a. Natural Spline
  22205. iNext = i1 - 1;
  22206. tNext = t0;
  22207. }
  22208. }
  22209. const halfDt = (t1 - t0) * 0.5,
  22210. stride = this.valueSize;
  22211. this._weightPrev = halfDt / (t0 - tPrev);
  22212. this._weightNext = halfDt / (tNext - t1);
  22213. this._offsetPrev = iPrev * stride;
  22214. this._offsetNext = iNext * stride;
  22215. }
  22216. interpolate_(i1, t0, t, t1) {
  22217. const result = this.resultBuffer,
  22218. values = this.sampleValues,
  22219. stride = this.valueSize,
  22220. o1 = i1 * stride,
  22221. o0 = o1 - stride,
  22222. oP = this._offsetPrev,
  22223. oN = this._offsetNext,
  22224. wP = this._weightPrev,
  22225. wN = this._weightNext,
  22226. p = (t - t0) / (t1 - t0),
  22227. pp = p * p,
  22228. ppp = pp * p; // evaluate polynomials
  22229. const sP = -wP * ppp + 2 * wP * pp - wP * p;
  22230. const s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
  22231. const s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
  22232. const sN = wN * ppp - wN * pp; // combine data linearly
  22233. for (let i = 0; i !== stride; ++i) {
  22234. result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
  22235. }
  22236. return result;
  22237. }
  22238. }
  22239. class LinearInterpolant extends Interpolant {
  22240. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  22241. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  22242. }
  22243. interpolate_(i1, t0, t, t1) {
  22244. const result = this.resultBuffer,
  22245. values = this.sampleValues,
  22246. stride = this.valueSize,
  22247. offset1 = i1 * stride,
  22248. offset0 = offset1 - stride,
  22249. weight1 = (t - t0) / (t1 - t0),
  22250. weight0 = 1 - weight1;
  22251. for (let i = 0; i !== stride; ++i) {
  22252. result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
  22253. }
  22254. return result;
  22255. }
  22256. }
  22257. /**
  22258. *
  22259. * Interpolant that evaluates to the sample value at the position preceeding
  22260. * the parameter.
  22261. */
  22262. class DiscreteInterpolant extends Interpolant {
  22263. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  22264. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  22265. }
  22266. interpolate_(i1
  22267. /*, t0, t, t1 */
  22268. ) {
  22269. return this.copySampleValue_(i1 - 1);
  22270. }
  22271. }
  22272. class KeyframeTrack {
  22273. constructor(name, times, values, interpolation) {
  22274. if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
  22275. if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
  22276. this.name = name;
  22277. this.times = AnimationUtils.convertArray(times, this.TimeBufferType);
  22278. this.values = AnimationUtils.convertArray(values, this.ValueBufferType);
  22279. this.setInterpolation(interpolation || this.DefaultInterpolation);
  22280. } // Serialization (in static context, because of constructor invocation
  22281. // and automatic invocation of .toJSON):
  22282. static toJSON(track) {
  22283. const trackType = track.constructor;
  22284. let json; // derived classes can define a static toJSON method
  22285. if (trackType.toJSON !== this.toJSON) {
  22286. json = trackType.toJSON(track);
  22287. } else {
  22288. // by default, we assume the data can be serialized as-is
  22289. json = {
  22290. 'name': track.name,
  22291. 'times': AnimationUtils.convertArray(track.times, Array),
  22292. 'values': AnimationUtils.convertArray(track.values, Array)
  22293. };
  22294. const interpolation = track.getInterpolation();
  22295. if (interpolation !== track.DefaultInterpolation) {
  22296. json.interpolation = interpolation;
  22297. }
  22298. }
  22299. json.type = track.ValueTypeName; // mandatory
  22300. return json;
  22301. }
  22302. InterpolantFactoryMethodDiscrete(result) {
  22303. return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
  22304. }
  22305. InterpolantFactoryMethodLinear(result) {
  22306. return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
  22307. }
  22308. InterpolantFactoryMethodSmooth(result) {
  22309. return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
  22310. }
  22311. setInterpolation(interpolation) {
  22312. let factoryMethod;
  22313. switch (interpolation) {
  22314. case InterpolateDiscrete:
  22315. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  22316. break;
  22317. case InterpolateLinear:
  22318. factoryMethod = this.InterpolantFactoryMethodLinear;
  22319. break;
  22320. case InterpolateSmooth:
  22321. factoryMethod = this.InterpolantFactoryMethodSmooth;
  22322. break;
  22323. }
  22324. if (factoryMethod === undefined) {
  22325. const message = 'unsupported interpolation for ' + this.ValueTypeName + ' keyframe track named ' + this.name;
  22326. if (this.createInterpolant === undefined) {
  22327. // fall back to default, unless the default itself is messed up
  22328. if (interpolation !== this.DefaultInterpolation) {
  22329. this.setInterpolation(this.DefaultInterpolation);
  22330. } else {
  22331. throw new Error(message); // fatal, in this case
  22332. }
  22333. }
  22334. console.warn('THREE.KeyframeTrack:', message);
  22335. return this;
  22336. }
  22337. this.createInterpolant = factoryMethod;
  22338. return this;
  22339. }
  22340. getInterpolation() {
  22341. switch (this.createInterpolant) {
  22342. case this.InterpolantFactoryMethodDiscrete:
  22343. return InterpolateDiscrete;
  22344. case this.InterpolantFactoryMethodLinear:
  22345. return InterpolateLinear;
  22346. case this.InterpolantFactoryMethodSmooth:
  22347. return InterpolateSmooth;
  22348. }
  22349. }
  22350. getValueSize() {
  22351. return this.values.length / this.times.length;
  22352. } // move all keyframes either forwards or backwards in time
  22353. shift(timeOffset) {
  22354. if (timeOffset !== 0.0) {
  22355. const times = this.times;
  22356. for (let i = 0, n = times.length; i !== n; ++i) {
  22357. times[i] += timeOffset;
  22358. }
  22359. }
  22360. return this;
  22361. } // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  22362. scale(timeScale) {
  22363. if (timeScale !== 1.0) {
  22364. const times = this.times;
  22365. for (let i = 0, n = times.length; i !== n; ++i) {
  22366. times[i] *= timeScale;
  22367. }
  22368. }
  22369. return this;
  22370. } // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  22371. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  22372. trim(startTime, endTime) {
  22373. const times = this.times,
  22374. nKeys = times.length;
  22375. let from = 0,
  22376. to = nKeys - 1;
  22377. while (from !== nKeys && times[from] < startTime) {
  22378. ++from;
  22379. }
  22380. while (to !== -1 && times[to] > endTime) {
  22381. --to;
  22382. }
  22383. ++to; // inclusive -> exclusive bound
  22384. if (from !== 0 || to !== nKeys) {
  22385. // empty tracks are forbidden, so keep at least one keyframe
  22386. if (from >= to) {
  22387. to = Math.max(to, 1);
  22388. from = to - 1;
  22389. }
  22390. const stride = this.getValueSize();
  22391. this.times = AnimationUtils.arraySlice(times, from, to);
  22392. this.values = AnimationUtils.arraySlice(this.values, from * stride, to * stride);
  22393. }
  22394. return this;
  22395. } // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  22396. validate() {
  22397. let valid = true;
  22398. const valueSize = this.getValueSize();
  22399. if (valueSize - Math.floor(valueSize) !== 0) {
  22400. console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
  22401. valid = false;
  22402. }
  22403. const times = this.times,
  22404. values = this.values,
  22405. nKeys = times.length;
  22406. if (nKeys === 0) {
  22407. console.error('THREE.KeyframeTrack: Track is empty.', this);
  22408. valid = false;
  22409. }
  22410. let prevTime = null;
  22411. for (let i = 0; i !== nKeys; i++) {
  22412. const currTime = times[i];
  22413. if (typeof currTime === 'number' && isNaN(currTime)) {
  22414. console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
  22415. valid = false;
  22416. break;
  22417. }
  22418. if (prevTime !== null && prevTime > currTime) {
  22419. console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
  22420. valid = false;
  22421. break;
  22422. }
  22423. prevTime = currTime;
  22424. }
  22425. if (values !== undefined) {
  22426. if (AnimationUtils.isTypedArray(values)) {
  22427. for (let i = 0, n = values.length; i !== n; ++i) {
  22428. const value = values[i];
  22429. if (isNaN(value)) {
  22430. console.error('THREE.KeyframeTrack: Value is not a valid number.', this, i, value);
  22431. valid = false;
  22432. break;
  22433. }
  22434. }
  22435. }
  22436. }
  22437. return valid;
  22438. } // removes equivalent sequential keys as common in morph target sequences
  22439. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  22440. optimize() {
  22441. // times or values may be shared with other tracks, so overwriting is unsafe
  22442. const times = AnimationUtils.arraySlice(this.times),
  22443. values = AnimationUtils.arraySlice(this.values),
  22444. stride = this.getValueSize(),
  22445. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  22446. lastIndex = times.length - 1;
  22447. let writeIndex = 1;
  22448. for (let i = 1; i < lastIndex; ++i) {
  22449. let keep = false;
  22450. const time = times[i];
  22451. const timeNext = times[i + 1]; // remove adjacent keyframes scheduled at the same time
  22452. if (time !== timeNext && (i !== 1 || time !== times[0])) {
  22453. if (!smoothInterpolation) {
  22454. // remove unnecessary keyframes same as their neighbors
  22455. const offset = i * stride,
  22456. offsetP = offset - stride,
  22457. offsetN = offset + stride;
  22458. for (let j = 0; j !== stride; ++j) {
  22459. const value = values[offset + j];
  22460. if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
  22461. keep = true;
  22462. break;
  22463. }
  22464. }
  22465. } else {
  22466. keep = true;
  22467. }
  22468. } // in-place compaction
  22469. if (keep) {
  22470. if (i !== writeIndex) {
  22471. times[writeIndex] = times[i];
  22472. const readOffset = i * stride,
  22473. writeOffset = writeIndex * stride;
  22474. for (let j = 0; j !== stride; ++j) {
  22475. values[writeOffset + j] = values[readOffset + j];
  22476. }
  22477. }
  22478. ++writeIndex;
  22479. }
  22480. } // flush last keyframe (compaction looks ahead)
  22481. if (lastIndex > 0) {
  22482. times[writeIndex] = times[lastIndex];
  22483. for (let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++j) {
  22484. values[writeOffset + j] = values[readOffset + j];
  22485. }
  22486. ++writeIndex;
  22487. }
  22488. if (writeIndex !== times.length) {
  22489. this.times = AnimationUtils.arraySlice(times, 0, writeIndex);
  22490. this.values = AnimationUtils.arraySlice(values, 0, writeIndex * stride);
  22491. } else {
  22492. this.times = times;
  22493. this.values = values;
  22494. }
  22495. return this;
  22496. }
  22497. clone() {
  22498. const times = AnimationUtils.arraySlice(this.times, 0);
  22499. const values = AnimationUtils.arraySlice(this.values, 0);
  22500. const TypedKeyframeTrack = this.constructor;
  22501. const track = new TypedKeyframeTrack(this.name, times, values); // Interpolant argument to constructor is not saved, so copy the factory method directly.
  22502. track.createInterpolant = this.createInterpolant;
  22503. return track;
  22504. }
  22505. }
  22506. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  22507. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  22508. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  22509. /**
  22510. * A Track of Boolean keyframe values.
  22511. */
  22512. class BooleanKeyframeTrack extends KeyframeTrack {}
  22513. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  22514. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  22515. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  22516. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  22517. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; // Note: Actually this track could have a optimized / compressed
  22518. /**
  22519. * A Track of keyframe values that represent color.
  22520. */
  22521. class ColorKeyframeTrack extends KeyframeTrack {}
  22522. ColorKeyframeTrack.prototype.ValueTypeName = 'color'; // ValueBufferType is inherited
  22523. /**
  22524. * A Track of numeric keyframe values.
  22525. */
  22526. class NumberKeyframeTrack extends KeyframeTrack {}
  22527. NumberKeyframeTrack.prototype.ValueTypeName = 'number'; // ValueBufferType is inherited
  22528. /**
  22529. * Spherical linear unit quaternion interpolant.
  22530. */
  22531. class QuaternionLinearInterpolant extends Interpolant {
  22532. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  22533. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  22534. }
  22535. interpolate_(i1, t0, t, t1) {
  22536. const result = this.resultBuffer,
  22537. values = this.sampleValues,
  22538. stride = this.valueSize,
  22539. alpha = (t - t0) / (t1 - t0);
  22540. let offset = i1 * stride;
  22541. for (let end = offset + stride; offset !== end; offset += 4) {
  22542. Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
  22543. }
  22544. return result;
  22545. }
  22546. }
  22547. /**
  22548. * A Track of quaternion keyframe values.
  22549. */
  22550. class QuaternionKeyframeTrack extends KeyframeTrack {
  22551. InterpolantFactoryMethodLinear(result) {
  22552. return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
  22553. }
  22554. }
  22555. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion'; // ValueBufferType is inherited
  22556. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  22557. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  22558. /**
  22559. * A Track that interpolates Strings
  22560. */
  22561. class StringKeyframeTrack extends KeyframeTrack {}
  22562. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  22563. StringKeyframeTrack.prototype.ValueBufferType = Array;
  22564. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  22565. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  22566. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  22567. /**
  22568. * A Track of vectored keyframe values.
  22569. */
  22570. class VectorKeyframeTrack extends KeyframeTrack {}
  22571. VectorKeyframeTrack.prototype.ValueTypeName = 'vector'; // ValueBufferType is inherited
  22572. class AnimationClip {
  22573. constructor(name, duration = -1, tracks, blendMode = NormalAnimationBlendMode) {
  22574. this.name = name;
  22575. this.tracks = tracks;
  22576. this.duration = duration;
  22577. this.blendMode = blendMode;
  22578. this.uuid = generateUUID(); // this means it should figure out its duration by scanning the tracks
  22579. if (this.duration < 0) {
  22580. this.resetDuration();
  22581. }
  22582. }
  22583. static parse(json) {
  22584. const tracks = [],
  22585. jsonTracks = json.tracks,
  22586. frameTime = 1.0 / (json.fps || 1.0);
  22587. for (let i = 0, n = jsonTracks.length; i !== n; ++i) {
  22588. tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime));
  22589. }
  22590. const clip = new this(json.name, json.duration, tracks, json.blendMode);
  22591. clip.uuid = json.uuid;
  22592. return clip;
  22593. }
  22594. static toJSON(clip) {
  22595. const tracks = [],
  22596. clipTracks = clip.tracks;
  22597. const json = {
  22598. 'name': clip.name,
  22599. 'duration': clip.duration,
  22600. 'tracks': tracks,
  22601. 'uuid': clip.uuid,
  22602. 'blendMode': clip.blendMode
  22603. };
  22604. for (let i = 0, n = clipTracks.length; i !== n; ++i) {
  22605. tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
  22606. }
  22607. return json;
  22608. }
  22609. static CreateFromMorphTargetSequence(name, morphTargetSequence, fps, noLoop) {
  22610. const numMorphTargets = morphTargetSequence.length;
  22611. const tracks = [];
  22612. for (let i = 0; i < numMorphTargets; i++) {
  22613. let times = [];
  22614. let values = [];
  22615. times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);
  22616. values.push(0, 1, 0);
  22617. const order = AnimationUtils.getKeyframeOrder(times);
  22618. times = AnimationUtils.sortedArray(times, 1, order);
  22619. values = AnimationUtils.sortedArray(values, 1, order); // if there is a key at the first frame, duplicate it as the
  22620. // last frame as well for perfect loop.
  22621. if (!noLoop && times[0] === 0) {
  22622. times.push(numMorphTargets);
  22623. values.push(values[0]);
  22624. }
  22625. tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
  22626. }
  22627. return new this(name, -1, tracks);
  22628. }
  22629. static findByName(objectOrClipArray, name) {
  22630. let clipArray = objectOrClipArray;
  22631. if (!Array.isArray(objectOrClipArray)) {
  22632. const o = objectOrClipArray;
  22633. clipArray = o.geometry && o.geometry.animations || o.animations;
  22634. }
  22635. for (let i = 0; i < clipArray.length; i++) {
  22636. if (clipArray[i].name === name) {
  22637. return clipArray[i];
  22638. }
  22639. }
  22640. return null;
  22641. }
  22642. static CreateClipsFromMorphTargetSequences(morphTargets, fps, noLoop) {
  22643. const animationToMorphTargets = {}; // tested with https://regex101.com/ on trick sequences
  22644. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  22645. const pattern = /^([\w-]*?)([\d]+)$/; // sort morph target names into animation groups based
  22646. // patterns like Walk_001, Walk_002, Run_001, Run_002
  22647. for (let i = 0, il = morphTargets.length; i < il; i++) {
  22648. const morphTarget = morphTargets[i];
  22649. const parts = morphTarget.name.match(pattern);
  22650. if (parts && parts.length > 1) {
  22651. const name = parts[1];
  22652. let animationMorphTargets = animationToMorphTargets[name];
  22653. if (!animationMorphTargets) {
  22654. animationToMorphTargets[name] = animationMorphTargets = [];
  22655. }
  22656. animationMorphTargets.push(morphTarget);
  22657. }
  22658. }
  22659. const clips = [];
  22660. for (const name in animationToMorphTargets) {
  22661. clips.push(this.CreateFromMorphTargetSequence(name, animationToMorphTargets[name], fps, noLoop));
  22662. }
  22663. return clips;
  22664. } // parse the animation.hierarchy format
  22665. static parseAnimation(animation, bones) {
  22666. if (!animation) {
  22667. console.error('THREE.AnimationClip: No animation in JSONLoader data.');
  22668. return null;
  22669. }
  22670. const addNonemptyTrack = function (trackType, trackName, animationKeys, propertyName, destTracks) {
  22671. // only return track if there are actually keys.
  22672. if (animationKeys.length !== 0) {
  22673. const times = [];
  22674. const values = [];
  22675. AnimationUtils.flattenJSON(animationKeys, times, values, propertyName); // empty keys are filtered out, so check again
  22676. if (times.length !== 0) {
  22677. destTracks.push(new trackType(trackName, times, values));
  22678. }
  22679. }
  22680. };
  22681. const tracks = [];
  22682. const clipName = animation.name || 'default';
  22683. const fps = animation.fps || 30;
  22684. const blendMode = animation.blendMode; // automatic length determination in AnimationClip.
  22685. let duration = animation.length || -1;
  22686. const hierarchyTracks = animation.hierarchy || [];
  22687. for (let h = 0; h < hierarchyTracks.length; h++) {
  22688. const animationKeys = hierarchyTracks[h].keys; // skip empty tracks
  22689. if (!animationKeys || animationKeys.length === 0) continue; // process morph targets
  22690. if (animationKeys[0].morphTargets) {
  22691. // figure out all morph targets used in this track
  22692. const morphTargetNames = {};
  22693. let k;
  22694. for (k = 0; k < animationKeys.length; k++) {
  22695. if (animationKeys[k].morphTargets) {
  22696. for (let m = 0; m < animationKeys[k].morphTargets.length; m++) {
  22697. morphTargetNames[animationKeys[k].morphTargets[m]] = -1;
  22698. }
  22699. }
  22700. } // create a track for each morph target with all zero
  22701. // morphTargetInfluences except for the keys in which
  22702. // the morphTarget is named.
  22703. for (const morphTargetName in morphTargetNames) {
  22704. const times = [];
  22705. const values = [];
  22706. for (let m = 0; m !== animationKeys[k].morphTargets.length; ++m) {
  22707. const animationKey = animationKeys[k];
  22708. times.push(animationKey.time);
  22709. values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
  22710. }
  22711. tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));
  22712. }
  22713. duration = morphTargetNames.length * (fps || 1.0);
  22714. } else {
  22715. // ...assume skeletal animation
  22716. const boneName = '.bones[' + bones[h].name + ']';
  22717. addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);
  22718. addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);
  22719. addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);
  22720. }
  22721. }
  22722. if (tracks.length === 0) {
  22723. return null;
  22724. }
  22725. const clip = new this(clipName, duration, tracks, blendMode);
  22726. return clip;
  22727. }
  22728. resetDuration() {
  22729. const tracks = this.tracks;
  22730. let duration = 0;
  22731. for (let i = 0, n = tracks.length; i !== n; ++i) {
  22732. const track = this.tracks[i];
  22733. duration = Math.max(duration, track.times[track.times.length - 1]);
  22734. }
  22735. this.duration = duration;
  22736. return this;
  22737. }
  22738. trim() {
  22739. for (let i = 0; i < this.tracks.length; i++) {
  22740. this.tracks[i].trim(0, this.duration);
  22741. }
  22742. return this;
  22743. }
  22744. validate() {
  22745. let valid = true;
  22746. for (let i = 0; i < this.tracks.length; i++) {
  22747. valid = valid && this.tracks[i].validate();
  22748. }
  22749. return valid;
  22750. }
  22751. optimize() {
  22752. for (let i = 0; i < this.tracks.length; i++) {
  22753. this.tracks[i].optimize();
  22754. }
  22755. return this;
  22756. }
  22757. clone() {
  22758. const tracks = [];
  22759. for (let i = 0; i < this.tracks.length; i++) {
  22760. tracks.push(this.tracks[i].clone());
  22761. }
  22762. return new this.constructor(this.name, this.duration, tracks, this.blendMode);
  22763. }
  22764. toJSON() {
  22765. return this.constructor.toJSON(this);
  22766. }
  22767. }
  22768. function getTrackTypeForValueTypeName(typeName) {
  22769. switch (typeName.toLowerCase()) {
  22770. case 'scalar':
  22771. case 'double':
  22772. case 'float':
  22773. case 'number':
  22774. case 'integer':
  22775. return NumberKeyframeTrack;
  22776. case 'vector':
  22777. case 'vector2':
  22778. case 'vector3':
  22779. case 'vector4':
  22780. return VectorKeyframeTrack;
  22781. case 'color':
  22782. return ColorKeyframeTrack;
  22783. case 'quaternion':
  22784. return QuaternionKeyframeTrack;
  22785. case 'bool':
  22786. case 'boolean':
  22787. return BooleanKeyframeTrack;
  22788. case 'string':
  22789. return StringKeyframeTrack;
  22790. }
  22791. throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);
  22792. }
  22793. function parseKeyframeTrack(json) {
  22794. if (json.type === undefined) {
  22795. throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
  22796. }
  22797. const trackType = getTrackTypeForValueTypeName(json.type);
  22798. if (json.times === undefined) {
  22799. const times = [],
  22800. values = [];
  22801. AnimationUtils.flattenJSON(json.keys, times, values, 'value');
  22802. json.times = times;
  22803. json.values = values;
  22804. } // derived classes can define a static parse method
  22805. if (trackType.parse !== undefined) {
  22806. return trackType.parse(json);
  22807. } else {
  22808. // by default, we assume a constructor compatible with the base
  22809. return new trackType(json.name, json.times, json.values, json.interpolation);
  22810. }
  22811. }
  22812. const Cache = {
  22813. enabled: false,
  22814. files: {},
  22815. add: function (key, file) {
  22816. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Adding key:', key );
  22817. this.files[key] = file;
  22818. },
  22819. get: function (key) {
  22820. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Checking key:', key );
  22821. return this.files[key];
  22822. },
  22823. remove: function (key) {
  22824. delete this.files[key];
  22825. },
  22826. clear: function () {
  22827. this.files = {};
  22828. }
  22829. };
  22830. class LoadingManager {
  22831. constructor(onLoad, onProgress, onError) {
  22832. const scope = this;
  22833. let isLoading = false;
  22834. let itemsLoaded = 0;
  22835. let itemsTotal = 0;
  22836. let urlModifier = undefined;
  22837. const handlers = []; // Refer to #5689 for the reason why we don't set .onStart
  22838. // in the constructor
  22839. this.onStart = undefined;
  22840. this.onLoad = onLoad;
  22841. this.onProgress = onProgress;
  22842. this.onError = onError;
  22843. this.itemStart = function (url) {
  22844. itemsTotal++;
  22845. if (isLoading === false) {
  22846. if (scope.onStart !== undefined) {
  22847. scope.onStart(url, itemsLoaded, itemsTotal);
  22848. }
  22849. }
  22850. isLoading = true;
  22851. };
  22852. this.itemEnd = function (url) {
  22853. itemsLoaded++;
  22854. if (scope.onProgress !== undefined) {
  22855. scope.onProgress(url, itemsLoaded, itemsTotal);
  22856. }
  22857. if (itemsLoaded === itemsTotal) {
  22858. isLoading = false;
  22859. if (scope.onLoad !== undefined) {
  22860. scope.onLoad();
  22861. }
  22862. }
  22863. };
  22864. this.itemError = function (url) {
  22865. if (scope.onError !== undefined) {
  22866. scope.onError(url);
  22867. }
  22868. };
  22869. this.resolveURL = function (url) {
  22870. if (urlModifier) {
  22871. return urlModifier(url);
  22872. }
  22873. return url;
  22874. };
  22875. this.setURLModifier = function (transform) {
  22876. urlModifier = transform;
  22877. return this;
  22878. };
  22879. this.addHandler = function (regex, loader) {
  22880. handlers.push(regex, loader);
  22881. return this;
  22882. };
  22883. this.removeHandler = function (regex) {
  22884. const index = handlers.indexOf(regex);
  22885. if (index !== -1) {
  22886. handlers.splice(index, 2);
  22887. }
  22888. return this;
  22889. };
  22890. this.getHandler = function (file) {
  22891. for (let i = 0, l = handlers.length; i < l; i += 2) {
  22892. const regex = handlers[i];
  22893. const loader = handlers[i + 1];
  22894. if (regex.global) regex.lastIndex = 0; // see #17920
  22895. if (regex.test(file)) {
  22896. return loader;
  22897. }
  22898. }
  22899. return null;
  22900. };
  22901. }
  22902. }
  22903. const DefaultLoadingManager = new LoadingManager();
  22904. class Loader {
  22905. constructor(manager) {
  22906. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  22907. this.crossOrigin = 'anonymous';
  22908. this.withCredentials = false;
  22909. this.path = '';
  22910. this.resourcePath = '';
  22911. this.requestHeader = {};
  22912. }
  22913. load() {}
  22914. loadAsync(url, onProgress) {
  22915. const scope = this;
  22916. return new Promise(function (resolve, reject) {
  22917. scope.load(url, resolve, onProgress, reject);
  22918. });
  22919. }
  22920. parse() {}
  22921. setCrossOrigin(crossOrigin) {
  22922. this.crossOrigin = crossOrigin;
  22923. return this;
  22924. }
  22925. setWithCredentials(value) {
  22926. this.withCredentials = value;
  22927. return this;
  22928. }
  22929. setPath(path) {
  22930. this.path = path;
  22931. return this;
  22932. }
  22933. setResourcePath(resourcePath) {
  22934. this.resourcePath = resourcePath;
  22935. return this;
  22936. }
  22937. setRequestHeader(requestHeader) {
  22938. this.requestHeader = requestHeader;
  22939. return this;
  22940. }
  22941. }
  22942. const loading = {};
  22943. class FileLoader extends Loader {
  22944. constructor(manager) {
  22945. super(manager);
  22946. }
  22947. load(url, onLoad, onProgress, onError) {
  22948. if (url === undefined) url = '';
  22949. if (this.path !== undefined) url = this.path + url;
  22950. url = this.manager.resolveURL(url);
  22951. const cached = Cache.get(url);
  22952. if (cached !== undefined) {
  22953. this.manager.itemStart(url);
  22954. setTimeout(() => {
  22955. if (onLoad) onLoad(cached);
  22956. this.manager.itemEnd(url);
  22957. }, 0);
  22958. return cached;
  22959. } // Check if request is duplicate
  22960. if (loading[url] !== undefined) {
  22961. loading[url].push({
  22962. onLoad: onLoad,
  22963. onProgress: onProgress,
  22964. onError: onError
  22965. });
  22966. return;
  22967. } // Initialise array for duplicate requests
  22968. loading[url] = [];
  22969. loading[url].push({
  22970. onLoad: onLoad,
  22971. onProgress: onProgress,
  22972. onError: onError
  22973. }); // create request
  22974. const req = new Request(url, {
  22975. headers: new Headers(this.requestHeader),
  22976. credentials: this.withCredentials ? 'include' : 'same-origin' // An abort controller could be added within a future PR
  22977. }); // start the fetch
  22978. fetch(req).then(response => {
  22979. if (response.status === 200 || response.status === 0) {
  22980. // Some browsers return HTTP Status 0 when using non-http protocol
  22981. // e.g. 'file://' or 'data://'. Handle as success.
  22982. if (response.status === 0) {
  22983. console.warn('THREE.FileLoader: HTTP Status 0 received.');
  22984. }
  22985. if (typeof ReadableStream === 'undefined' || response.body.getReader === undefined) {
  22986. return response;
  22987. }
  22988. const callbacks = loading[url];
  22989. const reader = response.body.getReader();
  22990. const contentLength = response.headers.get('Content-Length');
  22991. const total = contentLength ? parseInt(contentLength) : 0;
  22992. const lengthComputable = total !== 0;
  22993. let loaded = 0; // periodically read data into the new stream tracking while download progress
  22994. const stream = new ReadableStream({
  22995. start(controller) {
  22996. readData();
  22997. function readData() {
  22998. reader.read().then(({
  22999. done,
  23000. value
  23001. }) => {
  23002. if (done) {
  23003. controller.close();
  23004. } else {
  23005. loaded += value.byteLength;
  23006. const event = new ProgressEvent('progress', {
  23007. lengthComputable,
  23008. loaded,
  23009. total
  23010. });
  23011. for (let i = 0, il = callbacks.length; i < il; i++) {
  23012. const callback = callbacks[i];
  23013. if (callback.onProgress) callback.onProgress(event);
  23014. }
  23015. controller.enqueue(value);
  23016. readData();
  23017. }
  23018. });
  23019. }
  23020. }
  23021. });
  23022. return new Response(stream);
  23023. } else {
  23024. throw Error(`fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`);
  23025. }
  23026. }).then(response => {
  23027. switch (this.responseType) {
  23028. case 'arraybuffer':
  23029. return response.arrayBuffer();
  23030. case 'blob':
  23031. return response.blob();
  23032. case 'document':
  23033. return response.text().then(text => {
  23034. const parser = new DOMParser();
  23035. return parser.parseFromString(text, this.mimeType);
  23036. });
  23037. case 'json':
  23038. return response.json();
  23039. default:
  23040. return response.text();
  23041. }
  23042. }).then(data => {
  23043. // Add to cache only on HTTP success, so that we do not cache
  23044. // error response bodies as proper responses to requests.
  23045. Cache.add(url, data);
  23046. const callbacks = loading[url];
  23047. delete loading[url];
  23048. for (let i = 0, il = callbacks.length; i < il; i++) {
  23049. const callback = callbacks[i];
  23050. if (callback.onLoad) callback.onLoad(data);
  23051. }
  23052. }).catch(err => {
  23053. // Abort errors and other errors are handled the same
  23054. const callbacks = loading[url];
  23055. if (callbacks === undefined) {
  23056. // When onLoad was called and url was deleted in `loading`
  23057. this.manager.itemError(url);
  23058. throw err;
  23059. }
  23060. delete loading[url];
  23061. for (let i = 0, il = callbacks.length; i < il; i++) {
  23062. const callback = callbacks[i];
  23063. if (callback.onError) callback.onError(err);
  23064. }
  23065. this.manager.itemError(url);
  23066. }).finally(() => {
  23067. this.manager.itemEnd(url);
  23068. });
  23069. this.manager.itemStart(url);
  23070. }
  23071. setResponseType(value) {
  23072. this.responseType = value;
  23073. return this;
  23074. }
  23075. setMimeType(value) {
  23076. this.mimeType = value;
  23077. return this;
  23078. }
  23079. }
  23080. class AnimationLoader extends Loader {
  23081. constructor(manager) {
  23082. super(manager);
  23083. }
  23084. load(url, onLoad, onProgress, onError) {
  23085. const scope = this;
  23086. const loader = new FileLoader(this.manager);
  23087. loader.setPath(this.path);
  23088. loader.setRequestHeader(this.requestHeader);
  23089. loader.setWithCredentials(this.withCredentials);
  23090. loader.load(url, function (text) {
  23091. try {
  23092. onLoad(scope.parse(JSON.parse(text)));
  23093. } catch (e) {
  23094. if (onError) {
  23095. onError(e);
  23096. } else {
  23097. console.error(e);
  23098. }
  23099. scope.manager.itemError(url);
  23100. }
  23101. }, onProgress, onError);
  23102. }
  23103. parse(json) {
  23104. const animations = [];
  23105. for (let i = 0; i < json.length; i++) {
  23106. const clip = AnimationClip.parse(json[i]);
  23107. animations.push(clip);
  23108. }
  23109. return animations;
  23110. }
  23111. }
  23112. /**
  23113. * Abstract Base class to block based textures loader (dds, pvr, ...)
  23114. *
  23115. * Sub classes have to implement the parse() method which will be used in load().
  23116. */
  23117. class CompressedTextureLoader extends Loader {
  23118. constructor(manager) {
  23119. super(manager);
  23120. }
  23121. load(url, onLoad, onProgress, onError) {
  23122. const scope = this;
  23123. const images = [];
  23124. const texture = new CompressedTexture();
  23125. const loader = new FileLoader(this.manager);
  23126. loader.setPath(this.path);
  23127. loader.setResponseType('arraybuffer');
  23128. loader.setRequestHeader(this.requestHeader);
  23129. loader.setWithCredentials(scope.withCredentials);
  23130. let loaded = 0;
  23131. function loadTexture(i) {
  23132. loader.load(url[i], function (buffer) {
  23133. const texDatas = scope.parse(buffer, true);
  23134. images[i] = {
  23135. width: texDatas.width,
  23136. height: texDatas.height,
  23137. format: texDatas.format,
  23138. mipmaps: texDatas.mipmaps
  23139. };
  23140. loaded += 1;
  23141. if (loaded === 6) {
  23142. if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
  23143. texture.image = images;
  23144. texture.format = texDatas.format;
  23145. texture.needsUpdate = true;
  23146. if (onLoad) onLoad(texture);
  23147. }
  23148. }, onProgress, onError);
  23149. }
  23150. if (Array.isArray(url)) {
  23151. for (let i = 0, il = url.length; i < il; ++i) {
  23152. loadTexture(i);
  23153. }
  23154. } else {
  23155. // compressed cubemap texture stored in a single DDS file
  23156. loader.load(url, function (buffer) {
  23157. const texDatas = scope.parse(buffer, true);
  23158. if (texDatas.isCubemap) {
  23159. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  23160. for (let f = 0; f < faces; f++) {
  23161. images[f] = {
  23162. mipmaps: []
  23163. };
  23164. for (let i = 0; i < texDatas.mipmapCount; i++) {
  23165. images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]);
  23166. images[f].format = texDatas.format;
  23167. images[f].width = texDatas.width;
  23168. images[f].height = texDatas.height;
  23169. }
  23170. }
  23171. texture.image = images;
  23172. } else {
  23173. texture.image.width = texDatas.width;
  23174. texture.image.height = texDatas.height;
  23175. texture.mipmaps = texDatas.mipmaps;
  23176. }
  23177. if (texDatas.mipmapCount === 1) {
  23178. texture.minFilter = LinearFilter;
  23179. }
  23180. texture.format = texDatas.format;
  23181. texture.needsUpdate = true;
  23182. if (onLoad) onLoad(texture);
  23183. }, onProgress, onError);
  23184. }
  23185. return texture;
  23186. }
  23187. }
  23188. class ImageLoader extends Loader {
  23189. constructor(manager) {
  23190. super(manager);
  23191. }
  23192. load(url, onLoad, onProgress, onError) {
  23193. if (this.path !== undefined) url = this.path + url;
  23194. url = this.manager.resolveURL(url);
  23195. const scope = this;
  23196. const cached = Cache.get(url);
  23197. if (cached !== undefined) {
  23198. scope.manager.itemStart(url);
  23199. setTimeout(function () {
  23200. if (onLoad) onLoad(cached);
  23201. scope.manager.itemEnd(url);
  23202. }, 0);
  23203. return cached;
  23204. }
  23205. const image = createElementNS('img');
  23206. function onImageLoad() {
  23207. removeEventListeners();
  23208. Cache.add(url, this);
  23209. if (onLoad) onLoad(this);
  23210. scope.manager.itemEnd(url);
  23211. }
  23212. function onImageError(event) {
  23213. removeEventListeners();
  23214. if (onError) onError(event);
  23215. scope.manager.itemError(url);
  23216. scope.manager.itemEnd(url);
  23217. }
  23218. function removeEventListeners() {
  23219. image.removeEventListener('load', onImageLoad, false);
  23220. image.removeEventListener('error', onImageError, false);
  23221. }
  23222. image.addEventListener('load', onImageLoad, false);
  23223. image.addEventListener('error', onImageError, false);
  23224. if (url.substr(0, 5) !== 'data:') {
  23225. if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
  23226. }
  23227. scope.manager.itemStart(url);
  23228. image.src = url;
  23229. return image;
  23230. }
  23231. }
  23232. class CubeTextureLoader extends Loader {
  23233. constructor(manager) {
  23234. super(manager);
  23235. }
  23236. load(urls, onLoad, onProgress, onError) {
  23237. const texture = new CubeTexture();
  23238. const loader = new ImageLoader(this.manager);
  23239. loader.setCrossOrigin(this.crossOrigin);
  23240. loader.setPath(this.path);
  23241. let loaded = 0;
  23242. function loadTexture(i) {
  23243. loader.load(urls[i], function (image) {
  23244. texture.images[i] = image;
  23245. loaded++;
  23246. if (loaded === 6) {
  23247. texture.needsUpdate = true;
  23248. if (onLoad) onLoad(texture);
  23249. }
  23250. }, undefined, onError);
  23251. }
  23252. for (let i = 0; i < urls.length; ++i) {
  23253. loadTexture(i);
  23254. }
  23255. return texture;
  23256. }
  23257. }
  23258. /**
  23259. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  23260. *
  23261. * Sub classes have to implement the parse() method which will be used in load().
  23262. */
  23263. class DataTextureLoader extends Loader {
  23264. constructor(manager) {
  23265. super(manager);
  23266. }
  23267. load(url, onLoad, onProgress, onError) {
  23268. const scope = this;
  23269. const texture = new DataTexture();
  23270. const loader = new FileLoader(this.manager);
  23271. loader.setResponseType('arraybuffer');
  23272. loader.setRequestHeader(this.requestHeader);
  23273. loader.setPath(this.path);
  23274. loader.setWithCredentials(scope.withCredentials);
  23275. loader.load(url, function (buffer) {
  23276. const texData = scope.parse(buffer);
  23277. if (!texData) return;
  23278. if (texData.image !== undefined) {
  23279. texture.image = texData.image;
  23280. } else if (texData.data !== undefined) {
  23281. texture.image.width = texData.width;
  23282. texture.image.height = texData.height;
  23283. texture.image.data = texData.data;
  23284. }
  23285. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  23286. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  23287. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  23288. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  23289. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  23290. if (texData.encoding !== undefined) {
  23291. texture.encoding = texData.encoding;
  23292. }
  23293. if (texData.flipY !== undefined) {
  23294. texture.flipY = texData.flipY;
  23295. }
  23296. if (texData.format !== undefined) {
  23297. texture.format = texData.format;
  23298. }
  23299. if (texData.type !== undefined) {
  23300. texture.type = texData.type;
  23301. }
  23302. if (texData.mipmaps !== undefined) {
  23303. texture.mipmaps = texData.mipmaps;
  23304. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  23305. }
  23306. if (texData.mipmapCount === 1) {
  23307. texture.minFilter = LinearFilter;
  23308. }
  23309. if (texData.generateMipmaps !== undefined) {
  23310. texture.generateMipmaps = texData.generateMipmaps;
  23311. }
  23312. texture.needsUpdate = true;
  23313. if (onLoad) onLoad(texture, texData);
  23314. }, onProgress, onError);
  23315. return texture;
  23316. }
  23317. }
  23318. class TextureLoader extends Loader {
  23319. constructor(manager) {
  23320. super(manager);
  23321. }
  23322. load(url, onLoad, onProgress, onError) {
  23323. const texture = new Texture();
  23324. const loader = new ImageLoader(this.manager);
  23325. loader.setCrossOrigin(this.crossOrigin);
  23326. loader.setPath(this.path);
  23327. loader.load(url, function (image) {
  23328. texture.image = image;
  23329. texture.needsUpdate = true;
  23330. if (onLoad !== undefined) {
  23331. onLoad(texture);
  23332. }
  23333. }, onProgress, onError);
  23334. return texture;
  23335. }
  23336. }
  23337. class Light extends Object3D {
  23338. constructor(color, intensity = 1) {
  23339. super();
  23340. this.type = 'Light';
  23341. this.color = new Color(color);
  23342. this.intensity = intensity;
  23343. }
  23344. dispose() {// Empty here in base class; some subclasses override.
  23345. }
  23346. copy(source) {
  23347. super.copy(source);
  23348. this.color.copy(source.color);
  23349. this.intensity = source.intensity;
  23350. return this;
  23351. }
  23352. toJSON(meta) {
  23353. const data = super.toJSON(meta);
  23354. data.object.color = this.color.getHex();
  23355. data.object.intensity = this.intensity;
  23356. if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
  23357. if (this.distance !== undefined) data.object.distance = this.distance;
  23358. if (this.angle !== undefined) data.object.angle = this.angle;
  23359. if (this.decay !== undefined) data.object.decay = this.decay;
  23360. if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
  23361. if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
  23362. return data;
  23363. }
  23364. }
  23365. Light.prototype.isLight = true;
  23366. class HemisphereLight extends Light {
  23367. constructor(skyColor, groundColor, intensity) {
  23368. super(skyColor, intensity);
  23369. this.type = 'HemisphereLight';
  23370. this.position.copy(Object3D.DefaultUp);
  23371. this.updateMatrix();
  23372. this.groundColor = new Color(groundColor);
  23373. }
  23374. copy(source) {
  23375. Light.prototype.copy.call(this, source);
  23376. this.groundColor.copy(source.groundColor);
  23377. return this;
  23378. }
  23379. }
  23380. HemisphereLight.prototype.isHemisphereLight = true;
  23381. const _projScreenMatrix$1 = /*@__PURE__*/new Matrix4();
  23382. const _lightPositionWorld$1 = /*@__PURE__*/new Vector3();
  23383. const _lookTarget$1 = /*@__PURE__*/new Vector3();
  23384. class LightShadow {
  23385. constructor(camera) {
  23386. this.camera = camera;
  23387. this.bias = 0;
  23388. this.normalBias = 0;
  23389. this.radius = 1;
  23390. this.blurSamples = 8;
  23391. this.mapSize = new Vector2(512, 512);
  23392. this.map = null;
  23393. this.mapPass = null;
  23394. this.matrix = new Matrix4();
  23395. this.autoUpdate = true;
  23396. this.needsUpdate = false;
  23397. this._frustum = new Frustum();
  23398. this._frameExtents = new Vector2(1, 1);
  23399. this._viewportCount = 1;
  23400. this._viewports = [new Vector4(0, 0, 1, 1)];
  23401. }
  23402. getViewportCount() {
  23403. return this._viewportCount;
  23404. }
  23405. getFrustum() {
  23406. return this._frustum;
  23407. }
  23408. updateMatrices(light) {
  23409. const shadowCamera = this.camera;
  23410. const shadowMatrix = this.matrix;
  23411. _lightPositionWorld$1.setFromMatrixPosition(light.matrixWorld);
  23412. shadowCamera.position.copy(_lightPositionWorld$1);
  23413. _lookTarget$1.setFromMatrixPosition(light.target.matrixWorld);
  23414. shadowCamera.lookAt(_lookTarget$1);
  23415. shadowCamera.updateMatrixWorld();
  23416. _projScreenMatrix$1.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
  23417. this._frustum.setFromProjectionMatrix(_projScreenMatrix$1);
  23418. 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);
  23419. shadowMatrix.multiply(shadowCamera.projectionMatrix);
  23420. shadowMatrix.multiply(shadowCamera.matrixWorldInverse);
  23421. }
  23422. getViewport(viewportIndex) {
  23423. return this._viewports[viewportIndex];
  23424. }
  23425. getFrameExtents() {
  23426. return this._frameExtents;
  23427. }
  23428. dispose() {
  23429. if (this.map) {
  23430. this.map.dispose();
  23431. }
  23432. if (this.mapPass) {
  23433. this.mapPass.dispose();
  23434. }
  23435. }
  23436. copy(source) {
  23437. this.camera = source.camera.clone();
  23438. this.bias = source.bias;
  23439. this.radius = source.radius;
  23440. this.mapSize.copy(source.mapSize);
  23441. return this;
  23442. }
  23443. clone() {
  23444. return new this.constructor().copy(this);
  23445. }
  23446. toJSON() {
  23447. const object = {};
  23448. if (this.bias !== 0) object.bias = this.bias;
  23449. if (this.normalBias !== 0) object.normalBias = this.normalBias;
  23450. if (this.radius !== 1) object.radius = this.radius;
  23451. if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
  23452. object.camera = this.camera.toJSON(false).object;
  23453. delete object.camera.matrix;
  23454. return object;
  23455. }
  23456. }
  23457. class SpotLightShadow extends LightShadow {
  23458. constructor() {
  23459. super(new PerspectiveCamera(50, 1, 0.5, 500));
  23460. this.focus = 1;
  23461. }
  23462. updateMatrices(light) {
  23463. const camera = this.camera;
  23464. const fov = RAD2DEG * 2 * light.angle * this.focus;
  23465. const aspect = this.mapSize.width / this.mapSize.height;
  23466. const far = light.distance || camera.far;
  23467. if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
  23468. camera.fov = fov;
  23469. camera.aspect = aspect;
  23470. camera.far = far;
  23471. camera.updateProjectionMatrix();
  23472. }
  23473. super.updateMatrices(light);
  23474. }
  23475. copy(source) {
  23476. super.copy(source);
  23477. this.focus = source.focus;
  23478. return this;
  23479. }
  23480. }
  23481. SpotLightShadow.prototype.isSpotLightShadow = true;
  23482. class SpotLight extends Light {
  23483. constructor(color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 1) {
  23484. super(color, intensity);
  23485. this.type = 'SpotLight';
  23486. this.position.copy(Object3D.DefaultUp);
  23487. this.updateMatrix();
  23488. this.target = new Object3D();
  23489. this.distance = distance;
  23490. this.angle = angle;
  23491. this.penumbra = penumbra;
  23492. this.decay = decay; // for physically correct lights, should be 2.
  23493. this.shadow = new SpotLightShadow();
  23494. }
  23495. get power() {
  23496. // compute the light's luminous power (in lumens) from its intensity (in candela)
  23497. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  23498. return this.intensity * Math.PI;
  23499. }
  23500. set power(power) {
  23501. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  23502. this.intensity = power / Math.PI;
  23503. }
  23504. dispose() {
  23505. this.shadow.dispose();
  23506. }
  23507. copy(source) {
  23508. super.copy(source);
  23509. this.distance = source.distance;
  23510. this.angle = source.angle;
  23511. this.penumbra = source.penumbra;
  23512. this.decay = source.decay;
  23513. this.target = source.target.clone();
  23514. this.shadow = source.shadow.clone();
  23515. return this;
  23516. }
  23517. }
  23518. SpotLight.prototype.isSpotLight = true;
  23519. const _projScreenMatrix = /*@__PURE__*/new Matrix4();
  23520. const _lightPositionWorld = /*@__PURE__*/new Vector3();
  23521. const _lookTarget = /*@__PURE__*/new Vector3();
  23522. class PointLightShadow extends LightShadow {
  23523. constructor() {
  23524. super(new PerspectiveCamera(90, 1, 0.5, 500));
  23525. this._frameExtents = new Vector2(4, 2);
  23526. this._viewportCount = 6;
  23527. this._viewports = [// These viewports map a cube-map onto a 2D texture with the
  23528. // following orientation:
  23529. //
  23530. // xzXZ
  23531. // y Y
  23532. //
  23533. // X - Positive x direction
  23534. // x - Negative x direction
  23535. // Y - Positive y direction
  23536. // y - Negative y direction
  23537. // Z - Positive z direction
  23538. // z - Negative z direction
  23539. // positive X
  23540. new Vector4(2, 1, 1, 1), // negative X
  23541. new Vector4(0, 1, 1, 1), // positive Z
  23542. new Vector4(3, 1, 1, 1), // negative Z
  23543. new Vector4(1, 1, 1, 1), // positive Y
  23544. new Vector4(3, 0, 1, 1), // negative Y
  23545. new Vector4(1, 0, 1, 1)];
  23546. 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)];
  23547. 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)];
  23548. }
  23549. updateMatrices(light, viewportIndex = 0) {
  23550. const camera = this.camera;
  23551. const shadowMatrix = this.matrix;
  23552. const far = light.distance || camera.far;
  23553. if (far !== camera.far) {
  23554. camera.far = far;
  23555. camera.updateProjectionMatrix();
  23556. }
  23557. _lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  23558. camera.position.copy(_lightPositionWorld);
  23559. _lookTarget.copy(camera.position);
  23560. _lookTarget.add(this._cubeDirections[viewportIndex]);
  23561. camera.up.copy(this._cubeUps[viewportIndex]);
  23562. camera.lookAt(_lookTarget);
  23563. camera.updateMatrixWorld();
  23564. shadowMatrix.makeTranslation(-_lightPositionWorld.x, -_lightPositionWorld.y, -_lightPositionWorld.z);
  23565. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  23566. this._frustum.setFromProjectionMatrix(_projScreenMatrix);
  23567. }
  23568. }
  23569. PointLightShadow.prototype.isPointLightShadow = true;
  23570. class PointLight extends Light {
  23571. constructor(color, intensity, distance = 0, decay = 1) {
  23572. super(color, intensity);
  23573. this.type = 'PointLight';
  23574. this.distance = distance;
  23575. this.decay = decay; // for physically correct lights, should be 2.
  23576. this.shadow = new PointLightShadow();
  23577. }
  23578. get power() {
  23579. // compute the light's luminous power (in lumens) from its intensity (in candela)
  23580. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  23581. return this.intensity * 4 * Math.PI;
  23582. }
  23583. set power(power) {
  23584. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  23585. this.intensity = power / (4 * Math.PI);
  23586. }
  23587. dispose() {
  23588. this.shadow.dispose();
  23589. }
  23590. copy(source) {
  23591. super.copy(source);
  23592. this.distance = source.distance;
  23593. this.decay = source.decay;
  23594. this.shadow = source.shadow.clone();
  23595. return this;
  23596. }
  23597. }
  23598. PointLight.prototype.isPointLight = true;
  23599. class DirectionalLightShadow extends LightShadow {
  23600. constructor() {
  23601. super(new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
  23602. }
  23603. }
  23604. DirectionalLightShadow.prototype.isDirectionalLightShadow = true;
  23605. class DirectionalLight extends Light {
  23606. constructor(color, intensity) {
  23607. super(color, intensity);
  23608. this.type = 'DirectionalLight';
  23609. this.position.copy(Object3D.DefaultUp);
  23610. this.updateMatrix();
  23611. this.target = new Object3D();
  23612. this.shadow = new DirectionalLightShadow();
  23613. }
  23614. dispose() {
  23615. this.shadow.dispose();
  23616. }
  23617. copy(source) {
  23618. super.copy(source);
  23619. this.target = source.target.clone();
  23620. this.shadow = source.shadow.clone();
  23621. return this;
  23622. }
  23623. }
  23624. DirectionalLight.prototype.isDirectionalLight = true;
  23625. class AmbientLight extends Light {
  23626. constructor(color, intensity) {
  23627. super(color, intensity);
  23628. this.type = 'AmbientLight';
  23629. }
  23630. }
  23631. AmbientLight.prototype.isAmbientLight = true;
  23632. class RectAreaLight extends Light {
  23633. constructor(color, intensity, width = 10, height = 10) {
  23634. super(color, intensity);
  23635. this.type = 'RectAreaLight';
  23636. this.width = width;
  23637. this.height = height;
  23638. }
  23639. get power() {
  23640. // compute the light's luminous power (in lumens) from its intensity (in nits)
  23641. return this.intensity * this.width * this.height * Math.PI;
  23642. }
  23643. set power(power) {
  23644. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  23645. this.intensity = power / (this.width * this.height * Math.PI);
  23646. }
  23647. copy(source) {
  23648. super.copy(source);
  23649. this.width = source.width;
  23650. this.height = source.height;
  23651. return this;
  23652. }
  23653. toJSON(meta) {
  23654. const data = super.toJSON(meta);
  23655. data.object.width = this.width;
  23656. data.object.height = this.height;
  23657. return data;
  23658. }
  23659. }
  23660. RectAreaLight.prototype.isRectAreaLight = true;
  23661. /**
  23662. * Primary reference:
  23663. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  23664. *
  23665. * Secondary reference:
  23666. * https://www.ppsloan.org/publications/StupidSH36.pdf
  23667. */
  23668. // 3-band SH defined by 9 coefficients
  23669. class SphericalHarmonics3 {
  23670. constructor() {
  23671. this.coefficients = [];
  23672. for (let i = 0; i < 9; i++) {
  23673. this.coefficients.push(new Vector3());
  23674. }
  23675. }
  23676. set(coefficients) {
  23677. for (let i = 0; i < 9; i++) {
  23678. this.coefficients[i].copy(coefficients[i]);
  23679. }
  23680. return this;
  23681. }
  23682. zero() {
  23683. for (let i = 0; i < 9; i++) {
  23684. this.coefficients[i].set(0, 0, 0);
  23685. }
  23686. return this;
  23687. } // get the radiance in the direction of the normal
  23688. // target is a Vector3
  23689. getAt(normal, target) {
  23690. // normal is assumed to be unit length
  23691. const x = normal.x,
  23692. y = normal.y,
  23693. z = normal.z;
  23694. const coeff = this.coefficients; // band 0
  23695. target.copy(coeff[0]).multiplyScalar(0.282095); // band 1
  23696. target.addScaledVector(coeff[1], 0.488603 * y);
  23697. target.addScaledVector(coeff[2], 0.488603 * z);
  23698. target.addScaledVector(coeff[3], 0.488603 * x); // band 2
  23699. target.addScaledVector(coeff[4], 1.092548 * (x * y));
  23700. target.addScaledVector(coeff[5], 1.092548 * (y * z));
  23701. target.addScaledVector(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
  23702. target.addScaledVector(coeff[7], 1.092548 * (x * z));
  23703. target.addScaledVector(coeff[8], 0.546274 * (x * x - y * y));
  23704. return target;
  23705. } // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  23706. // target is a Vector3
  23707. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  23708. getIrradianceAt(normal, target) {
  23709. // normal is assumed to be unit length
  23710. const x = normal.x,
  23711. y = normal.y,
  23712. z = normal.z;
  23713. const coeff = this.coefficients; // band 0
  23714. target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
  23715. // band 1
  23716. target.addScaledVector(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
  23717. target.addScaledVector(coeff[2], 2.0 * 0.511664 * z);
  23718. target.addScaledVector(coeff[3], 2.0 * 0.511664 * x); // band 2
  23719. target.addScaledVector(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
  23720. target.addScaledVector(coeff[5], 2.0 * 0.429043 * y * z);
  23721. target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
  23722. target.addScaledVector(coeff[7], 2.0 * 0.429043 * x * z);
  23723. target.addScaledVector(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
  23724. return target;
  23725. }
  23726. add(sh) {
  23727. for (let i = 0; i < 9; i++) {
  23728. this.coefficients[i].add(sh.coefficients[i]);
  23729. }
  23730. return this;
  23731. }
  23732. addScaledSH(sh, s) {
  23733. for (let i = 0; i < 9; i++) {
  23734. this.coefficients[i].addScaledVector(sh.coefficients[i], s);
  23735. }
  23736. return this;
  23737. }
  23738. scale(s) {
  23739. for (let i = 0; i < 9; i++) {
  23740. this.coefficients[i].multiplyScalar(s);
  23741. }
  23742. return this;
  23743. }
  23744. lerp(sh, alpha) {
  23745. for (let i = 0; i < 9; i++) {
  23746. this.coefficients[i].lerp(sh.coefficients[i], alpha);
  23747. }
  23748. return this;
  23749. }
  23750. equals(sh) {
  23751. for (let i = 0; i < 9; i++) {
  23752. if (!this.coefficients[i].equals(sh.coefficients[i])) {
  23753. return false;
  23754. }
  23755. }
  23756. return true;
  23757. }
  23758. copy(sh) {
  23759. return this.set(sh.coefficients);
  23760. }
  23761. clone() {
  23762. return new this.constructor().copy(this);
  23763. }
  23764. fromArray(array, offset = 0) {
  23765. const coefficients = this.coefficients;
  23766. for (let i = 0; i < 9; i++) {
  23767. coefficients[i].fromArray(array, offset + i * 3);
  23768. }
  23769. return this;
  23770. }
  23771. toArray(array = [], offset = 0) {
  23772. const coefficients = this.coefficients;
  23773. for (let i = 0; i < 9; i++) {
  23774. coefficients[i].toArray(array, offset + i * 3);
  23775. }
  23776. return array;
  23777. } // evaluate the basis functions
  23778. // shBasis is an Array[ 9 ]
  23779. static getBasisAt(normal, shBasis) {
  23780. // normal is assumed to be unit length
  23781. const x = normal.x,
  23782. y = normal.y,
  23783. z = normal.z; // band 0
  23784. shBasis[0] = 0.282095; // band 1
  23785. shBasis[1] = 0.488603 * y;
  23786. shBasis[2] = 0.488603 * z;
  23787. shBasis[3] = 0.488603 * x; // band 2
  23788. shBasis[4] = 1.092548 * x * y;
  23789. shBasis[5] = 1.092548 * y * z;
  23790. shBasis[6] = 0.315392 * (3 * z * z - 1);
  23791. shBasis[7] = 1.092548 * x * z;
  23792. shBasis[8] = 0.546274 * (x * x - y * y);
  23793. }
  23794. }
  23795. SphericalHarmonics3.prototype.isSphericalHarmonics3 = true;
  23796. class LightProbe extends Light {
  23797. constructor(sh = new SphericalHarmonics3(), intensity = 1) {
  23798. super(undefined, intensity);
  23799. this.sh = sh;
  23800. }
  23801. copy(source) {
  23802. super.copy(source);
  23803. this.sh.copy(source.sh);
  23804. return this;
  23805. }
  23806. fromJSON(json) {
  23807. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  23808. this.sh.fromArray(json.sh);
  23809. return this;
  23810. }
  23811. toJSON(meta) {
  23812. const data = super.toJSON(meta);
  23813. data.object.sh = this.sh.toArray();
  23814. return data;
  23815. }
  23816. }
  23817. LightProbe.prototype.isLightProbe = true;
  23818. class MaterialLoader extends Loader {
  23819. constructor(manager) {
  23820. super(manager);
  23821. this.textures = {};
  23822. }
  23823. load(url, onLoad, onProgress, onError) {
  23824. const scope = this;
  23825. const loader = new FileLoader(scope.manager);
  23826. loader.setPath(scope.path);
  23827. loader.setRequestHeader(scope.requestHeader);
  23828. loader.setWithCredentials(scope.withCredentials);
  23829. loader.load(url, function (text) {
  23830. try {
  23831. onLoad(scope.parse(JSON.parse(text)));
  23832. } catch (e) {
  23833. if (onError) {
  23834. onError(e);
  23835. } else {
  23836. console.error(e);
  23837. }
  23838. scope.manager.itemError(url);
  23839. }
  23840. }, onProgress, onError);
  23841. }
  23842. parse(json) {
  23843. const textures = this.textures;
  23844. function getTexture(name) {
  23845. if (textures[name] === undefined) {
  23846. console.warn('THREE.MaterialLoader: Undefined texture', name);
  23847. }
  23848. return textures[name];
  23849. }
  23850. const material = new Materials[json.type]();
  23851. if (json.uuid !== undefined) material.uuid = json.uuid;
  23852. if (json.name !== undefined) material.name = json.name;
  23853. if (json.color !== undefined && material.color !== undefined) material.color.setHex(json.color);
  23854. if (json.roughness !== undefined) material.roughness = json.roughness;
  23855. if (json.metalness !== undefined) material.metalness = json.metalness;
  23856. if (json.sheen !== undefined) material.sheen = json.sheen;
  23857. if (json.sheenColor !== undefined) material.sheenColor = new Color().setHex(json.sheenColor);
  23858. if (json.sheenRoughness !== undefined) material.sheenRoughness = json.sheenRoughness;
  23859. if (json.emissive !== undefined && material.emissive !== undefined) material.emissive.setHex(json.emissive);
  23860. if (json.specular !== undefined && material.specular !== undefined) material.specular.setHex(json.specular);
  23861. if (json.specularIntensity !== undefined) material.specularIntensity = json.specularIntensity;
  23862. if (json.specularColor !== undefined && material.specularColor !== undefined) material.specularColor.setHex(json.specularColor);
  23863. if (json.shininess !== undefined) material.shininess = json.shininess;
  23864. if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
  23865. if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
  23866. if (json.transmission !== undefined) material.transmission = json.transmission;
  23867. if (json.thickness !== undefined) material.thickness = json.thickness;
  23868. if (json.attenuationDistance !== undefined) material.attenuationDistance = json.attenuationDistance;
  23869. if (json.attenuationColor !== undefined && material.attenuationColor !== undefined) material.attenuationColor.setHex(json.attenuationColor);
  23870. if (json.fog !== undefined) material.fog = json.fog;
  23871. if (json.flatShading !== undefined) material.flatShading = json.flatShading;
  23872. if (json.blending !== undefined) material.blending = json.blending;
  23873. if (json.combine !== undefined) material.combine = json.combine;
  23874. if (json.side !== undefined) material.side = json.side;
  23875. if (json.shadowSide !== undefined) material.shadowSide = json.shadowSide;
  23876. if (json.opacity !== undefined) material.opacity = json.opacity;
  23877. if (json.format !== undefined) material.format = json.format;
  23878. if (json.transparent !== undefined) material.transparent = json.transparent;
  23879. if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
  23880. if (json.depthTest !== undefined) material.depthTest = json.depthTest;
  23881. if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
  23882. if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
  23883. if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
  23884. if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
  23885. if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
  23886. if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
  23887. if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
  23888. if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
  23889. if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
  23890. if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
  23891. if (json.wireframe !== undefined) material.wireframe = json.wireframe;
  23892. if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
  23893. if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
  23894. if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
  23895. if (json.rotation !== undefined) material.rotation = json.rotation;
  23896. if (json.linewidth !== 1) material.linewidth = json.linewidth;
  23897. if (json.dashSize !== undefined) material.dashSize = json.dashSize;
  23898. if (json.gapSize !== undefined) material.gapSize = json.gapSize;
  23899. if (json.scale !== undefined) material.scale = json.scale;
  23900. if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
  23901. if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
  23902. if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
  23903. if (json.dithering !== undefined) material.dithering = json.dithering;
  23904. if (json.alphaToCoverage !== undefined) material.alphaToCoverage = json.alphaToCoverage;
  23905. if (json.premultipliedAlpha !== undefined) material.premultipliedAlpha = json.premultipliedAlpha;
  23906. if (json.visible !== undefined) material.visible = json.visible;
  23907. if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
  23908. if (json.userData !== undefined) material.userData = json.userData;
  23909. if (json.vertexColors !== undefined) {
  23910. if (typeof json.vertexColors === 'number') {
  23911. material.vertexColors = json.vertexColors > 0 ? true : false;
  23912. } else {
  23913. material.vertexColors = json.vertexColors;
  23914. }
  23915. } // Shader Material
  23916. if (json.uniforms !== undefined) {
  23917. for (const name in json.uniforms) {
  23918. const uniform = json.uniforms[name];
  23919. material.uniforms[name] = {};
  23920. switch (uniform.type) {
  23921. case 't':
  23922. material.uniforms[name].value = getTexture(uniform.value);
  23923. break;
  23924. case 'c':
  23925. material.uniforms[name].value = new Color().setHex(uniform.value);
  23926. break;
  23927. case 'v2':
  23928. material.uniforms[name].value = new Vector2().fromArray(uniform.value);
  23929. break;
  23930. case 'v3':
  23931. material.uniforms[name].value = new Vector3().fromArray(uniform.value);
  23932. break;
  23933. case 'v4':
  23934. material.uniforms[name].value = new Vector4().fromArray(uniform.value);
  23935. break;
  23936. case 'm3':
  23937. material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
  23938. break;
  23939. case 'm4':
  23940. material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
  23941. break;
  23942. default:
  23943. material.uniforms[name].value = uniform.value;
  23944. }
  23945. }
  23946. }
  23947. if (json.defines !== undefined) material.defines = json.defines;
  23948. if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
  23949. if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
  23950. if (json.extensions !== undefined) {
  23951. for (const key in json.extensions) {
  23952. material.extensions[key] = json.extensions[key];
  23953. }
  23954. } // Deprecated
  23955. if (json.shading !== undefined) material.flatShading = json.shading === 1; // THREE.FlatShading
  23956. // for PointsMaterial
  23957. if (json.size !== undefined) material.size = json.size;
  23958. if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // maps
  23959. if (json.map !== undefined) material.map = getTexture(json.map);
  23960. if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
  23961. if (json.alphaMap !== undefined) material.alphaMap = getTexture(json.alphaMap);
  23962. if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
  23963. if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
  23964. if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
  23965. if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
  23966. if (json.normalScale !== undefined) {
  23967. let normalScale = json.normalScale;
  23968. if (Array.isArray(normalScale) === false) {
  23969. // Blender exporter used to export a scalar. See #7459
  23970. normalScale = [normalScale, normalScale];
  23971. }
  23972. material.normalScale = new Vector2().fromArray(normalScale);
  23973. }
  23974. if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
  23975. if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
  23976. if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
  23977. if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
  23978. if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
  23979. if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
  23980. if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
  23981. if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
  23982. if (json.specularIntensityMap !== undefined) material.specularIntensityMap = getTexture(json.specularIntensityMap);
  23983. if (json.specularColorMap !== undefined) material.specularColorMap = getTexture(json.specularColorMap);
  23984. if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
  23985. if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
  23986. if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
  23987. if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
  23988. if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
  23989. if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
  23990. if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
  23991. if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
  23992. if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
  23993. if (json.clearcoatMap !== undefined) material.clearcoatMap = getTexture(json.clearcoatMap);
  23994. if (json.clearcoatRoughnessMap !== undefined) material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap);
  23995. if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
  23996. if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
  23997. if (json.transmissionMap !== undefined) material.transmissionMap = getTexture(json.transmissionMap);
  23998. if (json.thicknessMap !== undefined) material.thicknessMap = getTexture(json.thicknessMap);
  23999. if (json.sheenColorMap !== undefined) material.sheenColorMap = getTexture(json.sheenColorMap);
  24000. if (json.sheenRoughnessMap !== undefined) material.sheenRoughnessMap = getTexture(json.sheenRoughnessMap);
  24001. return material;
  24002. }
  24003. setTextures(value) {
  24004. this.textures = value;
  24005. return this;
  24006. }
  24007. }
  24008. class LoaderUtils {
  24009. static decodeText(array) {
  24010. if (typeof TextDecoder !== 'undefined') {
  24011. return new TextDecoder().decode(array);
  24012. } // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  24013. // throws a "maximum call stack size exceeded" error for large arrays.
  24014. let s = '';
  24015. for (let i = 0, il = array.length; i < il; i++) {
  24016. // Implicitly assumes little-endian.
  24017. s += String.fromCharCode(array[i]);
  24018. }
  24019. try {
  24020. // merges multi-byte utf-8 characters.
  24021. return decodeURIComponent(escape(s));
  24022. } catch (e) {
  24023. // see #16358
  24024. return s;
  24025. }
  24026. }
  24027. static extractUrlBase(url) {
  24028. const index = url.lastIndexOf('/');
  24029. if (index === -1) return './';
  24030. return url.substr(0, index + 1);
  24031. }
  24032. static resolveURL(url, path) {
  24033. // Invalid URL
  24034. if (typeof url !== 'string' || url === '') return ''; // Host Relative URL
  24035. if (/^https?:\/\//i.test(path) && /^\//.test(url)) {
  24036. path = path.replace(/(^https?:\/\/[^\/]+).*/i, '$1');
  24037. } // Absolute URL http://,https://,//
  24038. if (/^(https?:)?\/\//i.test(url)) return url; // Data URI
  24039. if (/^data:.*,.*$/i.test(url)) return url; // Blob URL
  24040. if (/^blob:.*$/i.test(url)) return url; // Relative URL
  24041. return path + url;
  24042. }
  24043. }
  24044. class InstancedBufferGeometry extends BufferGeometry {
  24045. constructor() {
  24046. super();
  24047. this.type = 'InstancedBufferGeometry';
  24048. this.instanceCount = Infinity;
  24049. }
  24050. copy(source) {
  24051. super.copy(source);
  24052. this.instanceCount = source.instanceCount;
  24053. return this;
  24054. }
  24055. clone() {
  24056. return new this.constructor().copy(this);
  24057. }
  24058. toJSON() {
  24059. const data = super.toJSON(this);
  24060. data.instanceCount = this.instanceCount;
  24061. data.isInstancedBufferGeometry = true;
  24062. return data;
  24063. }
  24064. }
  24065. InstancedBufferGeometry.prototype.isInstancedBufferGeometry = true;
  24066. class BufferGeometryLoader extends Loader {
  24067. constructor(manager) {
  24068. super(manager);
  24069. }
  24070. load(url, onLoad, onProgress, onError) {
  24071. const scope = this;
  24072. const loader = new FileLoader(scope.manager);
  24073. loader.setPath(scope.path);
  24074. loader.setRequestHeader(scope.requestHeader);
  24075. loader.setWithCredentials(scope.withCredentials);
  24076. loader.load(url, function (text) {
  24077. try {
  24078. onLoad(scope.parse(JSON.parse(text)));
  24079. } catch (e) {
  24080. if (onError) {
  24081. onError(e);
  24082. } else {
  24083. console.error(e);
  24084. }
  24085. scope.manager.itemError(url);
  24086. }
  24087. }, onProgress, onError);
  24088. }
  24089. parse(json) {
  24090. const interleavedBufferMap = {};
  24091. const arrayBufferMap = {};
  24092. function getInterleavedBuffer(json, uuid) {
  24093. if (interleavedBufferMap[uuid] !== undefined) return interleavedBufferMap[uuid];
  24094. const interleavedBuffers = json.interleavedBuffers;
  24095. const interleavedBuffer = interleavedBuffers[uuid];
  24096. const buffer = getArrayBuffer(json, interleavedBuffer.buffer);
  24097. const array = getTypedArray(interleavedBuffer.type, buffer);
  24098. const ib = new InterleavedBuffer(array, interleavedBuffer.stride);
  24099. ib.uuid = interleavedBuffer.uuid;
  24100. interleavedBufferMap[uuid] = ib;
  24101. return ib;
  24102. }
  24103. function getArrayBuffer(json, uuid) {
  24104. if (arrayBufferMap[uuid] !== undefined) return arrayBufferMap[uuid];
  24105. const arrayBuffers = json.arrayBuffers;
  24106. const arrayBuffer = arrayBuffers[uuid];
  24107. const ab = new Uint32Array(arrayBuffer).buffer;
  24108. arrayBufferMap[uuid] = ab;
  24109. return ab;
  24110. }
  24111. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  24112. const index = json.data.index;
  24113. if (index !== undefined) {
  24114. const typedArray = getTypedArray(index.type, index.array);
  24115. geometry.setIndex(new BufferAttribute(typedArray, 1));
  24116. }
  24117. const attributes = json.data.attributes;
  24118. for (const key in attributes) {
  24119. const attribute = attributes[key];
  24120. let bufferAttribute;
  24121. if (attribute.isInterleavedBufferAttribute) {
  24122. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  24123. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  24124. } else {
  24125. const typedArray = getTypedArray(attribute.type, attribute.array);
  24126. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  24127. bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized);
  24128. }
  24129. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  24130. if (attribute.usage !== undefined) bufferAttribute.setUsage(attribute.usage);
  24131. if (attribute.updateRange !== undefined) {
  24132. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  24133. bufferAttribute.updateRange.count = attribute.updateRange.count;
  24134. }
  24135. geometry.setAttribute(key, bufferAttribute);
  24136. }
  24137. const morphAttributes = json.data.morphAttributes;
  24138. if (morphAttributes) {
  24139. for (const key in morphAttributes) {
  24140. const attributeArray = morphAttributes[key];
  24141. const array = [];
  24142. for (let i = 0, il = attributeArray.length; i < il; i++) {
  24143. const attribute = attributeArray[i];
  24144. let bufferAttribute;
  24145. if (attribute.isInterleavedBufferAttribute) {
  24146. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  24147. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  24148. } else {
  24149. const typedArray = getTypedArray(attribute.type, attribute.array);
  24150. bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized);
  24151. }
  24152. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  24153. array.push(bufferAttribute);
  24154. }
  24155. geometry.morphAttributes[key] = array;
  24156. }
  24157. }
  24158. const morphTargetsRelative = json.data.morphTargetsRelative;
  24159. if (morphTargetsRelative) {
  24160. geometry.morphTargetsRelative = true;
  24161. }
  24162. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  24163. if (groups !== undefined) {
  24164. for (let i = 0, n = groups.length; i !== n; ++i) {
  24165. const group = groups[i];
  24166. geometry.addGroup(group.start, group.count, group.materialIndex);
  24167. }
  24168. }
  24169. const boundingSphere = json.data.boundingSphere;
  24170. if (boundingSphere !== undefined) {
  24171. const center = new Vector3();
  24172. if (boundingSphere.center !== undefined) {
  24173. center.fromArray(boundingSphere.center);
  24174. }
  24175. geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
  24176. }
  24177. if (json.name) geometry.name = json.name;
  24178. if (json.userData) geometry.userData = json.userData;
  24179. return geometry;
  24180. }
  24181. }
  24182. class ObjectLoader extends Loader {
  24183. constructor(manager) {
  24184. super(manager);
  24185. }
  24186. load(url, onLoad, onProgress, onError) {
  24187. const scope = this;
  24188. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  24189. this.resourcePath = this.resourcePath || path;
  24190. const loader = new FileLoader(this.manager);
  24191. loader.setPath(this.path);
  24192. loader.setRequestHeader(this.requestHeader);
  24193. loader.setWithCredentials(this.withCredentials);
  24194. loader.load(url, function (text) {
  24195. let json = null;
  24196. try {
  24197. json = JSON.parse(text);
  24198. } catch (error) {
  24199. if (onError !== undefined) onError(error);
  24200. console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
  24201. return;
  24202. }
  24203. const metadata = json.metadata;
  24204. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  24205. console.error('THREE.ObjectLoader: Can\'t load ' + url);
  24206. return;
  24207. }
  24208. scope.parse(json, onLoad);
  24209. }, onProgress, onError);
  24210. }
  24211. async loadAsync(url, onProgress) {
  24212. const scope = this;
  24213. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  24214. this.resourcePath = this.resourcePath || path;
  24215. const loader = new FileLoader(this.manager);
  24216. loader.setPath(this.path);
  24217. loader.setRequestHeader(this.requestHeader);
  24218. loader.setWithCredentials(this.withCredentials);
  24219. const text = await loader.loadAsync(url, onProgress);
  24220. const json = JSON.parse(text);
  24221. const metadata = json.metadata;
  24222. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  24223. throw new Error('THREE.ObjectLoader: Can\'t load ' + url);
  24224. }
  24225. return await scope.parseAsync(json);
  24226. }
  24227. parse(json, onLoad) {
  24228. const animations = this.parseAnimations(json.animations);
  24229. const shapes = this.parseShapes(json.shapes);
  24230. const geometries = this.parseGeometries(json.geometries, shapes);
  24231. const images = this.parseImages(json.images, function () {
  24232. if (onLoad !== undefined) onLoad(object);
  24233. });
  24234. const textures = this.parseTextures(json.textures, images);
  24235. const materials = this.parseMaterials(json.materials, textures);
  24236. const object = this.parseObject(json.object, geometries, materials, textures, animations);
  24237. const skeletons = this.parseSkeletons(json.skeletons, object);
  24238. this.bindSkeletons(object, skeletons); //
  24239. if (onLoad !== undefined) {
  24240. let hasImages = false;
  24241. for (const uuid in images) {
  24242. if (images[uuid] instanceof HTMLImageElement) {
  24243. hasImages = true;
  24244. break;
  24245. }
  24246. }
  24247. if (hasImages === false) onLoad(object);
  24248. }
  24249. return object;
  24250. }
  24251. async parseAsync(json) {
  24252. const animations = this.parseAnimations(json.animations);
  24253. const shapes = this.parseShapes(json.shapes);
  24254. const geometries = this.parseGeometries(json.geometries, shapes);
  24255. const images = await this.parseImagesAsync(json.images);
  24256. const textures = this.parseTextures(json.textures, images);
  24257. const materials = this.parseMaterials(json.materials, textures);
  24258. const object = this.parseObject(json.object, geometries, materials, textures, animations);
  24259. const skeletons = this.parseSkeletons(json.skeletons, object);
  24260. this.bindSkeletons(object, skeletons);
  24261. return object;
  24262. }
  24263. parseShapes(json) {
  24264. const shapes = {};
  24265. if (json !== undefined) {
  24266. for (let i = 0, l = json.length; i < l; i++) {
  24267. const shape = new Shape().fromJSON(json[i]);
  24268. shapes[shape.uuid] = shape;
  24269. }
  24270. }
  24271. return shapes;
  24272. }
  24273. parseSkeletons(json, object) {
  24274. const skeletons = {};
  24275. const bones = {}; // generate bone lookup table
  24276. object.traverse(function (child) {
  24277. if (child.isBone) bones[child.uuid] = child;
  24278. }); // create skeletons
  24279. if (json !== undefined) {
  24280. for (let i = 0, l = json.length; i < l; i++) {
  24281. const skeleton = new Skeleton().fromJSON(json[i], bones);
  24282. skeletons[skeleton.uuid] = skeleton;
  24283. }
  24284. }
  24285. return skeletons;
  24286. }
  24287. parseGeometries(json, shapes) {
  24288. const geometries = {};
  24289. if (json !== undefined) {
  24290. const bufferGeometryLoader = new BufferGeometryLoader();
  24291. for (let i = 0, l = json.length; i < l; i++) {
  24292. let geometry;
  24293. const data = json[i];
  24294. switch (data.type) {
  24295. case 'BufferGeometry':
  24296. case 'InstancedBufferGeometry':
  24297. geometry = bufferGeometryLoader.parse(data);
  24298. break;
  24299. case 'Geometry':
  24300. console.error('THREE.ObjectLoader: The legacy Geometry type is no longer supported.');
  24301. break;
  24302. default:
  24303. if (data.type in Geometries) {
  24304. geometry = Geometries[data.type].fromJSON(data, shapes);
  24305. } else {
  24306. console.warn(`THREE.ObjectLoader: Unsupported geometry type "${data.type}"`);
  24307. }
  24308. }
  24309. geometry.uuid = data.uuid;
  24310. if (data.name !== undefined) geometry.name = data.name;
  24311. if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
  24312. geometries[data.uuid] = geometry;
  24313. }
  24314. }
  24315. return geometries;
  24316. }
  24317. parseMaterials(json, textures) {
  24318. const cache = {}; // MultiMaterial
  24319. const materials = {};
  24320. if (json !== undefined) {
  24321. const loader = new MaterialLoader();
  24322. loader.setTextures(textures);
  24323. for (let i = 0, l = json.length; i < l; i++) {
  24324. const data = json[i];
  24325. if (data.type === 'MultiMaterial') {
  24326. // Deprecated
  24327. const array = [];
  24328. for (let j = 0; j < data.materials.length; j++) {
  24329. const material = data.materials[j];
  24330. if (cache[material.uuid] === undefined) {
  24331. cache[material.uuid] = loader.parse(material);
  24332. }
  24333. array.push(cache[material.uuid]);
  24334. }
  24335. materials[data.uuid] = array;
  24336. } else {
  24337. if (cache[data.uuid] === undefined) {
  24338. cache[data.uuid] = loader.parse(data);
  24339. }
  24340. materials[data.uuid] = cache[data.uuid];
  24341. }
  24342. }
  24343. }
  24344. return materials;
  24345. }
  24346. parseAnimations(json) {
  24347. const animations = {};
  24348. if (json !== undefined) {
  24349. for (let i = 0; i < json.length; i++) {
  24350. const data = json[i];
  24351. const clip = AnimationClip.parse(data);
  24352. animations[clip.uuid] = clip;
  24353. }
  24354. }
  24355. return animations;
  24356. }
  24357. parseImages(json, onLoad) {
  24358. const scope = this;
  24359. const images = {};
  24360. let loader;
  24361. function loadImage(url) {
  24362. scope.manager.itemStart(url);
  24363. return loader.load(url, function () {
  24364. scope.manager.itemEnd(url);
  24365. }, undefined, function () {
  24366. scope.manager.itemError(url);
  24367. scope.manager.itemEnd(url);
  24368. });
  24369. }
  24370. function deserializeImage(image) {
  24371. if (typeof image === 'string') {
  24372. const url = image;
  24373. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  24374. return loadImage(path);
  24375. } else {
  24376. if (image.data) {
  24377. return {
  24378. data: getTypedArray(image.type, image.data),
  24379. width: image.width,
  24380. height: image.height
  24381. };
  24382. } else {
  24383. return null;
  24384. }
  24385. }
  24386. }
  24387. if (json !== undefined && json.length > 0) {
  24388. const manager = new LoadingManager(onLoad);
  24389. loader = new ImageLoader(manager);
  24390. loader.setCrossOrigin(this.crossOrigin);
  24391. for (let i = 0, il = json.length; i < il; i++) {
  24392. const image = json[i];
  24393. const url = image.url;
  24394. if (Array.isArray(url)) {
  24395. // load array of images e.g CubeTexture
  24396. images[image.uuid] = [];
  24397. for (let j = 0, jl = url.length; j < jl; j++) {
  24398. const currentUrl = url[j];
  24399. const deserializedImage = deserializeImage(currentUrl);
  24400. if (deserializedImage !== null) {
  24401. if (deserializedImage instanceof HTMLImageElement) {
  24402. images[image.uuid].push(deserializedImage);
  24403. } else {
  24404. // special case: handle array of data textures for cube textures
  24405. images[image.uuid].push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  24406. }
  24407. }
  24408. }
  24409. } else {
  24410. // load single image
  24411. const deserializedImage = deserializeImage(image.url);
  24412. if (deserializedImage !== null) {
  24413. images[image.uuid] = deserializedImage;
  24414. }
  24415. }
  24416. }
  24417. }
  24418. return images;
  24419. }
  24420. async parseImagesAsync(json) {
  24421. const scope = this;
  24422. const images = {};
  24423. let loader;
  24424. async function deserializeImage(image) {
  24425. if (typeof image === 'string') {
  24426. const url = image;
  24427. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  24428. return await loader.loadAsync(path);
  24429. } else {
  24430. if (image.data) {
  24431. return {
  24432. data: getTypedArray(image.type, image.data),
  24433. width: image.width,
  24434. height: image.height
  24435. };
  24436. } else {
  24437. return null;
  24438. }
  24439. }
  24440. }
  24441. if (json !== undefined && json.length > 0) {
  24442. loader = new ImageLoader(this.manager);
  24443. loader.setCrossOrigin(this.crossOrigin);
  24444. for (let i = 0, il = json.length; i < il; i++) {
  24445. const image = json[i];
  24446. const url = image.url;
  24447. if (Array.isArray(url)) {
  24448. // load array of images e.g CubeTexture
  24449. images[image.uuid] = [];
  24450. for (let j = 0, jl = url.length; j < jl; j++) {
  24451. const currentUrl = url[j];
  24452. const deserializedImage = await deserializeImage(currentUrl);
  24453. if (deserializedImage !== null) {
  24454. if (deserializedImage instanceof HTMLImageElement) {
  24455. images[image.uuid].push(deserializedImage);
  24456. } else {
  24457. // special case: handle array of data textures for cube textures
  24458. images[image.uuid].push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  24459. }
  24460. }
  24461. }
  24462. } else {
  24463. // load single image
  24464. const deserializedImage = await deserializeImage(image.url);
  24465. if (deserializedImage !== null) {
  24466. images[image.uuid] = deserializedImage;
  24467. }
  24468. }
  24469. }
  24470. }
  24471. return images;
  24472. }
  24473. parseTextures(json, images) {
  24474. function parseConstant(value, type) {
  24475. if (typeof value === 'number') return value;
  24476. console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
  24477. return type[value];
  24478. }
  24479. const textures = {};
  24480. if (json !== undefined) {
  24481. for (let i = 0, l = json.length; i < l; i++) {
  24482. const data = json[i];
  24483. if (data.image === undefined) {
  24484. console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
  24485. }
  24486. if (images[data.image] === undefined) {
  24487. console.warn('THREE.ObjectLoader: Undefined image', data.image);
  24488. }
  24489. let texture;
  24490. const image = images[data.image];
  24491. if (Array.isArray(image)) {
  24492. texture = new CubeTexture(image);
  24493. if (image.length === 6) texture.needsUpdate = true;
  24494. } else {
  24495. if (image && image.data) {
  24496. texture = new DataTexture(image.data, image.width, image.height);
  24497. } else {
  24498. texture = new Texture(image);
  24499. }
  24500. if (image) texture.needsUpdate = true; // textures can have undefined image data
  24501. }
  24502. texture.uuid = data.uuid;
  24503. if (data.name !== undefined) texture.name = data.name;
  24504. if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
  24505. if (data.offset !== undefined) texture.offset.fromArray(data.offset);
  24506. if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
  24507. if (data.center !== undefined) texture.center.fromArray(data.center);
  24508. if (data.rotation !== undefined) texture.rotation = data.rotation;
  24509. if (data.wrap !== undefined) {
  24510. texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
  24511. texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
  24512. }
  24513. if (data.format !== undefined) texture.format = data.format;
  24514. if (data.type !== undefined) texture.type = data.type;
  24515. if (data.encoding !== undefined) texture.encoding = data.encoding;
  24516. if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
  24517. if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
  24518. if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
  24519. if (data.flipY !== undefined) texture.flipY = data.flipY;
  24520. if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
  24521. if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
  24522. if (data.userData !== undefined) texture.userData = data.userData;
  24523. textures[data.uuid] = texture;
  24524. }
  24525. }
  24526. return textures;
  24527. }
  24528. parseObject(data, geometries, materials, textures, animations) {
  24529. let object;
  24530. function getGeometry(name) {
  24531. if (geometries[name] === undefined) {
  24532. console.warn('THREE.ObjectLoader: Undefined geometry', name);
  24533. }
  24534. return geometries[name];
  24535. }
  24536. function getMaterial(name) {
  24537. if (name === undefined) return undefined;
  24538. if (Array.isArray(name)) {
  24539. const array = [];
  24540. for (let i = 0, l = name.length; i < l; i++) {
  24541. const uuid = name[i];
  24542. if (materials[uuid] === undefined) {
  24543. console.warn('THREE.ObjectLoader: Undefined material', uuid);
  24544. }
  24545. array.push(materials[uuid]);
  24546. }
  24547. return array;
  24548. }
  24549. if (materials[name] === undefined) {
  24550. console.warn('THREE.ObjectLoader: Undefined material', name);
  24551. }
  24552. return materials[name];
  24553. }
  24554. function getTexture(uuid) {
  24555. if (textures[uuid] === undefined) {
  24556. console.warn('THREE.ObjectLoader: Undefined texture', uuid);
  24557. }
  24558. return textures[uuid];
  24559. }
  24560. let geometry, material;
  24561. switch (data.type) {
  24562. case 'Scene':
  24563. object = new Scene();
  24564. if (data.background !== undefined) {
  24565. if (Number.isInteger(data.background)) {
  24566. object.background = new Color(data.background);
  24567. } else {
  24568. object.background = getTexture(data.background);
  24569. }
  24570. }
  24571. if (data.environment !== undefined) {
  24572. object.environment = getTexture(data.environment);
  24573. }
  24574. if (data.fog !== undefined) {
  24575. if (data.fog.type === 'Fog') {
  24576. object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
  24577. } else if (data.fog.type === 'FogExp2') {
  24578. object.fog = new FogExp2(data.fog.color, data.fog.density);
  24579. }
  24580. }
  24581. break;
  24582. case 'PerspectiveCamera':
  24583. object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
  24584. if (data.focus !== undefined) object.focus = data.focus;
  24585. if (data.zoom !== undefined) object.zoom = data.zoom;
  24586. if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
  24587. if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
  24588. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24589. break;
  24590. case 'OrthographicCamera':
  24591. object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
  24592. if (data.zoom !== undefined) object.zoom = data.zoom;
  24593. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24594. break;
  24595. case 'AmbientLight':
  24596. object = new AmbientLight(data.color, data.intensity);
  24597. break;
  24598. case 'DirectionalLight':
  24599. object = new DirectionalLight(data.color, data.intensity);
  24600. break;
  24601. case 'PointLight':
  24602. object = new PointLight(data.color, data.intensity, data.distance, data.decay);
  24603. break;
  24604. case 'RectAreaLight':
  24605. object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
  24606. break;
  24607. case 'SpotLight':
  24608. object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
  24609. break;
  24610. case 'HemisphereLight':
  24611. object = new HemisphereLight(data.color, data.groundColor, data.intensity);
  24612. break;
  24613. case 'LightProbe':
  24614. object = new LightProbe().fromJSON(data);
  24615. break;
  24616. case 'SkinnedMesh':
  24617. geometry = getGeometry(data.geometry);
  24618. material = getMaterial(data.material);
  24619. object = new SkinnedMesh(geometry, material);
  24620. if (data.bindMode !== undefined) object.bindMode = data.bindMode;
  24621. if (data.bindMatrix !== undefined) object.bindMatrix.fromArray(data.bindMatrix);
  24622. if (data.skeleton !== undefined) object.skeleton = data.skeleton;
  24623. break;
  24624. case 'Mesh':
  24625. geometry = getGeometry(data.geometry);
  24626. material = getMaterial(data.material);
  24627. object = new Mesh(geometry, material);
  24628. break;
  24629. case 'InstancedMesh':
  24630. geometry = getGeometry(data.geometry);
  24631. material = getMaterial(data.material);
  24632. const count = data.count;
  24633. const instanceMatrix = data.instanceMatrix;
  24634. const instanceColor = data.instanceColor;
  24635. object = new InstancedMesh(geometry, material, count);
  24636. object.instanceMatrix = new InstancedBufferAttribute(new Float32Array(instanceMatrix.array), 16);
  24637. if (instanceColor !== undefined) object.instanceColor = new InstancedBufferAttribute(new Float32Array(instanceColor.array), instanceColor.itemSize);
  24638. break;
  24639. case 'LOD':
  24640. object = new LOD();
  24641. break;
  24642. case 'Line':
  24643. object = new Line(getGeometry(data.geometry), getMaterial(data.material));
  24644. break;
  24645. case 'LineLoop':
  24646. object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
  24647. break;
  24648. case 'LineSegments':
  24649. object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
  24650. break;
  24651. case 'PointCloud':
  24652. case 'Points':
  24653. object = new Points(getGeometry(data.geometry), getMaterial(data.material));
  24654. break;
  24655. case 'Sprite':
  24656. object = new Sprite(getMaterial(data.material));
  24657. break;
  24658. case 'Group':
  24659. object = new Group();
  24660. break;
  24661. case 'Bone':
  24662. object = new Bone();
  24663. break;
  24664. default:
  24665. object = new Object3D();
  24666. }
  24667. object.uuid = data.uuid;
  24668. if (data.name !== undefined) object.name = data.name;
  24669. if (data.matrix !== undefined) {
  24670. object.matrix.fromArray(data.matrix);
  24671. if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
  24672. if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
  24673. } else {
  24674. if (data.position !== undefined) object.position.fromArray(data.position);
  24675. if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
  24676. if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
  24677. if (data.scale !== undefined) object.scale.fromArray(data.scale);
  24678. }
  24679. if (data.castShadow !== undefined) object.castShadow = data.castShadow;
  24680. if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
  24681. if (data.shadow) {
  24682. if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
  24683. if (data.shadow.normalBias !== undefined) object.shadow.normalBias = data.shadow.normalBias;
  24684. if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
  24685. if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
  24686. if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
  24687. }
  24688. if (data.visible !== undefined) object.visible = data.visible;
  24689. if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
  24690. if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
  24691. if (data.userData !== undefined) object.userData = data.userData;
  24692. if (data.layers !== undefined) object.layers.mask = data.layers;
  24693. if (data.children !== undefined) {
  24694. const children = data.children;
  24695. for (let i = 0; i < children.length; i++) {
  24696. object.add(this.parseObject(children[i], geometries, materials, textures, animations));
  24697. }
  24698. }
  24699. if (data.animations !== undefined) {
  24700. const objectAnimations = data.animations;
  24701. for (let i = 0; i < objectAnimations.length; i++) {
  24702. const uuid = objectAnimations[i];
  24703. object.animations.push(animations[uuid]);
  24704. }
  24705. }
  24706. if (data.type === 'LOD') {
  24707. if (data.autoUpdate !== undefined) object.autoUpdate = data.autoUpdate;
  24708. const levels = data.levels;
  24709. for (let l = 0; l < levels.length; l++) {
  24710. const level = levels[l];
  24711. const child = object.getObjectByProperty('uuid', level.object);
  24712. if (child !== undefined) {
  24713. object.addLevel(child, level.distance);
  24714. }
  24715. }
  24716. }
  24717. return object;
  24718. }
  24719. bindSkeletons(object, skeletons) {
  24720. if (Object.keys(skeletons).length === 0) return;
  24721. object.traverse(function (child) {
  24722. if (child.isSkinnedMesh === true && child.skeleton !== undefined) {
  24723. const skeleton = skeletons[child.skeleton];
  24724. if (skeleton === undefined) {
  24725. console.warn('THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton);
  24726. } else {
  24727. child.bind(skeleton, child.bindMatrix);
  24728. }
  24729. }
  24730. });
  24731. }
  24732. /* DEPRECATED */
  24733. setTexturePath(value) {
  24734. console.warn('THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().');
  24735. return this.setResourcePath(value);
  24736. }
  24737. }
  24738. const TEXTURE_MAPPING = {
  24739. UVMapping: UVMapping,
  24740. CubeReflectionMapping: CubeReflectionMapping,
  24741. CubeRefractionMapping: CubeRefractionMapping,
  24742. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  24743. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  24744. CubeUVReflectionMapping: CubeUVReflectionMapping,
  24745. CubeUVRefractionMapping: CubeUVRefractionMapping
  24746. };
  24747. const TEXTURE_WRAPPING = {
  24748. RepeatWrapping: RepeatWrapping,
  24749. ClampToEdgeWrapping: ClampToEdgeWrapping,
  24750. MirroredRepeatWrapping: MirroredRepeatWrapping
  24751. };
  24752. const TEXTURE_FILTER = {
  24753. NearestFilter: NearestFilter,
  24754. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  24755. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  24756. LinearFilter: LinearFilter,
  24757. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  24758. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  24759. };
  24760. class ImageBitmapLoader extends Loader {
  24761. constructor(manager) {
  24762. super(manager);
  24763. if (typeof createImageBitmap === 'undefined') {
  24764. console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
  24765. }
  24766. if (typeof fetch === 'undefined') {
  24767. console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
  24768. }
  24769. this.options = {
  24770. premultiplyAlpha: 'none'
  24771. };
  24772. }
  24773. setOptions(options) {
  24774. this.options = options;
  24775. return this;
  24776. }
  24777. load(url, onLoad, onProgress, onError) {
  24778. if (url === undefined) url = '';
  24779. if (this.path !== undefined) url = this.path + url;
  24780. url = this.manager.resolveURL(url);
  24781. const scope = this;
  24782. const cached = Cache.get(url);
  24783. if (cached !== undefined) {
  24784. scope.manager.itemStart(url);
  24785. setTimeout(function () {
  24786. if (onLoad) onLoad(cached);
  24787. scope.manager.itemEnd(url);
  24788. }, 0);
  24789. return cached;
  24790. }
  24791. const fetchOptions = {};
  24792. fetchOptions.credentials = this.crossOrigin === 'anonymous' ? 'same-origin' : 'include';
  24793. fetchOptions.headers = this.requestHeader;
  24794. fetch(url, fetchOptions).then(function (res) {
  24795. return res.blob();
  24796. }).then(function (blob) {
  24797. return createImageBitmap(blob, Object.assign(scope.options, {
  24798. colorSpaceConversion: 'none'
  24799. }));
  24800. }).then(function (imageBitmap) {
  24801. Cache.add(url, imageBitmap);
  24802. if (onLoad) onLoad(imageBitmap);
  24803. scope.manager.itemEnd(url);
  24804. }).catch(function (e) {
  24805. if (onError) onError(e);
  24806. scope.manager.itemError(url);
  24807. scope.manager.itemEnd(url);
  24808. });
  24809. scope.manager.itemStart(url);
  24810. }
  24811. }
  24812. ImageBitmapLoader.prototype.isImageBitmapLoader = true;
  24813. let _context;
  24814. const AudioContext = {
  24815. getContext: function () {
  24816. if (_context === undefined) {
  24817. _context = new (window.AudioContext || window.webkitAudioContext)();
  24818. }
  24819. return _context;
  24820. },
  24821. setContext: function (value) {
  24822. _context = value;
  24823. }
  24824. };
  24825. class AudioLoader extends Loader {
  24826. constructor(manager) {
  24827. super(manager);
  24828. }
  24829. load(url, onLoad, onProgress, onError) {
  24830. const scope = this;
  24831. const loader = new FileLoader(this.manager);
  24832. loader.setResponseType('arraybuffer');
  24833. loader.setPath(this.path);
  24834. loader.setRequestHeader(this.requestHeader);
  24835. loader.setWithCredentials(this.withCredentials);
  24836. loader.load(url, function (buffer) {
  24837. try {
  24838. // Create a copy of the buffer. The `decodeAudioData` method
  24839. // detaches the buffer when complete, preventing reuse.
  24840. const bufferCopy = buffer.slice(0);
  24841. const context = AudioContext.getContext();
  24842. context.decodeAudioData(bufferCopy, function (audioBuffer) {
  24843. onLoad(audioBuffer);
  24844. });
  24845. } catch (e) {
  24846. if (onError) {
  24847. onError(e);
  24848. } else {
  24849. console.error(e);
  24850. }
  24851. scope.manager.itemError(url);
  24852. }
  24853. }, onProgress, onError);
  24854. }
  24855. }
  24856. class HemisphereLightProbe extends LightProbe {
  24857. constructor(skyColor, groundColor, intensity = 1) {
  24858. super(undefined, intensity);
  24859. const color1 = new Color().set(skyColor);
  24860. const color2 = new Color().set(groundColor);
  24861. const sky = new Vector3(color1.r, color1.g, color1.b);
  24862. const ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  24863. const c0 = Math.sqrt(Math.PI);
  24864. const c1 = c0 * Math.sqrt(0.75);
  24865. this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
  24866. this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
  24867. }
  24868. }
  24869. HemisphereLightProbe.prototype.isHemisphereLightProbe = true;
  24870. class AmbientLightProbe extends LightProbe {
  24871. constructor(color, intensity = 1) {
  24872. super(undefined, intensity);
  24873. const color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  24874. this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
  24875. }
  24876. }
  24877. AmbientLightProbe.prototype.isAmbientLightProbe = true;
  24878. const _eyeRight = /*@__PURE__*/new Matrix4();
  24879. const _eyeLeft = /*@__PURE__*/new Matrix4();
  24880. const _projectionMatrix = /*@__PURE__*/new Matrix4();
  24881. class StereoCamera {
  24882. constructor() {
  24883. this.type = 'StereoCamera';
  24884. this.aspect = 1;
  24885. this.eyeSep = 0.064;
  24886. this.cameraL = new PerspectiveCamera();
  24887. this.cameraL.layers.enable(1);
  24888. this.cameraL.matrixAutoUpdate = false;
  24889. this.cameraR = new PerspectiveCamera();
  24890. this.cameraR.layers.enable(2);
  24891. this.cameraR.matrixAutoUpdate = false;
  24892. this._cache = {
  24893. focus: null,
  24894. fov: null,
  24895. aspect: null,
  24896. near: null,
  24897. far: null,
  24898. zoom: null,
  24899. eyeSep: null
  24900. };
  24901. }
  24902. update(camera) {
  24903. const cache = this._cache;
  24904. 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;
  24905. if (needsUpdate) {
  24906. cache.focus = camera.focus;
  24907. cache.fov = camera.fov;
  24908. cache.aspect = camera.aspect * this.aspect;
  24909. cache.near = camera.near;
  24910. cache.far = camera.far;
  24911. cache.zoom = camera.zoom;
  24912. cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based on
  24913. // http://paulbourke.net/stereographics/stereorender/
  24914. _projectionMatrix.copy(camera.projectionMatrix);
  24915. const eyeSepHalf = cache.eyeSep / 2;
  24916. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  24917. const ymax = cache.near * Math.tan(DEG2RAD * cache.fov * 0.5) / cache.zoom;
  24918. let xmin, xmax; // translate xOffset
  24919. _eyeLeft.elements[12] = -eyeSepHalf;
  24920. _eyeRight.elements[12] = eyeSepHalf; // for left eye
  24921. xmin = -ymax * cache.aspect + eyeSepOnProjection;
  24922. xmax = ymax * cache.aspect + eyeSepOnProjection;
  24923. _projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  24924. _projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  24925. this.cameraL.projectionMatrix.copy(_projectionMatrix); // for right eye
  24926. xmin = -ymax * cache.aspect - eyeSepOnProjection;
  24927. xmax = ymax * cache.aspect - eyeSepOnProjection;
  24928. _projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  24929. _projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  24930. this.cameraR.projectionMatrix.copy(_projectionMatrix);
  24931. }
  24932. this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
  24933. this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
  24934. }
  24935. }
  24936. class Clock {
  24937. constructor(autoStart = true) {
  24938. this.autoStart = autoStart;
  24939. this.startTime = 0;
  24940. this.oldTime = 0;
  24941. this.elapsedTime = 0;
  24942. this.running = false;
  24943. }
  24944. start() {
  24945. this.startTime = now();
  24946. this.oldTime = this.startTime;
  24947. this.elapsedTime = 0;
  24948. this.running = true;
  24949. }
  24950. stop() {
  24951. this.getElapsedTime();
  24952. this.running = false;
  24953. this.autoStart = false;
  24954. }
  24955. getElapsedTime() {
  24956. this.getDelta();
  24957. return this.elapsedTime;
  24958. }
  24959. getDelta() {
  24960. let diff = 0;
  24961. if (this.autoStart && !this.running) {
  24962. this.start();
  24963. return 0;
  24964. }
  24965. if (this.running) {
  24966. const newTime = now();
  24967. diff = (newTime - this.oldTime) / 1000;
  24968. this.oldTime = newTime;
  24969. this.elapsedTime += diff;
  24970. }
  24971. return diff;
  24972. }
  24973. }
  24974. function now() {
  24975. return (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
  24976. }
  24977. const _position$1 = /*@__PURE__*/new Vector3();
  24978. const _quaternion$1 = /*@__PURE__*/new Quaternion();
  24979. const _scale$1 = /*@__PURE__*/new Vector3();
  24980. const _orientation$1 = /*@__PURE__*/new Vector3();
  24981. class AudioListener extends Object3D {
  24982. constructor() {
  24983. super();
  24984. this.type = 'AudioListener';
  24985. this.context = AudioContext.getContext();
  24986. this.gain = this.context.createGain();
  24987. this.gain.connect(this.context.destination);
  24988. this.filter = null;
  24989. this.timeDelta = 0; // private
  24990. this._clock = new Clock();
  24991. }
  24992. getInput() {
  24993. return this.gain;
  24994. }
  24995. removeFilter() {
  24996. if (this.filter !== null) {
  24997. this.gain.disconnect(this.filter);
  24998. this.filter.disconnect(this.context.destination);
  24999. this.gain.connect(this.context.destination);
  25000. this.filter = null;
  25001. }
  25002. return this;
  25003. }
  25004. getFilter() {
  25005. return this.filter;
  25006. }
  25007. setFilter(value) {
  25008. if (this.filter !== null) {
  25009. this.gain.disconnect(this.filter);
  25010. this.filter.disconnect(this.context.destination);
  25011. } else {
  25012. this.gain.disconnect(this.context.destination);
  25013. }
  25014. this.filter = value;
  25015. this.gain.connect(this.filter);
  25016. this.filter.connect(this.context.destination);
  25017. return this;
  25018. }
  25019. getMasterVolume() {
  25020. return this.gain.gain.value;
  25021. }
  25022. setMasterVolume(value) {
  25023. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  25024. return this;
  25025. }
  25026. updateMatrixWorld(force) {
  25027. super.updateMatrixWorld(force);
  25028. const listener = this.context.listener;
  25029. const up = this.up;
  25030. this.timeDelta = this._clock.getDelta();
  25031. this.matrixWorld.decompose(_position$1, _quaternion$1, _scale$1);
  25032. _orientation$1.set(0, 0, -1).applyQuaternion(_quaternion$1);
  25033. if (listener.positionX) {
  25034. // code path for Chrome (see #14393)
  25035. const endTime = this.context.currentTime + this.timeDelta;
  25036. listener.positionX.linearRampToValueAtTime(_position$1.x, endTime);
  25037. listener.positionY.linearRampToValueAtTime(_position$1.y, endTime);
  25038. listener.positionZ.linearRampToValueAtTime(_position$1.z, endTime);
  25039. listener.forwardX.linearRampToValueAtTime(_orientation$1.x, endTime);
  25040. listener.forwardY.linearRampToValueAtTime(_orientation$1.y, endTime);
  25041. listener.forwardZ.linearRampToValueAtTime(_orientation$1.z, endTime);
  25042. listener.upX.linearRampToValueAtTime(up.x, endTime);
  25043. listener.upY.linearRampToValueAtTime(up.y, endTime);
  25044. listener.upZ.linearRampToValueAtTime(up.z, endTime);
  25045. } else {
  25046. listener.setPosition(_position$1.x, _position$1.y, _position$1.z);
  25047. listener.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z);
  25048. }
  25049. }
  25050. }
  25051. class Audio extends Object3D {
  25052. constructor(listener) {
  25053. super();
  25054. this.type = 'Audio';
  25055. this.listener = listener;
  25056. this.context = listener.context;
  25057. this.gain = this.context.createGain();
  25058. this.gain.connect(listener.getInput());
  25059. this.autoplay = false;
  25060. this.buffer = null;
  25061. this.detune = 0;
  25062. this.loop = false;
  25063. this.loopStart = 0;
  25064. this.loopEnd = 0;
  25065. this.offset = 0;
  25066. this.duration = undefined;
  25067. this.playbackRate = 1;
  25068. this.isPlaying = false;
  25069. this.hasPlaybackControl = true;
  25070. this.source = null;
  25071. this.sourceType = 'empty';
  25072. this._startedAt = 0;
  25073. this._progress = 0;
  25074. this._connected = false;
  25075. this.filters = [];
  25076. }
  25077. getOutput() {
  25078. return this.gain;
  25079. }
  25080. setNodeSource(audioNode) {
  25081. this.hasPlaybackControl = false;
  25082. this.sourceType = 'audioNode';
  25083. this.source = audioNode;
  25084. this.connect();
  25085. return this;
  25086. }
  25087. setMediaElementSource(mediaElement) {
  25088. this.hasPlaybackControl = false;
  25089. this.sourceType = 'mediaNode';
  25090. this.source = this.context.createMediaElementSource(mediaElement);
  25091. this.connect();
  25092. return this;
  25093. }
  25094. setMediaStreamSource(mediaStream) {
  25095. this.hasPlaybackControl = false;
  25096. this.sourceType = 'mediaStreamNode';
  25097. this.source = this.context.createMediaStreamSource(mediaStream);
  25098. this.connect();
  25099. return this;
  25100. }
  25101. setBuffer(audioBuffer) {
  25102. this.buffer = audioBuffer;
  25103. this.sourceType = 'buffer';
  25104. if (this.autoplay) this.play();
  25105. return this;
  25106. }
  25107. play(delay = 0) {
  25108. if (this.isPlaying === true) {
  25109. console.warn('THREE.Audio: Audio is already playing.');
  25110. return;
  25111. }
  25112. if (this.hasPlaybackControl === false) {
  25113. console.warn('THREE.Audio: this Audio has no playback control.');
  25114. return;
  25115. }
  25116. this._startedAt = this.context.currentTime + delay;
  25117. const source = this.context.createBufferSource();
  25118. source.buffer = this.buffer;
  25119. source.loop = this.loop;
  25120. source.loopStart = this.loopStart;
  25121. source.loopEnd = this.loopEnd;
  25122. source.onended = this.onEnded.bind(this);
  25123. source.start(this._startedAt, this._progress + this.offset, this.duration);
  25124. this.isPlaying = true;
  25125. this.source = source;
  25126. this.setDetune(this.detune);
  25127. this.setPlaybackRate(this.playbackRate);
  25128. return this.connect();
  25129. }
  25130. pause() {
  25131. if (this.hasPlaybackControl === false) {
  25132. console.warn('THREE.Audio: this Audio has no playback control.');
  25133. return;
  25134. }
  25135. if (this.isPlaying === true) {
  25136. // update current progress
  25137. this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate;
  25138. if (this.loop === true) {
  25139. // ensure _progress does not exceed duration with looped audios
  25140. this._progress = this._progress % (this.duration || this.buffer.duration);
  25141. }
  25142. this.source.stop();
  25143. this.source.onended = null;
  25144. this.isPlaying = false;
  25145. }
  25146. return this;
  25147. }
  25148. stop() {
  25149. if (this.hasPlaybackControl === false) {
  25150. console.warn('THREE.Audio: this Audio has no playback control.');
  25151. return;
  25152. }
  25153. this._progress = 0;
  25154. this.source.stop();
  25155. this.source.onended = null;
  25156. this.isPlaying = false;
  25157. return this;
  25158. }
  25159. connect() {
  25160. if (this.filters.length > 0) {
  25161. this.source.connect(this.filters[0]);
  25162. for (let i = 1, l = this.filters.length; i < l; i++) {
  25163. this.filters[i - 1].connect(this.filters[i]);
  25164. }
  25165. this.filters[this.filters.length - 1].connect(this.getOutput());
  25166. } else {
  25167. this.source.connect(this.getOutput());
  25168. }
  25169. this._connected = true;
  25170. return this;
  25171. }
  25172. disconnect() {
  25173. if (this.filters.length > 0) {
  25174. this.source.disconnect(this.filters[0]);
  25175. for (let i = 1, l = this.filters.length; i < l; i++) {
  25176. this.filters[i - 1].disconnect(this.filters[i]);
  25177. }
  25178. this.filters[this.filters.length - 1].disconnect(this.getOutput());
  25179. } else {
  25180. this.source.disconnect(this.getOutput());
  25181. }
  25182. this._connected = false;
  25183. return this;
  25184. }
  25185. getFilters() {
  25186. return this.filters;
  25187. }
  25188. setFilters(value) {
  25189. if (!value) value = [];
  25190. if (this._connected === true) {
  25191. this.disconnect();
  25192. this.filters = value.slice();
  25193. this.connect();
  25194. } else {
  25195. this.filters = value.slice();
  25196. }
  25197. return this;
  25198. }
  25199. setDetune(value) {
  25200. this.detune = value;
  25201. if (this.source.detune === undefined) return; // only set detune when available
  25202. if (this.isPlaying === true) {
  25203. this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
  25204. }
  25205. return this;
  25206. }
  25207. getDetune() {
  25208. return this.detune;
  25209. }
  25210. getFilter() {
  25211. return this.getFilters()[0];
  25212. }
  25213. setFilter(filter) {
  25214. return this.setFilters(filter ? [filter] : []);
  25215. }
  25216. setPlaybackRate(value) {
  25217. if (this.hasPlaybackControl === false) {
  25218. console.warn('THREE.Audio: this Audio has no playback control.');
  25219. return;
  25220. }
  25221. this.playbackRate = value;
  25222. if (this.isPlaying === true) {
  25223. this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
  25224. }
  25225. return this;
  25226. }
  25227. getPlaybackRate() {
  25228. return this.playbackRate;
  25229. }
  25230. onEnded() {
  25231. this.isPlaying = false;
  25232. }
  25233. getLoop() {
  25234. if (this.hasPlaybackControl === false) {
  25235. console.warn('THREE.Audio: this Audio has no playback control.');
  25236. return false;
  25237. }
  25238. return this.loop;
  25239. }
  25240. setLoop(value) {
  25241. if (this.hasPlaybackControl === false) {
  25242. console.warn('THREE.Audio: this Audio has no playback control.');
  25243. return;
  25244. }
  25245. this.loop = value;
  25246. if (this.isPlaying === true) {
  25247. this.source.loop = this.loop;
  25248. }
  25249. return this;
  25250. }
  25251. setLoopStart(value) {
  25252. this.loopStart = value;
  25253. return this;
  25254. }
  25255. setLoopEnd(value) {
  25256. this.loopEnd = value;
  25257. return this;
  25258. }
  25259. getVolume() {
  25260. return this.gain.gain.value;
  25261. }
  25262. setVolume(value) {
  25263. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  25264. return this;
  25265. }
  25266. }
  25267. const _position = /*@__PURE__*/new Vector3();
  25268. const _quaternion = /*@__PURE__*/new Quaternion();
  25269. const _scale = /*@__PURE__*/new Vector3();
  25270. const _orientation = /*@__PURE__*/new Vector3();
  25271. class PositionalAudio extends Audio {
  25272. constructor(listener) {
  25273. super(listener);
  25274. this.panner = this.context.createPanner();
  25275. this.panner.panningModel = 'HRTF';
  25276. this.panner.connect(this.gain);
  25277. }
  25278. getOutput() {
  25279. return this.panner;
  25280. }
  25281. getRefDistance() {
  25282. return this.panner.refDistance;
  25283. }
  25284. setRefDistance(value) {
  25285. this.panner.refDistance = value;
  25286. return this;
  25287. }
  25288. getRolloffFactor() {
  25289. return this.panner.rolloffFactor;
  25290. }
  25291. setRolloffFactor(value) {
  25292. this.panner.rolloffFactor = value;
  25293. return this;
  25294. }
  25295. getDistanceModel() {
  25296. return this.panner.distanceModel;
  25297. }
  25298. setDistanceModel(value) {
  25299. this.panner.distanceModel = value;
  25300. return this;
  25301. }
  25302. getMaxDistance() {
  25303. return this.panner.maxDistance;
  25304. }
  25305. setMaxDistance(value) {
  25306. this.panner.maxDistance = value;
  25307. return this;
  25308. }
  25309. setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) {
  25310. this.panner.coneInnerAngle = coneInnerAngle;
  25311. this.panner.coneOuterAngle = coneOuterAngle;
  25312. this.panner.coneOuterGain = coneOuterGain;
  25313. return this;
  25314. }
  25315. updateMatrixWorld(force) {
  25316. super.updateMatrixWorld(force);
  25317. if (this.hasPlaybackControl === true && this.isPlaying === false) return;
  25318. this.matrixWorld.decompose(_position, _quaternion, _scale);
  25319. _orientation.set(0, 0, 1).applyQuaternion(_quaternion);
  25320. const panner = this.panner;
  25321. if (panner.positionX) {
  25322. // code path for Chrome and Firefox (see #14393)
  25323. const endTime = this.context.currentTime + this.listener.timeDelta;
  25324. panner.positionX.linearRampToValueAtTime(_position.x, endTime);
  25325. panner.positionY.linearRampToValueAtTime(_position.y, endTime);
  25326. panner.positionZ.linearRampToValueAtTime(_position.z, endTime);
  25327. panner.orientationX.linearRampToValueAtTime(_orientation.x, endTime);
  25328. panner.orientationY.linearRampToValueAtTime(_orientation.y, endTime);
  25329. panner.orientationZ.linearRampToValueAtTime(_orientation.z, endTime);
  25330. } else {
  25331. panner.setPosition(_position.x, _position.y, _position.z);
  25332. panner.setOrientation(_orientation.x, _orientation.y, _orientation.z);
  25333. }
  25334. }
  25335. }
  25336. class AudioAnalyser {
  25337. constructor(audio, fftSize = 2048) {
  25338. this.analyser = audio.context.createAnalyser();
  25339. this.analyser.fftSize = fftSize;
  25340. this.data = new Uint8Array(this.analyser.frequencyBinCount);
  25341. audio.getOutput().connect(this.analyser);
  25342. }
  25343. getFrequencyData() {
  25344. this.analyser.getByteFrequencyData(this.data);
  25345. return this.data;
  25346. }
  25347. getAverageFrequency() {
  25348. let value = 0;
  25349. const data = this.getFrequencyData();
  25350. for (let i = 0; i < data.length; i++) {
  25351. value += data[i];
  25352. }
  25353. return value / data.length;
  25354. }
  25355. }
  25356. class PropertyMixer {
  25357. constructor(binding, typeName, valueSize) {
  25358. this.binding = binding;
  25359. this.valueSize = valueSize;
  25360. let mixFunction, mixFunctionAdditive, setIdentity; // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  25361. //
  25362. // interpolators can use .buffer as their .result
  25363. // the data then goes to 'incoming'
  25364. //
  25365. // 'accu0' and 'accu1' are used frame-interleaved for
  25366. // the cumulative result and are compared to detect
  25367. // changes
  25368. //
  25369. // 'orig' stores the original state of the property
  25370. //
  25371. // 'add' is used for additive cumulative results
  25372. //
  25373. // 'work' is optional and is only present for quaternion types. It is used
  25374. // to store intermediate quaternion multiplication results
  25375. switch (typeName) {
  25376. case 'quaternion':
  25377. mixFunction = this._slerp;
  25378. mixFunctionAdditive = this._slerpAdditive;
  25379. setIdentity = this._setAdditiveIdentityQuaternion;
  25380. this.buffer = new Float64Array(valueSize * 6);
  25381. this._workIndex = 5;
  25382. break;
  25383. case 'string':
  25384. case 'bool':
  25385. mixFunction = this._select; // Use the regular mix function and for additive on these types,
  25386. // additive is not relevant for non-numeric types
  25387. mixFunctionAdditive = this._select;
  25388. setIdentity = this._setAdditiveIdentityOther;
  25389. this.buffer = new Array(valueSize * 5);
  25390. break;
  25391. default:
  25392. mixFunction = this._lerp;
  25393. mixFunctionAdditive = this._lerpAdditive;
  25394. setIdentity = this._setAdditiveIdentityNumeric;
  25395. this.buffer = new Float64Array(valueSize * 5);
  25396. }
  25397. this._mixBufferRegion = mixFunction;
  25398. this._mixBufferRegionAdditive = mixFunctionAdditive;
  25399. this._setIdentity = setIdentity;
  25400. this._origIndex = 3;
  25401. this._addIndex = 4;
  25402. this.cumulativeWeight = 0;
  25403. this.cumulativeWeightAdditive = 0;
  25404. this.useCount = 0;
  25405. this.referenceCount = 0;
  25406. } // accumulate data in the 'incoming' region into 'accu<i>'
  25407. accumulate(accuIndex, weight) {
  25408. // note: happily accumulating nothing when weight = 0, the caller knows
  25409. // the weight and shouldn't have made the call in the first place
  25410. const buffer = this.buffer,
  25411. stride = this.valueSize,
  25412. offset = accuIndex * stride + stride;
  25413. let currentWeight = this.cumulativeWeight;
  25414. if (currentWeight === 0) {
  25415. // accuN := incoming * weight
  25416. for (let i = 0; i !== stride; ++i) {
  25417. buffer[offset + i] = buffer[i];
  25418. }
  25419. currentWeight = weight;
  25420. } else {
  25421. // accuN := accuN + incoming * weight
  25422. currentWeight += weight;
  25423. const mix = weight / currentWeight;
  25424. this._mixBufferRegion(buffer, offset, 0, mix, stride);
  25425. }
  25426. this.cumulativeWeight = currentWeight;
  25427. } // accumulate data in the 'incoming' region into 'add'
  25428. accumulateAdditive(weight) {
  25429. const buffer = this.buffer,
  25430. stride = this.valueSize,
  25431. offset = stride * this._addIndex;
  25432. if (this.cumulativeWeightAdditive === 0) {
  25433. // add = identity
  25434. this._setIdentity();
  25435. } // add := add + incoming * weight
  25436. this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride);
  25437. this.cumulativeWeightAdditive += weight;
  25438. } // apply the state of 'accu<i>' to the binding when accus differ
  25439. apply(accuIndex) {
  25440. const stride = this.valueSize,
  25441. buffer = this.buffer,
  25442. offset = accuIndex * stride + stride,
  25443. weight = this.cumulativeWeight,
  25444. weightAdditive = this.cumulativeWeightAdditive,
  25445. binding = this.binding;
  25446. this.cumulativeWeight = 0;
  25447. this.cumulativeWeightAdditive = 0;
  25448. if (weight < 1) {
  25449. // accuN := accuN + original * ( 1 - cumulativeWeight )
  25450. const originalValueOffset = stride * this._origIndex;
  25451. this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
  25452. }
  25453. if (weightAdditive > 0) {
  25454. // accuN := accuN + additive accuN
  25455. this._mixBufferRegionAdditive(buffer, offset, this._addIndex * stride, 1, stride);
  25456. }
  25457. for (let i = stride, e = stride + stride; i !== e; ++i) {
  25458. if (buffer[i] !== buffer[i + stride]) {
  25459. // value has changed -> update scene graph
  25460. binding.setValue(buffer, offset);
  25461. break;
  25462. }
  25463. }
  25464. } // remember the state of the bound property and copy it to both accus
  25465. saveOriginalState() {
  25466. const binding = this.binding;
  25467. const buffer = this.buffer,
  25468. stride = this.valueSize,
  25469. originalValueOffset = stride * this._origIndex;
  25470. binding.getValue(buffer, originalValueOffset); // accu[0..1] := orig -- initially detect changes against the original
  25471. for (let i = stride, e = originalValueOffset; i !== e; ++i) {
  25472. buffer[i] = buffer[originalValueOffset + i % stride];
  25473. } // Add to identity for additive
  25474. this._setIdentity();
  25475. this.cumulativeWeight = 0;
  25476. this.cumulativeWeightAdditive = 0;
  25477. } // apply the state previously taken via 'saveOriginalState' to the binding
  25478. restoreOriginalState() {
  25479. const originalValueOffset = this.valueSize * 3;
  25480. this.binding.setValue(this.buffer, originalValueOffset);
  25481. }
  25482. _setAdditiveIdentityNumeric() {
  25483. const startIndex = this._addIndex * this.valueSize;
  25484. const endIndex = startIndex + this.valueSize;
  25485. for (let i = startIndex; i < endIndex; i++) {
  25486. this.buffer[i] = 0;
  25487. }
  25488. }
  25489. _setAdditiveIdentityQuaternion() {
  25490. this._setAdditiveIdentityNumeric();
  25491. this.buffer[this._addIndex * this.valueSize + 3] = 1;
  25492. }
  25493. _setAdditiveIdentityOther() {
  25494. const startIndex = this._origIndex * this.valueSize;
  25495. const targetIndex = this._addIndex * this.valueSize;
  25496. for (let i = 0; i < this.valueSize; i++) {
  25497. this.buffer[targetIndex + i] = this.buffer[startIndex + i];
  25498. }
  25499. } // mix functions
  25500. _select(buffer, dstOffset, srcOffset, t, stride) {
  25501. if (t >= 0.5) {
  25502. for (let i = 0; i !== stride; ++i) {
  25503. buffer[dstOffset + i] = buffer[srcOffset + i];
  25504. }
  25505. }
  25506. }
  25507. _slerp(buffer, dstOffset, srcOffset, t) {
  25508. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
  25509. }
  25510. _slerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  25511. const workOffset = this._workIndex * stride; // Store result in intermediate buffer offset
  25512. Quaternion.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset); // Slerp to the intermediate result
  25513. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t);
  25514. }
  25515. _lerp(buffer, dstOffset, srcOffset, t, stride) {
  25516. const s = 1 - t;
  25517. for (let i = 0; i !== stride; ++i) {
  25518. const j = dstOffset + i;
  25519. buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
  25520. }
  25521. }
  25522. _lerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  25523. for (let i = 0; i !== stride; ++i) {
  25524. const j = dstOffset + i;
  25525. buffer[j] = buffer[j] + buffer[srcOffset + i] * t;
  25526. }
  25527. }
  25528. }
  25529. // Characters [].:/ are reserved for track binding syntax.
  25530. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  25531. const _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matches
  25532. // only latin characters, and the unicode \p{L} is not yet supported. So
  25533. // instead, we exclude reserved characters and match everything else.
  25534. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  25535. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must
  25536. // be matched to parse the rest of the track name.
  25537. const _directoryRe = /((?:WC+[\/:])*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  25538. const _nodeRe = /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object on target node, and accessor. May not contain reserved
  25539. // characters. Accessor may contain any character except closing bracket.
  25540. const _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor may
  25541. // contain any non-bracket characters.
  25542. const _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
  25543. const _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
  25544. const _supportedObjectNames = ['material', 'materials', 'bones'];
  25545. class Composite {
  25546. constructor(targetGroup, path, optionalParsedPath) {
  25547. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
  25548. this._targetGroup = targetGroup;
  25549. this._bindings = targetGroup.subscribe_(path, parsedPath);
  25550. }
  25551. getValue(array, offset) {
  25552. this.bind(); // bind all binding
  25553. const firstValidIndex = this._targetGroup.nCachedObjects_,
  25554. binding = this._bindings[firstValidIndex]; // and only call .getValue on the first
  25555. if (binding !== undefined) binding.getValue(array, offset);
  25556. }
  25557. setValue(array, offset) {
  25558. const bindings = this._bindings;
  25559. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25560. bindings[i].setValue(array, offset);
  25561. }
  25562. }
  25563. bind() {
  25564. const bindings = this._bindings;
  25565. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25566. bindings[i].bind();
  25567. }
  25568. }
  25569. unbind() {
  25570. const bindings = this._bindings;
  25571. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25572. bindings[i].unbind();
  25573. }
  25574. }
  25575. } // Note: This class uses a State pattern on a per-method basis:
  25576. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  25577. // prototype version of these methods with one that represents
  25578. // the bound state. When the property is not found, the methods
  25579. // become no-ops.
  25580. class PropertyBinding {
  25581. constructor(rootNode, path, parsedPath) {
  25582. this.path = path;
  25583. this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
  25584. this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
  25585. this.rootNode = rootNode; // initial state of these methods that calls 'bind'
  25586. this.getValue = this._getValue_unbound;
  25587. this.setValue = this._setValue_unbound;
  25588. }
  25589. static create(root, path, parsedPath) {
  25590. if (!(root && root.isAnimationObjectGroup)) {
  25591. return new PropertyBinding(root, path, parsedPath);
  25592. } else {
  25593. return new PropertyBinding.Composite(root, path, parsedPath);
  25594. }
  25595. }
  25596. /**
  25597. * Replaces spaces with underscores and removes unsupported characters from
  25598. * node names, to ensure compatibility with parseTrackName().
  25599. *
  25600. * @param {string} name Node name to be sanitized.
  25601. * @return {string}
  25602. */
  25603. static sanitizeNodeName(name) {
  25604. return name.replace(/\s/g, '_').replace(_reservedRe, '');
  25605. }
  25606. static parseTrackName(trackName) {
  25607. const matches = _trackRe.exec(trackName);
  25608. if (!matches) {
  25609. throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
  25610. }
  25611. const results = {
  25612. // directoryName: matches[ 1 ], // (tschw) currently unused
  25613. nodeName: matches[2],
  25614. objectName: matches[3],
  25615. objectIndex: matches[4],
  25616. propertyName: matches[5],
  25617. // required
  25618. propertyIndex: matches[6]
  25619. };
  25620. const lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
  25621. if (lastDot !== undefined && lastDot !== -1) {
  25622. const objectName = results.nodeName.substring(lastDot + 1); // Object names must be checked against an allowlist. Otherwise, there
  25623. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  25624. // 'bar' could be the objectName, or part of a nodeName (which can
  25625. // include '.' characters).
  25626. if (_supportedObjectNames.indexOf(objectName) !== -1) {
  25627. results.nodeName = results.nodeName.substring(0, lastDot);
  25628. results.objectName = objectName;
  25629. }
  25630. }
  25631. if (results.propertyName === null || results.propertyName.length === 0) {
  25632. throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
  25633. }
  25634. return results;
  25635. }
  25636. static findNode(root, nodeName) {
  25637. if (!nodeName || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
  25638. return root;
  25639. } // search into skeleton bones.
  25640. if (root.skeleton) {
  25641. const bone = root.skeleton.getBoneByName(nodeName);
  25642. if (bone !== undefined) {
  25643. return bone;
  25644. }
  25645. } // search into node subtree.
  25646. if (root.children) {
  25647. const searchNodeSubtree = function (children) {
  25648. for (let i = 0; i < children.length; i++) {
  25649. const childNode = children[i];
  25650. if (childNode.name === nodeName || childNode.uuid === nodeName) {
  25651. return childNode;
  25652. }
  25653. const result = searchNodeSubtree(childNode.children);
  25654. if (result) return result;
  25655. }
  25656. return null;
  25657. };
  25658. const subTreeNode = searchNodeSubtree(root.children);
  25659. if (subTreeNode) {
  25660. return subTreeNode;
  25661. }
  25662. }
  25663. return null;
  25664. } // these are used to "bind" a nonexistent property
  25665. _getValue_unavailable() {}
  25666. _setValue_unavailable() {} // Getters
  25667. _getValue_direct(buffer, offset) {
  25668. buffer[offset] = this.targetObject[this.propertyName];
  25669. }
  25670. _getValue_array(buffer, offset) {
  25671. const source = this.resolvedProperty;
  25672. for (let i = 0, n = source.length; i !== n; ++i) {
  25673. buffer[offset++] = source[i];
  25674. }
  25675. }
  25676. _getValue_arrayElement(buffer, offset) {
  25677. buffer[offset] = this.resolvedProperty[this.propertyIndex];
  25678. }
  25679. _getValue_toArray(buffer, offset) {
  25680. this.resolvedProperty.toArray(buffer, offset);
  25681. } // Direct
  25682. _setValue_direct(buffer, offset) {
  25683. this.targetObject[this.propertyName] = buffer[offset];
  25684. }
  25685. _setValue_direct_setNeedsUpdate(buffer, offset) {
  25686. this.targetObject[this.propertyName] = buffer[offset];
  25687. this.targetObject.needsUpdate = true;
  25688. }
  25689. _setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
  25690. this.targetObject[this.propertyName] = buffer[offset];
  25691. this.targetObject.matrixWorldNeedsUpdate = true;
  25692. } // EntireArray
  25693. _setValue_array(buffer, offset) {
  25694. const dest = this.resolvedProperty;
  25695. for (let i = 0, n = dest.length; i !== n; ++i) {
  25696. dest[i] = buffer[offset++];
  25697. }
  25698. }
  25699. _setValue_array_setNeedsUpdate(buffer, offset) {
  25700. const dest = this.resolvedProperty;
  25701. for (let i = 0, n = dest.length; i !== n; ++i) {
  25702. dest[i] = buffer[offset++];
  25703. }
  25704. this.targetObject.needsUpdate = true;
  25705. }
  25706. _setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
  25707. const dest = this.resolvedProperty;
  25708. for (let i = 0, n = dest.length; i !== n; ++i) {
  25709. dest[i] = buffer[offset++];
  25710. }
  25711. this.targetObject.matrixWorldNeedsUpdate = true;
  25712. } // ArrayElement
  25713. _setValue_arrayElement(buffer, offset) {
  25714. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25715. }
  25716. _setValue_arrayElement_setNeedsUpdate(buffer, offset) {
  25717. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25718. this.targetObject.needsUpdate = true;
  25719. }
  25720. _setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
  25721. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25722. this.targetObject.matrixWorldNeedsUpdate = true;
  25723. } // HasToFromArray
  25724. _setValue_fromArray(buffer, offset) {
  25725. this.resolvedProperty.fromArray(buffer, offset);
  25726. }
  25727. _setValue_fromArray_setNeedsUpdate(buffer, offset) {
  25728. this.resolvedProperty.fromArray(buffer, offset);
  25729. this.targetObject.needsUpdate = true;
  25730. }
  25731. _setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
  25732. this.resolvedProperty.fromArray(buffer, offset);
  25733. this.targetObject.matrixWorldNeedsUpdate = true;
  25734. }
  25735. _getValue_unbound(targetArray, offset) {
  25736. this.bind();
  25737. this.getValue(targetArray, offset);
  25738. }
  25739. _setValue_unbound(sourceArray, offset) {
  25740. this.bind();
  25741. this.setValue(sourceArray, offset);
  25742. } // create getter / setter pair for a property in the scene graph
  25743. bind() {
  25744. let targetObject = this.node;
  25745. const parsedPath = this.parsedPath;
  25746. const objectName = parsedPath.objectName;
  25747. const propertyName = parsedPath.propertyName;
  25748. let propertyIndex = parsedPath.propertyIndex;
  25749. if (!targetObject) {
  25750. targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
  25751. this.node = targetObject;
  25752. } // set fail state so we can just 'return' on error
  25753. this.getValue = this._getValue_unavailable;
  25754. this.setValue = this._setValue_unavailable; // ensure there is a value node
  25755. if (!targetObject) {
  25756. console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
  25757. return;
  25758. }
  25759. if (objectName) {
  25760. let objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials....
  25761. switch (objectName) {
  25762. case 'materials':
  25763. if (!targetObject.material) {
  25764. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  25765. return;
  25766. }
  25767. if (!targetObject.material.materials) {
  25768. console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
  25769. return;
  25770. }
  25771. targetObject = targetObject.material.materials;
  25772. break;
  25773. case 'bones':
  25774. if (!targetObject.skeleton) {
  25775. console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
  25776. return;
  25777. } // potential future optimization: skip this if propertyIndex is already an integer
  25778. // and convert the integer string to a true integer.
  25779. targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.
  25780. for (let i = 0; i < targetObject.length; i++) {
  25781. if (targetObject[i].name === objectIndex) {
  25782. objectIndex = i;
  25783. break;
  25784. }
  25785. }
  25786. break;
  25787. default:
  25788. if (targetObject[objectName] === undefined) {
  25789. console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
  25790. return;
  25791. }
  25792. targetObject = targetObject[objectName];
  25793. }
  25794. if (objectIndex !== undefined) {
  25795. if (targetObject[objectIndex] === undefined) {
  25796. console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
  25797. return;
  25798. }
  25799. targetObject = targetObject[objectIndex];
  25800. }
  25801. } // resolve property
  25802. const nodeProperty = targetObject[propertyName];
  25803. if (nodeProperty === undefined) {
  25804. const nodeName = parsedPath.nodeName;
  25805. console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
  25806. return;
  25807. } // determine versioning scheme
  25808. let versioning = this.Versioning.None;
  25809. this.targetObject = targetObject;
  25810. if (targetObject.needsUpdate !== undefined) {
  25811. // material
  25812. versioning = this.Versioning.NeedsUpdate;
  25813. } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
  25814. // node transform
  25815. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  25816. } // determine how the property gets bound
  25817. let bindingType = this.BindingType.Direct;
  25818. if (propertyIndex !== undefined) {
  25819. // access a sub element of the property array (only primitives are supported right now)
  25820. if (propertyName === 'morphTargetInfluences') {
  25821. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  25822. // support resolving morphTarget names into indices.
  25823. if (!targetObject.geometry) {
  25824. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
  25825. return;
  25826. }
  25827. if (targetObject.geometry.isBufferGeometry) {
  25828. if (!targetObject.geometry.morphAttributes) {
  25829. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
  25830. return;
  25831. }
  25832. if (targetObject.morphTargetDictionary[propertyIndex] !== undefined) {
  25833. propertyIndex = targetObject.morphTargetDictionary[propertyIndex];
  25834. }
  25835. } else {
  25836. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this);
  25837. return;
  25838. }
  25839. }
  25840. bindingType = this.BindingType.ArrayElement;
  25841. this.resolvedProperty = nodeProperty;
  25842. this.propertyIndex = propertyIndex;
  25843. } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
  25844. // must use copy for Object3D.Euler/Quaternion
  25845. bindingType = this.BindingType.HasFromToArray;
  25846. this.resolvedProperty = nodeProperty;
  25847. } else if (Array.isArray(nodeProperty)) {
  25848. bindingType = this.BindingType.EntireArray;
  25849. this.resolvedProperty = nodeProperty;
  25850. } else {
  25851. this.propertyName = propertyName;
  25852. } // select getter / setter
  25853. this.getValue = this.GetterByBindingType[bindingType];
  25854. this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  25855. }
  25856. unbind() {
  25857. this.node = null; // back to the prototype version of getValue / setValue
  25858. // note: avoiding to mutate the shape of 'this' via 'delete'
  25859. this.getValue = this._getValue_unbound;
  25860. this.setValue = this._setValue_unbound;
  25861. }
  25862. }
  25863. PropertyBinding.Composite = Composite;
  25864. PropertyBinding.prototype.BindingType = {
  25865. Direct: 0,
  25866. EntireArray: 1,
  25867. ArrayElement: 2,
  25868. HasFromToArray: 3
  25869. };
  25870. PropertyBinding.prototype.Versioning = {
  25871. None: 0,
  25872. NeedsUpdate: 1,
  25873. MatrixWorldNeedsUpdate: 2
  25874. };
  25875. PropertyBinding.prototype.GetterByBindingType = [PropertyBinding.prototype._getValue_direct, PropertyBinding.prototype._getValue_array, PropertyBinding.prototype._getValue_arrayElement, PropertyBinding.prototype._getValue_toArray];
  25876. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [[// Direct
  25877. PropertyBinding.prototype._setValue_direct, PropertyBinding.prototype._setValue_direct_setNeedsUpdate, PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate], [// EntireArray
  25878. PropertyBinding.prototype._setValue_array, PropertyBinding.prototype._setValue_array_setNeedsUpdate, PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate], [// ArrayElement
  25879. PropertyBinding.prototype._setValue_arrayElement, PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate, PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate], [// HasToFromArray
  25880. PropertyBinding.prototype._setValue_fromArray, PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate, PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];
  25881. /**
  25882. *
  25883. * A group of objects that receives a shared animation state.
  25884. *
  25885. * Usage:
  25886. *
  25887. * - Add objects you would otherwise pass as 'root' to the
  25888. * constructor or the .clipAction method of AnimationMixer.
  25889. *
  25890. * - Instead pass this object as 'root'.
  25891. *
  25892. * - You can also add and remove objects later when the mixer
  25893. * is running.
  25894. *
  25895. * Note:
  25896. *
  25897. * Objects of this class appear as one object to the mixer,
  25898. * so cache control of the individual objects must be done
  25899. * on the group.
  25900. *
  25901. * Limitation:
  25902. *
  25903. * - The animated properties must be compatible among the
  25904. * all objects in the group.
  25905. *
  25906. * - A single property can either be controlled through a
  25907. * target group or directly, but not both.
  25908. */
  25909. class AnimationObjectGroup {
  25910. constructor() {
  25911. this.uuid = generateUUID(); // cached objects followed by the active ones
  25912. this._objects = Array.prototype.slice.call(arguments);
  25913. this.nCachedObjects_ = 0; // threshold
  25914. // note: read by PropertyBinding.Composite
  25915. const indices = {};
  25916. this._indicesByUUID = indices; // for bookkeeping
  25917. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25918. indices[arguments[i].uuid] = i;
  25919. }
  25920. this._paths = []; // inside: string
  25921. this._parsedPaths = []; // inside: { we don't care, here }
  25922. this._bindings = []; // inside: Array< PropertyBinding >
  25923. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  25924. const scope = this;
  25925. this.stats = {
  25926. objects: {
  25927. get total() {
  25928. return scope._objects.length;
  25929. },
  25930. get inUse() {
  25931. return this.total - scope.nCachedObjects_;
  25932. }
  25933. },
  25934. get bindingsPerObject() {
  25935. return scope._bindings.length;
  25936. }
  25937. };
  25938. }
  25939. add() {
  25940. const objects = this._objects,
  25941. indicesByUUID = this._indicesByUUID,
  25942. paths = this._paths,
  25943. parsedPaths = this._parsedPaths,
  25944. bindings = this._bindings,
  25945. nBindings = bindings.length;
  25946. let knownObject = undefined,
  25947. nObjects = objects.length,
  25948. nCachedObjects = this.nCachedObjects_;
  25949. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25950. const object = arguments[i],
  25951. uuid = object.uuid;
  25952. let index = indicesByUUID[uuid];
  25953. if (index === undefined) {
  25954. // unknown object -> add it to the ACTIVE region
  25955. index = nObjects++;
  25956. indicesByUUID[uuid] = index;
  25957. objects.push(object); // accounting is done, now do the same for all bindings
  25958. for (let j = 0, m = nBindings; j !== m; ++j) {
  25959. bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
  25960. }
  25961. } else if (index < nCachedObjects) {
  25962. knownObject = objects[index]; // move existing object to the ACTIVE region
  25963. const firstActiveIndex = --nCachedObjects,
  25964. lastCachedObject = objects[firstActiveIndex];
  25965. indicesByUUID[lastCachedObject.uuid] = index;
  25966. objects[index] = lastCachedObject;
  25967. indicesByUUID[uuid] = firstActiveIndex;
  25968. objects[firstActiveIndex] = object; // accounting is done, now do the same for all bindings
  25969. for (let j = 0, m = nBindings; j !== m; ++j) {
  25970. const bindingsForPath = bindings[j],
  25971. lastCached = bindingsForPath[firstActiveIndex];
  25972. let binding = bindingsForPath[index];
  25973. bindingsForPath[index] = lastCached;
  25974. if (binding === undefined) {
  25975. // since we do not bother to create new bindings
  25976. // for objects that are cached, the binding may
  25977. // or may not exist
  25978. binding = new PropertyBinding(object, paths[j], parsedPaths[j]);
  25979. }
  25980. bindingsForPath[firstActiveIndex] = binding;
  25981. }
  25982. } else if (objects[index] !== knownObject) {
  25983. console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
  25984. } // else the object is already where we want it to be
  25985. } // for arguments
  25986. this.nCachedObjects_ = nCachedObjects;
  25987. }
  25988. remove() {
  25989. const objects = this._objects,
  25990. indicesByUUID = this._indicesByUUID,
  25991. bindings = this._bindings,
  25992. nBindings = bindings.length;
  25993. let nCachedObjects = this.nCachedObjects_;
  25994. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25995. const object = arguments[i],
  25996. uuid = object.uuid,
  25997. index = indicesByUUID[uuid];
  25998. if (index !== undefined && index >= nCachedObjects) {
  25999. // move existing object into the CACHED region
  26000. const lastCachedIndex = nCachedObjects++,
  26001. firstActiveObject = objects[lastCachedIndex];
  26002. indicesByUUID[firstActiveObject.uuid] = index;
  26003. objects[index] = firstActiveObject;
  26004. indicesByUUID[uuid] = lastCachedIndex;
  26005. objects[lastCachedIndex] = object; // accounting is done, now do the same for all bindings
  26006. for (let j = 0, m = nBindings; j !== m; ++j) {
  26007. const bindingsForPath = bindings[j],
  26008. firstActive = bindingsForPath[lastCachedIndex],
  26009. binding = bindingsForPath[index];
  26010. bindingsForPath[index] = firstActive;
  26011. bindingsForPath[lastCachedIndex] = binding;
  26012. }
  26013. }
  26014. } // for arguments
  26015. this.nCachedObjects_ = nCachedObjects;
  26016. } // remove & forget
  26017. uncache() {
  26018. const objects = this._objects,
  26019. indicesByUUID = this._indicesByUUID,
  26020. bindings = this._bindings,
  26021. nBindings = bindings.length;
  26022. let nCachedObjects = this.nCachedObjects_,
  26023. nObjects = objects.length;
  26024. for (let i = 0, n = arguments.length; i !== n; ++i) {
  26025. const object = arguments[i],
  26026. uuid = object.uuid,
  26027. index = indicesByUUID[uuid];
  26028. if (index !== undefined) {
  26029. delete indicesByUUID[uuid];
  26030. if (index < nCachedObjects) {
  26031. // object is cached, shrink the CACHED region
  26032. const firstActiveIndex = --nCachedObjects,
  26033. lastCachedObject = objects[firstActiveIndex],
  26034. lastIndex = --nObjects,
  26035. lastObject = objects[lastIndex]; // last cached object takes this object's place
  26036. indicesByUUID[lastCachedObject.uuid] = index;
  26037. objects[index] = lastCachedObject; // last object goes to the activated slot and pop
  26038. indicesByUUID[lastObject.uuid] = firstActiveIndex;
  26039. objects[firstActiveIndex] = lastObject;
  26040. objects.pop(); // accounting is done, now do the same for all bindings
  26041. for (let j = 0, m = nBindings; j !== m; ++j) {
  26042. const bindingsForPath = bindings[j],
  26043. lastCached = bindingsForPath[firstActiveIndex],
  26044. last = bindingsForPath[lastIndex];
  26045. bindingsForPath[index] = lastCached;
  26046. bindingsForPath[firstActiveIndex] = last;
  26047. bindingsForPath.pop();
  26048. }
  26049. } else {
  26050. // object is active, just swap with the last and pop
  26051. const lastIndex = --nObjects,
  26052. lastObject = objects[lastIndex];
  26053. if (lastIndex > 0) {
  26054. indicesByUUID[lastObject.uuid] = index;
  26055. }
  26056. objects[index] = lastObject;
  26057. objects.pop(); // accounting is done, now do the same for all bindings
  26058. for (let j = 0, m = nBindings; j !== m; ++j) {
  26059. const bindingsForPath = bindings[j];
  26060. bindingsForPath[index] = bindingsForPath[lastIndex];
  26061. bindingsForPath.pop();
  26062. }
  26063. } // cached or active
  26064. } // if object is known
  26065. } // for arguments
  26066. this.nCachedObjects_ = nCachedObjects;
  26067. } // Internal interface used by befriended PropertyBinding.Composite:
  26068. subscribe_(path, parsedPath) {
  26069. // returns an array of bindings for the given path that is changed
  26070. // according to the contained objects in the group
  26071. const indicesByPath = this._bindingsIndicesByPath;
  26072. let index = indicesByPath[path];
  26073. const bindings = this._bindings;
  26074. if (index !== undefined) return bindings[index];
  26075. const paths = this._paths,
  26076. parsedPaths = this._parsedPaths,
  26077. objects = this._objects,
  26078. nObjects = objects.length,
  26079. nCachedObjects = this.nCachedObjects_,
  26080. bindingsForPath = new Array(nObjects);
  26081. index = bindings.length;
  26082. indicesByPath[path] = index;
  26083. paths.push(path);
  26084. parsedPaths.push(parsedPath);
  26085. bindings.push(bindingsForPath);
  26086. for (let i = nCachedObjects, n = objects.length; i !== n; ++i) {
  26087. const object = objects[i];
  26088. bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
  26089. }
  26090. return bindingsForPath;
  26091. }
  26092. unsubscribe_(path) {
  26093. // tells the group to forget about a property path and no longer
  26094. // update the array previously obtained with 'subscribe_'
  26095. const indicesByPath = this._bindingsIndicesByPath,
  26096. index = indicesByPath[path];
  26097. if (index !== undefined) {
  26098. const paths = this._paths,
  26099. parsedPaths = this._parsedPaths,
  26100. bindings = this._bindings,
  26101. lastBindingsIndex = bindings.length - 1,
  26102. lastBindings = bindings[lastBindingsIndex],
  26103. lastBindingsPath = path[lastBindingsIndex];
  26104. indicesByPath[lastBindingsPath] = index;
  26105. bindings[index] = lastBindings;
  26106. bindings.pop();
  26107. parsedPaths[index] = parsedPaths[lastBindingsIndex];
  26108. parsedPaths.pop();
  26109. paths[index] = paths[lastBindingsIndex];
  26110. paths.pop();
  26111. }
  26112. }
  26113. }
  26114. AnimationObjectGroup.prototype.isAnimationObjectGroup = true;
  26115. class AnimationAction {
  26116. constructor(mixer, clip, localRoot = null, blendMode = clip.blendMode) {
  26117. this._mixer = mixer;
  26118. this._clip = clip;
  26119. this._localRoot = localRoot;
  26120. this.blendMode = blendMode;
  26121. const tracks = clip.tracks,
  26122. nTracks = tracks.length,
  26123. interpolants = new Array(nTracks);
  26124. const interpolantSettings = {
  26125. endingStart: ZeroCurvatureEnding,
  26126. endingEnd: ZeroCurvatureEnding
  26127. };
  26128. for (let i = 0; i !== nTracks; ++i) {
  26129. const interpolant = tracks[i].createInterpolant(null);
  26130. interpolants[i] = interpolant;
  26131. interpolant.settings = interpolantSettings;
  26132. }
  26133. this._interpolantSettings = interpolantSettings;
  26134. this._interpolants = interpolants; // bound by the mixer
  26135. // inside: PropertyMixer (managed by the mixer)
  26136. this._propertyBindings = new Array(nTracks);
  26137. this._cacheIndex = null; // for the memory manager
  26138. this._byClipCacheIndex = null; // for the memory manager
  26139. this._timeScaleInterpolant = null;
  26140. this._weightInterpolant = null;
  26141. this.loop = LoopRepeat;
  26142. this._loopCount = -1; // global mixer time when the action is to be started
  26143. // it's set back to 'null' upon start of the action
  26144. this._startTime = null; // scaled local time of the action
  26145. // gets clamped or wrapped to 0..clip.duration according to loop
  26146. this.time = 0;
  26147. this.timeScale = 1;
  26148. this._effectiveTimeScale = 1;
  26149. this.weight = 1;
  26150. this._effectiveWeight = 1;
  26151. this.repetitions = Infinity; // no. of repetitions when looping
  26152. this.paused = false; // true -> zero effective time scale
  26153. this.enabled = true; // false -> zero effective weight
  26154. this.clampWhenFinished = false; // keep feeding the last frame?
  26155. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  26156. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  26157. } // State & Scheduling
  26158. play() {
  26159. this._mixer._activateAction(this);
  26160. return this;
  26161. }
  26162. stop() {
  26163. this._mixer._deactivateAction(this);
  26164. return this.reset();
  26165. }
  26166. reset() {
  26167. this.paused = false;
  26168. this.enabled = true;
  26169. this.time = 0; // restart clip
  26170. this._loopCount = -1; // forget previous loops
  26171. this._startTime = null; // forget scheduling
  26172. return this.stopFading().stopWarping();
  26173. }
  26174. isRunning() {
  26175. return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  26176. } // return true when play has been called
  26177. isScheduled() {
  26178. return this._mixer._isActiveAction(this);
  26179. }
  26180. startAt(time) {
  26181. this._startTime = time;
  26182. return this;
  26183. }
  26184. setLoop(mode, repetitions) {
  26185. this.loop = mode;
  26186. this.repetitions = repetitions;
  26187. return this;
  26188. } // Weight
  26189. // set the weight stopping any scheduled fading
  26190. // although .enabled = false yields an effective weight of zero, this
  26191. // method does *not* change .enabled, because it would be confusing
  26192. setEffectiveWeight(weight) {
  26193. this.weight = weight; // note: same logic as when updated at runtime
  26194. this._effectiveWeight = this.enabled ? weight : 0;
  26195. return this.stopFading();
  26196. } // return the weight considering fading and .enabled
  26197. getEffectiveWeight() {
  26198. return this._effectiveWeight;
  26199. }
  26200. fadeIn(duration) {
  26201. return this._scheduleFading(duration, 0, 1);
  26202. }
  26203. fadeOut(duration) {
  26204. return this._scheduleFading(duration, 1, 0);
  26205. }
  26206. crossFadeFrom(fadeOutAction, duration, warp) {
  26207. fadeOutAction.fadeOut(duration);
  26208. this.fadeIn(duration);
  26209. if (warp) {
  26210. const fadeInDuration = this._clip.duration,
  26211. fadeOutDuration = fadeOutAction._clip.duration,
  26212. startEndRatio = fadeOutDuration / fadeInDuration,
  26213. endStartRatio = fadeInDuration / fadeOutDuration;
  26214. fadeOutAction.warp(1.0, startEndRatio, duration);
  26215. this.warp(endStartRatio, 1.0, duration);
  26216. }
  26217. return this;
  26218. }
  26219. crossFadeTo(fadeInAction, duration, warp) {
  26220. return fadeInAction.crossFadeFrom(this, duration, warp);
  26221. }
  26222. stopFading() {
  26223. const weightInterpolant = this._weightInterpolant;
  26224. if (weightInterpolant !== null) {
  26225. this._weightInterpolant = null;
  26226. this._mixer._takeBackControlInterpolant(weightInterpolant);
  26227. }
  26228. return this;
  26229. } // Time Scale Control
  26230. // set the time scale stopping any scheduled warping
  26231. // although .paused = true yields an effective time scale of zero, this
  26232. // method does *not* change .paused, because it would be confusing
  26233. setEffectiveTimeScale(timeScale) {
  26234. this.timeScale = timeScale;
  26235. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  26236. return this.stopWarping();
  26237. } // return the time scale considering warping and .paused
  26238. getEffectiveTimeScale() {
  26239. return this._effectiveTimeScale;
  26240. }
  26241. setDuration(duration) {
  26242. this.timeScale = this._clip.duration / duration;
  26243. return this.stopWarping();
  26244. }
  26245. syncWith(action) {
  26246. this.time = action.time;
  26247. this.timeScale = action.timeScale;
  26248. return this.stopWarping();
  26249. }
  26250. halt(duration) {
  26251. return this.warp(this._effectiveTimeScale, 0, duration);
  26252. }
  26253. warp(startTimeScale, endTimeScale, duration) {
  26254. const mixer = this._mixer,
  26255. now = mixer.time,
  26256. timeScale = this.timeScale;
  26257. let interpolant = this._timeScaleInterpolant;
  26258. if (interpolant === null) {
  26259. interpolant = mixer._lendControlInterpolant();
  26260. this._timeScaleInterpolant = interpolant;
  26261. }
  26262. const times = interpolant.parameterPositions,
  26263. values = interpolant.sampleValues;
  26264. times[0] = now;
  26265. times[1] = now + duration;
  26266. values[0] = startTimeScale / timeScale;
  26267. values[1] = endTimeScale / timeScale;
  26268. return this;
  26269. }
  26270. stopWarping() {
  26271. const timeScaleInterpolant = this._timeScaleInterpolant;
  26272. if (timeScaleInterpolant !== null) {
  26273. this._timeScaleInterpolant = null;
  26274. this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
  26275. }
  26276. return this;
  26277. } // Object Accessors
  26278. getMixer() {
  26279. return this._mixer;
  26280. }
  26281. getClip() {
  26282. return this._clip;
  26283. }
  26284. getRoot() {
  26285. return this._localRoot || this._mixer._root;
  26286. } // Interna
  26287. _update(time, deltaTime, timeDirection, accuIndex) {
  26288. // called by the mixer
  26289. if (!this.enabled) {
  26290. // call ._updateWeight() to update ._effectiveWeight
  26291. this._updateWeight(time);
  26292. return;
  26293. }
  26294. const startTime = this._startTime;
  26295. if (startTime !== null) {
  26296. // check for scheduled start of action
  26297. const timeRunning = (time - startTime) * timeDirection;
  26298. if (timeRunning < 0 || timeDirection === 0) {
  26299. return; // yet to come / don't decide when delta = 0
  26300. } // start
  26301. this._startTime = null; // unschedule
  26302. deltaTime = timeDirection * timeRunning;
  26303. } // apply time scale and advance time
  26304. deltaTime *= this._updateTimeScale(time);
  26305. const clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting in
  26306. // an effective weight of 0
  26307. const weight = this._updateWeight(time);
  26308. if (weight > 0) {
  26309. const interpolants = this._interpolants;
  26310. const propertyMixers = this._propertyBindings;
  26311. switch (this.blendMode) {
  26312. case AdditiveAnimationBlendMode:
  26313. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  26314. interpolants[j].evaluate(clipTime);
  26315. propertyMixers[j].accumulateAdditive(weight);
  26316. }
  26317. break;
  26318. case NormalAnimationBlendMode:
  26319. default:
  26320. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  26321. interpolants[j].evaluate(clipTime);
  26322. propertyMixers[j].accumulate(accuIndex, weight);
  26323. }
  26324. }
  26325. }
  26326. }
  26327. _updateWeight(time) {
  26328. let weight = 0;
  26329. if (this.enabled) {
  26330. weight = this.weight;
  26331. const interpolant = this._weightInterpolant;
  26332. if (interpolant !== null) {
  26333. const interpolantValue = interpolant.evaluate(time)[0];
  26334. weight *= interpolantValue;
  26335. if (time > interpolant.parameterPositions[1]) {
  26336. this.stopFading();
  26337. if (interpolantValue === 0) {
  26338. // faded out, disable
  26339. this.enabled = false;
  26340. }
  26341. }
  26342. }
  26343. }
  26344. this._effectiveWeight = weight;
  26345. return weight;
  26346. }
  26347. _updateTimeScale(time) {
  26348. let timeScale = 0;
  26349. if (!this.paused) {
  26350. timeScale = this.timeScale;
  26351. const interpolant = this._timeScaleInterpolant;
  26352. if (interpolant !== null) {
  26353. const interpolantValue = interpolant.evaluate(time)[0];
  26354. timeScale *= interpolantValue;
  26355. if (time > interpolant.parameterPositions[1]) {
  26356. this.stopWarping();
  26357. if (timeScale === 0) {
  26358. // motion has halted, pause
  26359. this.paused = true;
  26360. } else {
  26361. // warp done - apply final time scale
  26362. this.timeScale = timeScale;
  26363. }
  26364. }
  26365. }
  26366. }
  26367. this._effectiveTimeScale = timeScale;
  26368. return timeScale;
  26369. }
  26370. _updateTime(deltaTime) {
  26371. const duration = this._clip.duration;
  26372. const loop = this.loop;
  26373. let time = this.time + deltaTime;
  26374. let loopCount = this._loopCount;
  26375. const pingPong = loop === LoopPingPong;
  26376. if (deltaTime === 0) {
  26377. if (loopCount === -1) return time;
  26378. return pingPong && (loopCount & 1) === 1 ? duration - time : time;
  26379. }
  26380. if (loop === LoopOnce) {
  26381. if (loopCount === -1) {
  26382. // just started
  26383. this._loopCount = 0;
  26384. this._setEndings(true, true, false);
  26385. }
  26386. handle_stop: {
  26387. if (time >= duration) {
  26388. time = duration;
  26389. } else if (time < 0) {
  26390. time = 0;
  26391. } else {
  26392. this.time = time;
  26393. break handle_stop;
  26394. }
  26395. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  26396. this.time = time;
  26397. this._mixer.dispatchEvent({
  26398. type: 'finished',
  26399. action: this,
  26400. direction: deltaTime < 0 ? -1 : 1
  26401. });
  26402. }
  26403. } else {
  26404. // repetitive Repeat or PingPong
  26405. if (loopCount === -1) {
  26406. // just started
  26407. if (deltaTime >= 0) {
  26408. loopCount = 0;
  26409. this._setEndings(true, this.repetitions === 0, pingPong);
  26410. } else {
  26411. // when looping in reverse direction, the initial
  26412. // transition through zero counts as a repetition,
  26413. // so leave loopCount at -1
  26414. this._setEndings(this.repetitions === 0, true, pingPong);
  26415. }
  26416. }
  26417. if (time >= duration || time < 0) {
  26418. // wrap around
  26419. const loopDelta = Math.floor(time / duration); // signed
  26420. time -= duration * loopDelta;
  26421. loopCount += Math.abs(loopDelta);
  26422. const pending = this.repetitions - loopCount;
  26423. if (pending <= 0) {
  26424. // have to stop (switch state, clamp time, fire event)
  26425. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  26426. time = deltaTime > 0 ? duration : 0;
  26427. this.time = time;
  26428. this._mixer.dispatchEvent({
  26429. type: 'finished',
  26430. action: this,
  26431. direction: deltaTime > 0 ? 1 : -1
  26432. });
  26433. } else {
  26434. // keep running
  26435. if (pending === 1) {
  26436. // entering the last round
  26437. const atStart = deltaTime < 0;
  26438. this._setEndings(atStart, !atStart, pingPong);
  26439. } else {
  26440. this._setEndings(false, false, pingPong);
  26441. }
  26442. this._loopCount = loopCount;
  26443. this.time = time;
  26444. this._mixer.dispatchEvent({
  26445. type: 'loop',
  26446. action: this,
  26447. loopDelta: loopDelta
  26448. });
  26449. }
  26450. } else {
  26451. this.time = time;
  26452. }
  26453. if (pingPong && (loopCount & 1) === 1) {
  26454. // invert time for the "pong round"
  26455. return duration - time;
  26456. }
  26457. }
  26458. return time;
  26459. }
  26460. _setEndings(atStart, atEnd, pingPong) {
  26461. const settings = this._interpolantSettings;
  26462. if (pingPong) {
  26463. settings.endingStart = ZeroSlopeEnding;
  26464. settings.endingEnd = ZeroSlopeEnding;
  26465. } else {
  26466. // assuming for LoopOnce atStart == atEnd == true
  26467. if (atStart) {
  26468. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26469. } else {
  26470. settings.endingStart = WrapAroundEnding;
  26471. }
  26472. if (atEnd) {
  26473. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26474. } else {
  26475. settings.endingEnd = WrapAroundEnding;
  26476. }
  26477. }
  26478. }
  26479. _scheduleFading(duration, weightNow, weightThen) {
  26480. const mixer = this._mixer,
  26481. now = mixer.time;
  26482. let interpolant = this._weightInterpolant;
  26483. if (interpolant === null) {
  26484. interpolant = mixer._lendControlInterpolant();
  26485. this._weightInterpolant = interpolant;
  26486. }
  26487. const times = interpolant.parameterPositions,
  26488. values = interpolant.sampleValues;
  26489. times[0] = now;
  26490. values[0] = weightNow;
  26491. times[1] = now + duration;
  26492. values[1] = weightThen;
  26493. return this;
  26494. }
  26495. }
  26496. class AnimationMixer extends EventDispatcher {
  26497. constructor(root) {
  26498. super();
  26499. this._root = root;
  26500. this._initMemoryManager();
  26501. this._accuIndex = 0;
  26502. this.time = 0;
  26503. this.timeScale = 1.0;
  26504. }
  26505. _bindAction(action, prototypeAction) {
  26506. const root = action._localRoot || this._root,
  26507. tracks = action._clip.tracks,
  26508. nTracks = tracks.length,
  26509. bindings = action._propertyBindings,
  26510. interpolants = action._interpolants,
  26511. rootUuid = root.uuid,
  26512. bindingsByRoot = this._bindingsByRootAndName;
  26513. let bindingsByName = bindingsByRoot[rootUuid];
  26514. if (bindingsByName === undefined) {
  26515. bindingsByName = {};
  26516. bindingsByRoot[rootUuid] = bindingsByName;
  26517. }
  26518. for (let i = 0; i !== nTracks; ++i) {
  26519. const track = tracks[i],
  26520. trackName = track.name;
  26521. let binding = bindingsByName[trackName];
  26522. if (binding !== undefined) {
  26523. bindings[i] = binding;
  26524. } else {
  26525. binding = bindings[i];
  26526. if (binding !== undefined) {
  26527. // existing binding, make sure the cache knows
  26528. if (binding._cacheIndex === null) {
  26529. ++binding.referenceCount;
  26530. this._addInactiveBinding(binding, rootUuid, trackName);
  26531. }
  26532. continue;
  26533. }
  26534. const path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
  26535. binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
  26536. ++binding.referenceCount;
  26537. this._addInactiveBinding(binding, rootUuid, trackName);
  26538. bindings[i] = binding;
  26539. }
  26540. interpolants[i].resultBuffer = binding.buffer;
  26541. }
  26542. }
  26543. _activateAction(action) {
  26544. if (!this._isActiveAction(action)) {
  26545. if (action._cacheIndex === null) {
  26546. // this action has been forgotten by the cache, but the user
  26547. // appears to be still using it -> rebind
  26548. const rootUuid = (action._localRoot || this._root).uuid,
  26549. clipUuid = action._clip.uuid,
  26550. actionsForClip = this._actionsByClip[clipUuid];
  26551. this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
  26552. this._addInactiveAction(action, clipUuid, rootUuid);
  26553. }
  26554. const bindings = action._propertyBindings; // increment reference counts / sort out state
  26555. for (let i = 0, n = bindings.length; i !== n; ++i) {
  26556. const binding = bindings[i];
  26557. if (binding.useCount++ === 0) {
  26558. this._lendBinding(binding);
  26559. binding.saveOriginalState();
  26560. }
  26561. }
  26562. this._lendAction(action);
  26563. }
  26564. }
  26565. _deactivateAction(action) {
  26566. if (this._isActiveAction(action)) {
  26567. const bindings = action._propertyBindings; // decrement reference counts / sort out state
  26568. for (let i = 0, n = bindings.length; i !== n; ++i) {
  26569. const binding = bindings[i];
  26570. if (--binding.useCount === 0) {
  26571. binding.restoreOriginalState();
  26572. this._takeBackBinding(binding);
  26573. }
  26574. }
  26575. this._takeBackAction(action);
  26576. }
  26577. } // Memory manager
  26578. _initMemoryManager() {
  26579. this._actions = []; // 'nActiveActions' followed by inactive ones
  26580. this._nActiveActions = 0;
  26581. this._actionsByClip = {}; // inside:
  26582. // {
  26583. // knownActions: Array< AnimationAction > - used as prototypes
  26584. // actionByRoot: AnimationAction - lookup
  26585. // }
  26586. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  26587. this._nActiveBindings = 0;
  26588. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  26589. this._controlInterpolants = []; // same game as above
  26590. this._nActiveControlInterpolants = 0;
  26591. const scope = this;
  26592. this.stats = {
  26593. actions: {
  26594. get total() {
  26595. return scope._actions.length;
  26596. },
  26597. get inUse() {
  26598. return scope._nActiveActions;
  26599. }
  26600. },
  26601. bindings: {
  26602. get total() {
  26603. return scope._bindings.length;
  26604. },
  26605. get inUse() {
  26606. return scope._nActiveBindings;
  26607. }
  26608. },
  26609. controlInterpolants: {
  26610. get total() {
  26611. return scope._controlInterpolants.length;
  26612. },
  26613. get inUse() {
  26614. return scope._nActiveControlInterpolants;
  26615. }
  26616. }
  26617. };
  26618. } // Memory management for AnimationAction objects
  26619. _isActiveAction(action) {
  26620. const index = action._cacheIndex;
  26621. return index !== null && index < this._nActiveActions;
  26622. }
  26623. _addInactiveAction(action, clipUuid, rootUuid) {
  26624. const actions = this._actions,
  26625. actionsByClip = this._actionsByClip;
  26626. let actionsForClip = actionsByClip[clipUuid];
  26627. if (actionsForClip === undefined) {
  26628. actionsForClip = {
  26629. knownActions: [action],
  26630. actionByRoot: {}
  26631. };
  26632. action._byClipCacheIndex = 0;
  26633. actionsByClip[clipUuid] = actionsForClip;
  26634. } else {
  26635. const knownActions = actionsForClip.knownActions;
  26636. action._byClipCacheIndex = knownActions.length;
  26637. knownActions.push(action);
  26638. }
  26639. action._cacheIndex = actions.length;
  26640. actions.push(action);
  26641. actionsForClip.actionByRoot[rootUuid] = action;
  26642. }
  26643. _removeInactiveAction(action) {
  26644. const actions = this._actions,
  26645. lastInactiveAction = actions[actions.length - 1],
  26646. cacheIndex = action._cacheIndex;
  26647. lastInactiveAction._cacheIndex = cacheIndex;
  26648. actions[cacheIndex] = lastInactiveAction;
  26649. actions.pop();
  26650. action._cacheIndex = null;
  26651. const clipUuid = action._clip.uuid,
  26652. actionsByClip = this._actionsByClip,
  26653. actionsForClip = actionsByClip[clipUuid],
  26654. knownActionsForClip = actionsForClip.knownActions,
  26655. lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
  26656. byClipCacheIndex = action._byClipCacheIndex;
  26657. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  26658. knownActionsForClip[byClipCacheIndex] = lastKnownAction;
  26659. knownActionsForClip.pop();
  26660. action._byClipCacheIndex = null;
  26661. const actionByRoot = actionsForClip.actionByRoot,
  26662. rootUuid = (action._localRoot || this._root).uuid;
  26663. delete actionByRoot[rootUuid];
  26664. if (knownActionsForClip.length === 0) {
  26665. delete actionsByClip[clipUuid];
  26666. }
  26667. this._removeInactiveBindingsForAction(action);
  26668. }
  26669. _removeInactiveBindingsForAction(action) {
  26670. const bindings = action._propertyBindings;
  26671. for (let i = 0, n = bindings.length; i !== n; ++i) {
  26672. const binding = bindings[i];
  26673. if (--binding.referenceCount === 0) {
  26674. this._removeInactiveBinding(binding);
  26675. }
  26676. }
  26677. }
  26678. _lendAction(action) {
  26679. // [ active actions | inactive actions ]
  26680. // [ active actions >| inactive actions ]
  26681. // s a
  26682. // <-swap->
  26683. // a s
  26684. const actions = this._actions,
  26685. prevIndex = action._cacheIndex,
  26686. lastActiveIndex = this._nActiveActions++,
  26687. firstInactiveAction = actions[lastActiveIndex];
  26688. action._cacheIndex = lastActiveIndex;
  26689. actions[lastActiveIndex] = action;
  26690. firstInactiveAction._cacheIndex = prevIndex;
  26691. actions[prevIndex] = firstInactiveAction;
  26692. }
  26693. _takeBackAction(action) {
  26694. // [ active actions | inactive actions ]
  26695. // [ active actions |< inactive actions ]
  26696. // a s
  26697. // <-swap->
  26698. // s a
  26699. const actions = this._actions,
  26700. prevIndex = action._cacheIndex,
  26701. firstInactiveIndex = --this._nActiveActions,
  26702. lastActiveAction = actions[firstInactiveIndex];
  26703. action._cacheIndex = firstInactiveIndex;
  26704. actions[firstInactiveIndex] = action;
  26705. lastActiveAction._cacheIndex = prevIndex;
  26706. actions[prevIndex] = lastActiveAction;
  26707. } // Memory management for PropertyMixer objects
  26708. _addInactiveBinding(binding, rootUuid, trackName) {
  26709. const bindingsByRoot = this._bindingsByRootAndName,
  26710. bindings = this._bindings;
  26711. let bindingByName = bindingsByRoot[rootUuid];
  26712. if (bindingByName === undefined) {
  26713. bindingByName = {};
  26714. bindingsByRoot[rootUuid] = bindingByName;
  26715. }
  26716. bindingByName[trackName] = binding;
  26717. binding._cacheIndex = bindings.length;
  26718. bindings.push(binding);
  26719. }
  26720. _removeInactiveBinding(binding) {
  26721. const bindings = this._bindings,
  26722. propBinding = binding.binding,
  26723. rootUuid = propBinding.rootNode.uuid,
  26724. trackName = propBinding.path,
  26725. bindingsByRoot = this._bindingsByRootAndName,
  26726. bindingByName = bindingsByRoot[rootUuid],
  26727. lastInactiveBinding = bindings[bindings.length - 1],
  26728. cacheIndex = binding._cacheIndex;
  26729. lastInactiveBinding._cacheIndex = cacheIndex;
  26730. bindings[cacheIndex] = lastInactiveBinding;
  26731. bindings.pop();
  26732. delete bindingByName[trackName];
  26733. if (Object.keys(bindingByName).length === 0) {
  26734. delete bindingsByRoot[rootUuid];
  26735. }
  26736. }
  26737. _lendBinding(binding) {
  26738. const bindings = this._bindings,
  26739. prevIndex = binding._cacheIndex,
  26740. lastActiveIndex = this._nActiveBindings++,
  26741. firstInactiveBinding = bindings[lastActiveIndex];
  26742. binding._cacheIndex = lastActiveIndex;
  26743. bindings[lastActiveIndex] = binding;
  26744. firstInactiveBinding._cacheIndex = prevIndex;
  26745. bindings[prevIndex] = firstInactiveBinding;
  26746. }
  26747. _takeBackBinding(binding) {
  26748. const bindings = this._bindings,
  26749. prevIndex = binding._cacheIndex,
  26750. firstInactiveIndex = --this._nActiveBindings,
  26751. lastActiveBinding = bindings[firstInactiveIndex];
  26752. binding._cacheIndex = firstInactiveIndex;
  26753. bindings[firstInactiveIndex] = binding;
  26754. lastActiveBinding._cacheIndex = prevIndex;
  26755. bindings[prevIndex] = lastActiveBinding;
  26756. } // Memory management of Interpolants for weight and time scale
  26757. _lendControlInterpolant() {
  26758. const interpolants = this._controlInterpolants,
  26759. lastActiveIndex = this._nActiveControlInterpolants++;
  26760. let interpolant = interpolants[lastActiveIndex];
  26761. if (interpolant === undefined) {
  26762. interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, this._controlInterpolantsResultBuffer);
  26763. interpolant.__cacheIndex = lastActiveIndex;
  26764. interpolants[lastActiveIndex] = interpolant;
  26765. }
  26766. return interpolant;
  26767. }
  26768. _takeBackControlInterpolant(interpolant) {
  26769. const interpolants = this._controlInterpolants,
  26770. prevIndex = interpolant.__cacheIndex,
  26771. firstInactiveIndex = --this._nActiveControlInterpolants,
  26772. lastActiveInterpolant = interpolants[firstInactiveIndex];
  26773. interpolant.__cacheIndex = firstInactiveIndex;
  26774. interpolants[firstInactiveIndex] = interpolant;
  26775. lastActiveInterpolant.__cacheIndex = prevIndex;
  26776. interpolants[prevIndex] = lastActiveInterpolant;
  26777. } // return an action for a clip optionally using a custom root target
  26778. // object (this method allocates a lot of dynamic memory in case a
  26779. // previously unknown clip/root combination is specified)
  26780. clipAction(clip, optionalRoot, blendMode) {
  26781. const root = optionalRoot || this._root,
  26782. rootUuid = root.uuid;
  26783. let clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip;
  26784. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  26785. const actionsForClip = this._actionsByClip[clipUuid];
  26786. let prototypeAction = null;
  26787. if (blendMode === undefined) {
  26788. if (clipObject !== null) {
  26789. blendMode = clipObject.blendMode;
  26790. } else {
  26791. blendMode = NormalAnimationBlendMode;
  26792. }
  26793. }
  26794. if (actionsForClip !== undefined) {
  26795. const existingAction = actionsForClip.actionByRoot[rootUuid];
  26796. if (existingAction !== undefined && existingAction.blendMode === blendMode) {
  26797. return existingAction;
  26798. } // we know the clip, so we don't have to parse all
  26799. // the bindings again but can just copy
  26800. prototypeAction = actionsForClip.knownActions[0]; // also, take the clip from the prototype action
  26801. if (clipObject === null) clipObject = prototypeAction._clip;
  26802. } // clip must be known when specified via string
  26803. if (clipObject === null) return null; // allocate all resources required to run it
  26804. const newAction = new AnimationAction(this, clipObject, optionalRoot, blendMode);
  26805. this._bindAction(newAction, prototypeAction); // and make the action known to the memory manager
  26806. this._addInactiveAction(newAction, clipUuid, rootUuid);
  26807. return newAction;
  26808. } // get an existing action
  26809. existingAction(clip, optionalRoot) {
  26810. const root = optionalRoot || this._root,
  26811. rootUuid = root.uuid,
  26812. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  26813. clipUuid = clipObject ? clipObject.uuid : clip,
  26814. actionsForClip = this._actionsByClip[clipUuid];
  26815. if (actionsForClip !== undefined) {
  26816. return actionsForClip.actionByRoot[rootUuid] || null;
  26817. }
  26818. return null;
  26819. } // deactivates all previously scheduled actions
  26820. stopAllAction() {
  26821. const actions = this._actions,
  26822. nActions = this._nActiveActions;
  26823. for (let i = nActions - 1; i >= 0; --i) {
  26824. actions[i].stop();
  26825. }
  26826. return this;
  26827. } // advance the time and update apply the animation
  26828. update(deltaTime) {
  26829. deltaTime *= this.timeScale;
  26830. const actions = this._actions,
  26831. nActions = this._nActiveActions,
  26832. time = this.time += deltaTime,
  26833. timeDirection = Math.sign(deltaTime),
  26834. accuIndex = this._accuIndex ^= 1; // run active actions
  26835. for (let i = 0; i !== nActions; ++i) {
  26836. const action = actions[i];
  26837. action._update(time, deltaTime, timeDirection, accuIndex);
  26838. } // update scene graph
  26839. const bindings = this._bindings,
  26840. nBindings = this._nActiveBindings;
  26841. for (let i = 0; i !== nBindings; ++i) {
  26842. bindings[i].apply(accuIndex);
  26843. }
  26844. return this;
  26845. } // Allows you to seek to a specific time in an animation.
  26846. setTime(timeInSeconds) {
  26847. this.time = 0; // Zero out time attribute for AnimationMixer object;
  26848. for (let i = 0; i < this._actions.length; i++) {
  26849. this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  26850. }
  26851. return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
  26852. } // return this mixer's root target object
  26853. getRoot() {
  26854. return this._root;
  26855. } // free all resources specific to a particular clip
  26856. uncacheClip(clip) {
  26857. const actions = this._actions,
  26858. clipUuid = clip.uuid,
  26859. actionsByClip = this._actionsByClip,
  26860. actionsForClip = actionsByClip[clipUuid];
  26861. if (actionsForClip !== undefined) {
  26862. // note: just calling _removeInactiveAction would mess up the
  26863. // iteration state and also require updating the state we can
  26864. // just throw away
  26865. const actionsToRemove = actionsForClip.knownActions;
  26866. for (let i = 0, n = actionsToRemove.length; i !== n; ++i) {
  26867. const action = actionsToRemove[i];
  26868. this._deactivateAction(action);
  26869. const cacheIndex = action._cacheIndex,
  26870. lastInactiveAction = actions[actions.length - 1];
  26871. action._cacheIndex = null;
  26872. action._byClipCacheIndex = null;
  26873. lastInactiveAction._cacheIndex = cacheIndex;
  26874. actions[cacheIndex] = lastInactiveAction;
  26875. actions.pop();
  26876. this._removeInactiveBindingsForAction(action);
  26877. }
  26878. delete actionsByClip[clipUuid];
  26879. }
  26880. } // free all resources specific to a particular root target object
  26881. uncacheRoot(root) {
  26882. const rootUuid = root.uuid,
  26883. actionsByClip = this._actionsByClip;
  26884. for (const clipUuid in actionsByClip) {
  26885. const actionByRoot = actionsByClip[clipUuid].actionByRoot,
  26886. action = actionByRoot[rootUuid];
  26887. if (action !== undefined) {
  26888. this._deactivateAction(action);
  26889. this._removeInactiveAction(action);
  26890. }
  26891. }
  26892. const bindingsByRoot = this._bindingsByRootAndName,
  26893. bindingByName = bindingsByRoot[rootUuid];
  26894. if (bindingByName !== undefined) {
  26895. for (const trackName in bindingByName) {
  26896. const binding = bindingByName[trackName];
  26897. binding.restoreOriginalState();
  26898. this._removeInactiveBinding(binding);
  26899. }
  26900. }
  26901. } // remove a targeted clip from the cache
  26902. uncacheAction(clip, optionalRoot) {
  26903. const action = this.existingAction(clip, optionalRoot);
  26904. if (action !== null) {
  26905. this._deactivateAction(action);
  26906. this._removeInactiveAction(action);
  26907. }
  26908. }
  26909. }
  26910. AnimationMixer.prototype._controlInterpolantsResultBuffer = new Float32Array(1);
  26911. class Uniform {
  26912. constructor(value) {
  26913. if (typeof value === 'string') {
  26914. console.warn('THREE.Uniform: Type parameter is no longer needed.');
  26915. value = arguments[1];
  26916. }
  26917. this.value = value;
  26918. }
  26919. clone() {
  26920. return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
  26921. }
  26922. }
  26923. class InstancedInterleavedBuffer extends InterleavedBuffer {
  26924. constructor(array, stride, meshPerAttribute = 1) {
  26925. super(array, stride);
  26926. this.meshPerAttribute = meshPerAttribute;
  26927. }
  26928. copy(source) {
  26929. super.copy(source);
  26930. this.meshPerAttribute = source.meshPerAttribute;
  26931. return this;
  26932. }
  26933. clone(data) {
  26934. const ib = super.clone(data);
  26935. ib.meshPerAttribute = this.meshPerAttribute;
  26936. return ib;
  26937. }
  26938. toJSON(data) {
  26939. const json = super.toJSON(data);
  26940. json.isInstancedInterleavedBuffer = true;
  26941. json.meshPerAttribute = this.meshPerAttribute;
  26942. return json;
  26943. }
  26944. }
  26945. InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true;
  26946. class GLBufferAttribute {
  26947. constructor(buffer, type, itemSize, elementSize, count) {
  26948. this.buffer = buffer;
  26949. this.type = type;
  26950. this.itemSize = itemSize;
  26951. this.elementSize = elementSize;
  26952. this.count = count;
  26953. this.version = 0;
  26954. }
  26955. set needsUpdate(value) {
  26956. if (value === true) this.version++;
  26957. }
  26958. setBuffer(buffer) {
  26959. this.buffer = buffer;
  26960. return this;
  26961. }
  26962. setType(type, elementSize) {
  26963. this.type = type;
  26964. this.elementSize = elementSize;
  26965. return this;
  26966. }
  26967. setItemSize(itemSize) {
  26968. this.itemSize = itemSize;
  26969. return this;
  26970. }
  26971. setCount(count) {
  26972. this.count = count;
  26973. return this;
  26974. }
  26975. }
  26976. GLBufferAttribute.prototype.isGLBufferAttribute = true;
  26977. class Raycaster {
  26978. constructor(origin, direction, near = 0, far = Infinity) {
  26979. this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)
  26980. this.near = near;
  26981. this.far = far;
  26982. this.camera = null;
  26983. this.layers = new Layers();
  26984. this.params = {
  26985. Mesh: {},
  26986. Line: {
  26987. threshold: 1
  26988. },
  26989. LOD: {},
  26990. Points: {
  26991. threshold: 1
  26992. },
  26993. Sprite: {}
  26994. };
  26995. }
  26996. set(origin, direction) {
  26997. // direction is assumed to be normalized (for accurate distance calculations)
  26998. this.ray.set(origin, direction);
  26999. }
  27000. setFromCamera(coords, camera) {
  27001. if (camera && camera.isPerspectiveCamera) {
  27002. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  27003. this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
  27004. this.camera = camera;
  27005. } else if (camera && camera.isOrthographicCamera) {
  27006. this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
  27007. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  27008. this.camera = camera;
  27009. } else {
  27010. console.error('THREE.Raycaster: Unsupported camera type: ' + camera.type);
  27011. }
  27012. }
  27013. intersectObject(object, recursive = true, intersects = []) {
  27014. intersectObject(object, this, intersects, recursive);
  27015. intersects.sort(ascSort);
  27016. return intersects;
  27017. }
  27018. intersectObjects(objects, recursive = true, intersects = []) {
  27019. for (let i = 0, l = objects.length; i < l; i++) {
  27020. intersectObject(objects[i], this, intersects, recursive);
  27021. }
  27022. intersects.sort(ascSort);
  27023. return intersects;
  27024. }
  27025. }
  27026. function ascSort(a, b) {
  27027. return a.distance - b.distance;
  27028. }
  27029. function intersectObject(object, raycaster, intersects, recursive) {
  27030. if (object.layers.test(raycaster.layers)) {
  27031. object.raycast(raycaster, intersects);
  27032. }
  27033. if (recursive === true) {
  27034. const children = object.children;
  27035. for (let i = 0, l = children.length; i < l; i++) {
  27036. intersectObject(children[i], raycaster, intersects, true);
  27037. }
  27038. }
  27039. }
  27040. /**
  27041. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  27042. *
  27043. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  27044. * The azimuthal angle (theta) is measured from the positive z-axis.
  27045. */
  27046. class Spherical {
  27047. constructor(radius = 1, phi = 0, theta = 0) {
  27048. this.radius = radius;
  27049. this.phi = phi; // polar angle
  27050. this.theta = theta; // azimuthal angle
  27051. return this;
  27052. }
  27053. set(radius, phi, theta) {
  27054. this.radius = radius;
  27055. this.phi = phi;
  27056. this.theta = theta;
  27057. return this;
  27058. }
  27059. copy(other) {
  27060. this.radius = other.radius;
  27061. this.phi = other.phi;
  27062. this.theta = other.theta;
  27063. return this;
  27064. } // restrict phi to be betwee EPS and PI-EPS
  27065. makeSafe() {
  27066. const EPS = 0.000001;
  27067. this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
  27068. return this;
  27069. }
  27070. setFromVector3(v) {
  27071. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27072. }
  27073. setFromCartesianCoords(x, y, z) {
  27074. this.radius = Math.sqrt(x * x + y * y + z * z);
  27075. if (this.radius === 0) {
  27076. this.theta = 0;
  27077. this.phi = 0;
  27078. } else {
  27079. this.theta = Math.atan2(x, z);
  27080. this.phi = Math.acos(clamp(y / this.radius, -1, 1));
  27081. }
  27082. return this;
  27083. }
  27084. clone() {
  27085. return new this.constructor().copy(this);
  27086. }
  27087. }
  27088. /**
  27089. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  27090. */
  27091. class Cylindrical {
  27092. constructor(radius = 1, theta = 0, y = 0) {
  27093. this.radius = radius; // distance from the origin to a point in the x-z plane
  27094. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  27095. this.y = y; // height above the x-z plane
  27096. return this;
  27097. }
  27098. set(radius, theta, y) {
  27099. this.radius = radius;
  27100. this.theta = theta;
  27101. this.y = y;
  27102. return this;
  27103. }
  27104. copy(other) {
  27105. this.radius = other.radius;
  27106. this.theta = other.theta;
  27107. this.y = other.y;
  27108. return this;
  27109. }
  27110. setFromVector3(v) {
  27111. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27112. }
  27113. setFromCartesianCoords(x, y, z) {
  27114. this.radius = Math.sqrt(x * x + z * z);
  27115. this.theta = Math.atan2(x, z);
  27116. this.y = y;
  27117. return this;
  27118. }
  27119. clone() {
  27120. return new this.constructor().copy(this);
  27121. }
  27122. }
  27123. const _vector$4 = /*@__PURE__*/new Vector2();
  27124. class Box2 {
  27125. constructor(min = new Vector2(+Infinity, +Infinity), max = new Vector2(-Infinity, -Infinity)) {
  27126. this.min = min;
  27127. this.max = max;
  27128. }
  27129. set(min, max) {
  27130. this.min.copy(min);
  27131. this.max.copy(max);
  27132. return this;
  27133. }
  27134. setFromPoints(points) {
  27135. this.makeEmpty();
  27136. for (let i = 0, il = points.length; i < il; i++) {
  27137. this.expandByPoint(points[i]);
  27138. }
  27139. return this;
  27140. }
  27141. setFromCenterAndSize(center, size) {
  27142. const halfSize = _vector$4.copy(size).multiplyScalar(0.5);
  27143. this.min.copy(center).sub(halfSize);
  27144. this.max.copy(center).add(halfSize);
  27145. return this;
  27146. }
  27147. clone() {
  27148. return new this.constructor().copy(this);
  27149. }
  27150. copy(box) {
  27151. this.min.copy(box.min);
  27152. this.max.copy(box.max);
  27153. return this;
  27154. }
  27155. makeEmpty() {
  27156. this.min.x = this.min.y = +Infinity;
  27157. this.max.x = this.max.y = -Infinity;
  27158. return this;
  27159. }
  27160. isEmpty() {
  27161. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  27162. return this.max.x < this.min.x || this.max.y < this.min.y;
  27163. }
  27164. getCenter(target) {
  27165. return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  27166. }
  27167. getSize(target) {
  27168. return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  27169. }
  27170. expandByPoint(point) {
  27171. this.min.min(point);
  27172. this.max.max(point);
  27173. return this;
  27174. }
  27175. expandByVector(vector) {
  27176. this.min.sub(vector);
  27177. this.max.add(vector);
  27178. return this;
  27179. }
  27180. expandByScalar(scalar) {
  27181. this.min.addScalar(-scalar);
  27182. this.max.addScalar(scalar);
  27183. return this;
  27184. }
  27185. containsPoint(point) {
  27186. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
  27187. }
  27188. containsBox(box) {
  27189. 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;
  27190. }
  27191. getParameter(point, target) {
  27192. // This can potentially have a divide by zero if the box
  27193. // has a size dimension of 0.
  27194. 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));
  27195. }
  27196. intersectsBox(box) {
  27197. // using 4 splitting planes to rule out intersections
  27198. 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;
  27199. }
  27200. clampPoint(point, target) {
  27201. return target.copy(point).clamp(this.min, this.max);
  27202. }
  27203. distanceToPoint(point) {
  27204. const clampedPoint = _vector$4.copy(point).clamp(this.min, this.max);
  27205. return clampedPoint.sub(point).length();
  27206. }
  27207. intersect(box) {
  27208. this.min.max(box.min);
  27209. this.max.min(box.max);
  27210. return this;
  27211. }
  27212. union(box) {
  27213. this.min.min(box.min);
  27214. this.max.max(box.max);
  27215. return this;
  27216. }
  27217. translate(offset) {
  27218. this.min.add(offset);
  27219. this.max.add(offset);
  27220. return this;
  27221. }
  27222. equals(box) {
  27223. return box.min.equals(this.min) && box.max.equals(this.max);
  27224. }
  27225. }
  27226. Box2.prototype.isBox2 = true;
  27227. const _startP = /*@__PURE__*/new Vector3();
  27228. const _startEnd = /*@__PURE__*/new Vector3();
  27229. class Line3 {
  27230. constructor(start = new Vector3(), end = new Vector3()) {
  27231. this.start = start;
  27232. this.end = end;
  27233. }
  27234. set(start, end) {
  27235. this.start.copy(start);
  27236. this.end.copy(end);
  27237. return this;
  27238. }
  27239. copy(line) {
  27240. this.start.copy(line.start);
  27241. this.end.copy(line.end);
  27242. return this;
  27243. }
  27244. getCenter(target) {
  27245. return target.addVectors(this.start, this.end).multiplyScalar(0.5);
  27246. }
  27247. delta(target) {
  27248. return target.subVectors(this.end, this.start);
  27249. }
  27250. distanceSq() {
  27251. return this.start.distanceToSquared(this.end);
  27252. }
  27253. distance() {
  27254. return this.start.distanceTo(this.end);
  27255. }
  27256. at(t, target) {
  27257. return this.delta(target).multiplyScalar(t).add(this.start);
  27258. }
  27259. closestPointToPointParameter(point, clampToLine) {
  27260. _startP.subVectors(point, this.start);
  27261. _startEnd.subVectors(this.end, this.start);
  27262. const startEnd2 = _startEnd.dot(_startEnd);
  27263. const startEnd_startP = _startEnd.dot(_startP);
  27264. let t = startEnd_startP / startEnd2;
  27265. if (clampToLine) {
  27266. t = clamp(t, 0, 1);
  27267. }
  27268. return t;
  27269. }
  27270. closestPointToPoint(point, clampToLine, target) {
  27271. const t = this.closestPointToPointParameter(point, clampToLine);
  27272. return this.delta(target).multiplyScalar(t).add(this.start);
  27273. }
  27274. applyMatrix4(matrix) {
  27275. this.start.applyMatrix4(matrix);
  27276. this.end.applyMatrix4(matrix);
  27277. return this;
  27278. }
  27279. equals(line) {
  27280. return line.start.equals(this.start) && line.end.equals(this.end);
  27281. }
  27282. clone() {
  27283. return new this.constructor().copy(this);
  27284. }
  27285. }
  27286. const _vector$3 = /*@__PURE__*/new Vector3();
  27287. class SpotLightHelper extends Object3D {
  27288. constructor(light, color) {
  27289. super();
  27290. this.light = light;
  27291. this.light.updateMatrixWorld();
  27292. this.matrix = light.matrixWorld;
  27293. this.matrixAutoUpdate = false;
  27294. this.color = color;
  27295. const geometry = new BufferGeometry();
  27296. 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];
  27297. for (let i = 0, j = 1, l = 32; i < l; i++, j++) {
  27298. const p1 = i / l * Math.PI * 2;
  27299. const p2 = j / l * Math.PI * 2;
  27300. positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
  27301. }
  27302. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  27303. const material = new LineBasicMaterial({
  27304. fog: false,
  27305. toneMapped: false
  27306. });
  27307. this.cone = new LineSegments(geometry, material);
  27308. this.add(this.cone);
  27309. this.update();
  27310. }
  27311. dispose() {
  27312. this.cone.geometry.dispose();
  27313. this.cone.material.dispose();
  27314. }
  27315. update() {
  27316. this.light.updateMatrixWorld();
  27317. const coneLength = this.light.distance ? this.light.distance : 1000;
  27318. const coneWidth = coneLength * Math.tan(this.light.angle);
  27319. this.cone.scale.set(coneWidth, coneWidth, coneLength);
  27320. _vector$3.setFromMatrixPosition(this.light.target.matrixWorld);
  27321. this.cone.lookAt(_vector$3);
  27322. if (this.color !== undefined) {
  27323. this.cone.material.color.set(this.color);
  27324. } else {
  27325. this.cone.material.color.copy(this.light.color);
  27326. }
  27327. }
  27328. }
  27329. const _vector$2 = /*@__PURE__*/new Vector3();
  27330. const _boneMatrix = /*@__PURE__*/new Matrix4();
  27331. const _matrixWorldInv = /*@__PURE__*/new Matrix4();
  27332. class SkeletonHelper extends LineSegments {
  27333. constructor(object) {
  27334. const bones = getBoneList(object);
  27335. const geometry = new BufferGeometry();
  27336. const vertices = [];
  27337. const colors = [];
  27338. const color1 = new Color(0, 0, 1);
  27339. const color2 = new Color(0, 1, 0);
  27340. for (let i = 0; i < bones.length; i++) {
  27341. const bone = bones[i];
  27342. if (bone.parent && bone.parent.isBone) {
  27343. vertices.push(0, 0, 0);
  27344. vertices.push(0, 0, 0);
  27345. colors.push(color1.r, color1.g, color1.b);
  27346. colors.push(color2.r, color2.g, color2.b);
  27347. }
  27348. }
  27349. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27350. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27351. const material = new LineBasicMaterial({
  27352. vertexColors: true,
  27353. depthTest: false,
  27354. depthWrite: false,
  27355. toneMapped: false,
  27356. transparent: true
  27357. });
  27358. super(geometry, material);
  27359. this.type = 'SkeletonHelper';
  27360. this.isSkeletonHelper = true;
  27361. this.root = object;
  27362. this.bones = bones;
  27363. this.matrix = object.matrixWorld;
  27364. this.matrixAutoUpdate = false;
  27365. }
  27366. updateMatrixWorld(force) {
  27367. const bones = this.bones;
  27368. const geometry = this.geometry;
  27369. const position = geometry.getAttribute('position');
  27370. _matrixWorldInv.copy(this.root.matrixWorld).invert();
  27371. for (let i = 0, j = 0; i < bones.length; i++) {
  27372. const bone = bones[i];
  27373. if (bone.parent && bone.parent.isBone) {
  27374. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
  27375. _vector$2.setFromMatrixPosition(_boneMatrix);
  27376. position.setXYZ(j, _vector$2.x, _vector$2.y, _vector$2.z);
  27377. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
  27378. _vector$2.setFromMatrixPosition(_boneMatrix);
  27379. position.setXYZ(j + 1, _vector$2.x, _vector$2.y, _vector$2.z);
  27380. j += 2;
  27381. }
  27382. }
  27383. geometry.getAttribute('position').needsUpdate = true;
  27384. super.updateMatrixWorld(force);
  27385. }
  27386. }
  27387. function getBoneList(object) {
  27388. const boneList = [];
  27389. if (object && object.isBone) {
  27390. boneList.push(object);
  27391. }
  27392. for (let i = 0; i < object.children.length; i++) {
  27393. boneList.push.apply(boneList, getBoneList(object.children[i]));
  27394. }
  27395. return boneList;
  27396. }
  27397. class PointLightHelper extends Mesh {
  27398. constructor(light, sphereSize, color) {
  27399. const geometry = new SphereGeometry(sphereSize, 4, 2);
  27400. const material = new MeshBasicMaterial({
  27401. wireframe: true,
  27402. fog: false,
  27403. toneMapped: false
  27404. });
  27405. super(geometry, material);
  27406. this.light = light;
  27407. this.light.updateMatrixWorld();
  27408. this.color = color;
  27409. this.type = 'PointLightHelper';
  27410. this.matrix = this.light.matrixWorld;
  27411. this.matrixAutoUpdate = false;
  27412. this.update();
  27413. /*
  27414. // TODO: delete this comment?
  27415. const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  27416. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  27417. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  27418. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  27419. const d = light.distance;
  27420. if ( d === 0.0 ) {
  27421. this.lightDistance.visible = false;
  27422. } else {
  27423. this.lightDistance.scale.set( d, d, d );
  27424. }
  27425. this.add( this.lightDistance );
  27426. */
  27427. }
  27428. dispose() {
  27429. this.geometry.dispose();
  27430. this.material.dispose();
  27431. }
  27432. update() {
  27433. if (this.color !== undefined) {
  27434. this.material.color.set(this.color);
  27435. } else {
  27436. this.material.color.copy(this.light.color);
  27437. }
  27438. /*
  27439. const d = this.light.distance;
  27440. if ( d === 0.0 ) {
  27441. this.lightDistance.visible = false;
  27442. } else {
  27443. this.lightDistance.visible = true;
  27444. this.lightDistance.scale.set( d, d, d );
  27445. }
  27446. */
  27447. }
  27448. }
  27449. const _vector$1 = /*@__PURE__*/new Vector3();
  27450. const _color1 = /*@__PURE__*/new Color();
  27451. const _color2 = /*@__PURE__*/new Color();
  27452. class HemisphereLightHelper extends Object3D {
  27453. constructor(light, size, color) {
  27454. super();
  27455. this.light = light;
  27456. this.light.updateMatrixWorld();
  27457. this.matrix = light.matrixWorld;
  27458. this.matrixAutoUpdate = false;
  27459. this.color = color;
  27460. const geometry = new OctahedronGeometry(size);
  27461. geometry.rotateY(Math.PI * 0.5);
  27462. this.material = new MeshBasicMaterial({
  27463. wireframe: true,
  27464. fog: false,
  27465. toneMapped: false
  27466. });
  27467. if (this.color === undefined) this.material.vertexColors = true;
  27468. const position = geometry.getAttribute('position');
  27469. const colors = new Float32Array(position.count * 3);
  27470. geometry.setAttribute('color', new BufferAttribute(colors, 3));
  27471. this.add(new Mesh(geometry, this.material));
  27472. this.update();
  27473. }
  27474. dispose() {
  27475. this.children[0].geometry.dispose();
  27476. this.children[0].material.dispose();
  27477. }
  27478. update() {
  27479. const mesh = this.children[0];
  27480. if (this.color !== undefined) {
  27481. this.material.color.set(this.color);
  27482. } else {
  27483. const colors = mesh.geometry.getAttribute('color');
  27484. _color1.copy(this.light.color);
  27485. _color2.copy(this.light.groundColor);
  27486. for (let i = 0, l = colors.count; i < l; i++) {
  27487. const color = i < l / 2 ? _color1 : _color2;
  27488. colors.setXYZ(i, color.r, color.g, color.b);
  27489. }
  27490. colors.needsUpdate = true;
  27491. }
  27492. mesh.lookAt(_vector$1.setFromMatrixPosition(this.light.matrixWorld).negate());
  27493. }
  27494. }
  27495. class GridHelper extends LineSegments {
  27496. constructor(size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888) {
  27497. color1 = new Color(color1);
  27498. color2 = new Color(color2);
  27499. const center = divisions / 2;
  27500. const step = size / divisions;
  27501. const halfSize = size / 2;
  27502. const vertices = [],
  27503. colors = [];
  27504. for (let i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
  27505. vertices.push(-halfSize, 0, k, halfSize, 0, k);
  27506. vertices.push(k, 0, -halfSize, k, 0, halfSize);
  27507. const color = i === center ? color1 : color2;
  27508. color.toArray(colors, j);
  27509. j += 3;
  27510. color.toArray(colors, j);
  27511. j += 3;
  27512. color.toArray(colors, j);
  27513. j += 3;
  27514. color.toArray(colors, j);
  27515. j += 3;
  27516. }
  27517. const geometry = new BufferGeometry();
  27518. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27519. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27520. const material = new LineBasicMaterial({
  27521. vertexColors: true,
  27522. toneMapped: false
  27523. });
  27524. super(geometry, material);
  27525. this.type = 'GridHelper';
  27526. }
  27527. }
  27528. class PolarGridHelper extends LineSegments {
  27529. constructor(radius = 10, radials = 16, circles = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888) {
  27530. color1 = new Color(color1);
  27531. color2 = new Color(color2);
  27532. const vertices = [];
  27533. const colors = []; // create the radials
  27534. for (let i = 0; i <= radials; i++) {
  27535. const v = i / radials * (Math.PI * 2);
  27536. const x = Math.sin(v) * radius;
  27537. const z = Math.cos(v) * radius;
  27538. vertices.push(0, 0, 0);
  27539. vertices.push(x, 0, z);
  27540. const color = i & 1 ? color1 : color2;
  27541. colors.push(color.r, color.g, color.b);
  27542. colors.push(color.r, color.g, color.b);
  27543. } // create the circles
  27544. for (let i = 0; i <= circles; i++) {
  27545. const color = i & 1 ? color1 : color2;
  27546. const r = radius - radius / circles * i;
  27547. for (let j = 0; j < divisions; j++) {
  27548. // first vertex
  27549. let v = j / divisions * (Math.PI * 2);
  27550. let x = Math.sin(v) * r;
  27551. let z = Math.cos(v) * r;
  27552. vertices.push(x, 0, z);
  27553. colors.push(color.r, color.g, color.b); // second vertex
  27554. v = (j + 1) / divisions * (Math.PI * 2);
  27555. x = Math.sin(v) * r;
  27556. z = Math.cos(v) * r;
  27557. vertices.push(x, 0, z);
  27558. colors.push(color.r, color.g, color.b);
  27559. }
  27560. }
  27561. const geometry = new BufferGeometry();
  27562. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27563. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27564. const material = new LineBasicMaterial({
  27565. vertexColors: true,
  27566. toneMapped: false
  27567. });
  27568. super(geometry, material);
  27569. this.type = 'PolarGridHelper';
  27570. }
  27571. }
  27572. const _v1 = /*@__PURE__*/new Vector3();
  27573. const _v2 = /*@__PURE__*/new Vector3();
  27574. const _v3 = /*@__PURE__*/new Vector3();
  27575. class DirectionalLightHelper extends Object3D {
  27576. constructor(light, size, color) {
  27577. super();
  27578. this.light = light;
  27579. this.light.updateMatrixWorld();
  27580. this.matrix = light.matrixWorld;
  27581. this.matrixAutoUpdate = false;
  27582. this.color = color;
  27583. if (size === undefined) size = 1;
  27584. let geometry = new BufferGeometry();
  27585. geometry.setAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
  27586. const material = new LineBasicMaterial({
  27587. fog: false,
  27588. toneMapped: false
  27589. });
  27590. this.lightPlane = new Line(geometry, material);
  27591. this.add(this.lightPlane);
  27592. geometry = new BufferGeometry();
  27593. geometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
  27594. this.targetLine = new Line(geometry, material);
  27595. this.add(this.targetLine);
  27596. this.update();
  27597. }
  27598. dispose() {
  27599. this.lightPlane.geometry.dispose();
  27600. this.lightPlane.material.dispose();
  27601. this.targetLine.geometry.dispose();
  27602. this.targetLine.material.dispose();
  27603. }
  27604. update() {
  27605. _v1.setFromMatrixPosition(this.light.matrixWorld);
  27606. _v2.setFromMatrixPosition(this.light.target.matrixWorld);
  27607. _v3.subVectors(_v2, _v1);
  27608. this.lightPlane.lookAt(_v2);
  27609. if (this.color !== undefined) {
  27610. this.lightPlane.material.color.set(this.color);
  27611. this.targetLine.material.color.set(this.color);
  27612. } else {
  27613. this.lightPlane.material.color.copy(this.light.color);
  27614. this.targetLine.material.color.copy(this.light.color);
  27615. }
  27616. this.targetLine.lookAt(_v2);
  27617. this.targetLine.scale.z = _v3.length();
  27618. }
  27619. }
  27620. const _vector = /*@__PURE__*/new Vector3();
  27621. const _camera = /*@__PURE__*/new Camera();
  27622. /**
  27623. * - shows frustum, line of sight and up of the camera
  27624. * - suitable for fast updates
  27625. * - based on frustum visualization in lightgl.js shadowmap example
  27626. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  27627. */
  27628. class CameraHelper extends LineSegments {
  27629. constructor(camera) {
  27630. const geometry = new BufferGeometry();
  27631. const material = new LineBasicMaterial({
  27632. color: 0xffffff,
  27633. vertexColors: true,
  27634. toneMapped: false
  27635. });
  27636. const vertices = [];
  27637. const colors = [];
  27638. const pointMap = {}; // colors
  27639. const colorFrustum = new Color(0xffaa00);
  27640. const colorCone = new Color(0xff0000);
  27641. const colorUp = new Color(0x00aaff);
  27642. const colorTarget = new Color(0xffffff);
  27643. const colorCross = new Color(0x333333); // near
  27644. addLine('n1', 'n2', colorFrustum);
  27645. addLine('n2', 'n4', colorFrustum);
  27646. addLine('n4', 'n3', colorFrustum);
  27647. addLine('n3', 'n1', colorFrustum); // far
  27648. addLine('f1', 'f2', colorFrustum);
  27649. addLine('f2', 'f4', colorFrustum);
  27650. addLine('f4', 'f3', colorFrustum);
  27651. addLine('f3', 'f1', colorFrustum); // sides
  27652. addLine('n1', 'f1', colorFrustum);
  27653. addLine('n2', 'f2', colorFrustum);
  27654. addLine('n3', 'f3', colorFrustum);
  27655. addLine('n4', 'f4', colorFrustum); // cone
  27656. addLine('p', 'n1', colorCone);
  27657. addLine('p', 'n2', colorCone);
  27658. addLine('p', 'n3', colorCone);
  27659. addLine('p', 'n4', colorCone); // up
  27660. addLine('u1', 'u2', colorUp);
  27661. addLine('u2', 'u3', colorUp);
  27662. addLine('u3', 'u1', colorUp); // target
  27663. addLine('c', 't', colorTarget);
  27664. addLine('p', 'c', colorCross); // cross
  27665. addLine('cn1', 'cn2', colorCross);
  27666. addLine('cn3', 'cn4', colorCross);
  27667. addLine('cf1', 'cf2', colorCross);
  27668. addLine('cf3', 'cf4', colorCross);
  27669. function addLine(a, b, color) {
  27670. addPoint(a, color);
  27671. addPoint(b, color);
  27672. }
  27673. function addPoint(id, color) {
  27674. vertices.push(0, 0, 0);
  27675. colors.push(color.r, color.g, color.b);
  27676. if (pointMap[id] === undefined) {
  27677. pointMap[id] = [];
  27678. }
  27679. pointMap[id].push(vertices.length / 3 - 1);
  27680. }
  27681. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27682. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27683. super(geometry, material);
  27684. this.type = 'CameraHelper';
  27685. this.camera = camera;
  27686. if (this.camera.updateProjectionMatrix) this.camera.updateProjectionMatrix();
  27687. this.matrix = camera.matrixWorld;
  27688. this.matrixAutoUpdate = false;
  27689. this.pointMap = pointMap;
  27690. this.update();
  27691. }
  27692. update() {
  27693. const geometry = this.geometry;
  27694. const pointMap = this.pointMap;
  27695. const w = 1,
  27696. h = 1; // we need just camera projection matrix inverse
  27697. // world matrix must be identity
  27698. _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / target
  27699. setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
  27700. setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // near
  27701. setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
  27702. setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
  27703. setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
  27704. setPoint('n4', pointMap, geometry, _camera, w, h, -1); // far
  27705. setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
  27706. setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
  27707. setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
  27708. setPoint('f4', pointMap, geometry, _camera, w, h, 1); // up
  27709. setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
  27710. setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
  27711. setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // cross
  27712. setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
  27713. setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
  27714. setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
  27715. setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
  27716. setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
  27717. setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
  27718. setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
  27719. setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
  27720. geometry.getAttribute('position').needsUpdate = true;
  27721. }
  27722. dispose() {
  27723. this.geometry.dispose();
  27724. this.material.dispose();
  27725. }
  27726. }
  27727. function setPoint(point, pointMap, geometry, camera, x, y, z) {
  27728. _vector.set(x, y, z).unproject(camera);
  27729. const points = pointMap[point];
  27730. if (points !== undefined) {
  27731. const position = geometry.getAttribute('position');
  27732. for (let i = 0, l = points.length; i < l; i++) {
  27733. position.setXYZ(points[i], _vector.x, _vector.y, _vector.z);
  27734. }
  27735. }
  27736. }
  27737. const _box = /*@__PURE__*/new Box3();
  27738. class BoxHelper extends LineSegments {
  27739. constructor(object, color = 0xffff00) {
  27740. 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]);
  27741. const positions = new Float32Array(8 * 3);
  27742. const geometry = new BufferGeometry();
  27743. geometry.setIndex(new BufferAttribute(indices, 1));
  27744. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  27745. super(geometry, new LineBasicMaterial({
  27746. color: color,
  27747. toneMapped: false
  27748. }));
  27749. this.object = object;
  27750. this.type = 'BoxHelper';
  27751. this.matrixAutoUpdate = false;
  27752. this.update();
  27753. }
  27754. update(object) {
  27755. if (object !== undefined) {
  27756. console.warn('THREE.BoxHelper: .update() has no longer arguments.');
  27757. }
  27758. if (this.object !== undefined) {
  27759. _box.setFromObject(this.object);
  27760. }
  27761. if (_box.isEmpty()) return;
  27762. const min = _box.min;
  27763. const max = _box.max;
  27764. /*
  27765. 5____4
  27766. 1/___0/|
  27767. | 6__|_7
  27768. 2/___3/
  27769. 0: max.x, max.y, max.z
  27770. 1: min.x, max.y, max.z
  27771. 2: min.x, min.y, max.z
  27772. 3: max.x, min.y, max.z
  27773. 4: max.x, max.y, min.z
  27774. 5: min.x, max.y, min.z
  27775. 6: min.x, min.y, min.z
  27776. 7: max.x, min.y, min.z
  27777. */
  27778. const position = this.geometry.attributes.position;
  27779. const array = position.array;
  27780. array[0] = max.x;
  27781. array[1] = max.y;
  27782. array[2] = max.z;
  27783. array[3] = min.x;
  27784. array[4] = max.y;
  27785. array[5] = max.z;
  27786. array[6] = min.x;
  27787. array[7] = min.y;
  27788. array[8] = max.z;
  27789. array[9] = max.x;
  27790. array[10] = min.y;
  27791. array[11] = max.z;
  27792. array[12] = max.x;
  27793. array[13] = max.y;
  27794. array[14] = min.z;
  27795. array[15] = min.x;
  27796. array[16] = max.y;
  27797. array[17] = min.z;
  27798. array[18] = min.x;
  27799. array[19] = min.y;
  27800. array[20] = min.z;
  27801. array[21] = max.x;
  27802. array[22] = min.y;
  27803. array[23] = min.z;
  27804. position.needsUpdate = true;
  27805. this.geometry.computeBoundingSphere();
  27806. }
  27807. setFromObject(object) {
  27808. this.object = object;
  27809. this.update();
  27810. return this;
  27811. }
  27812. copy(source) {
  27813. LineSegments.prototype.copy.call(this, source);
  27814. this.object = source.object;
  27815. return this;
  27816. }
  27817. }
  27818. class Box3Helper extends LineSegments {
  27819. constructor(box, color = 0xffff00) {
  27820. 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]);
  27821. 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];
  27822. const geometry = new BufferGeometry();
  27823. geometry.setIndex(new BufferAttribute(indices, 1));
  27824. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  27825. super(geometry, new LineBasicMaterial({
  27826. color: color,
  27827. toneMapped: false
  27828. }));
  27829. this.box = box;
  27830. this.type = 'Box3Helper';
  27831. this.geometry.computeBoundingSphere();
  27832. }
  27833. updateMatrixWorld(force) {
  27834. const box = this.box;
  27835. if (box.isEmpty()) return;
  27836. box.getCenter(this.position);
  27837. box.getSize(this.scale);
  27838. this.scale.multiplyScalar(0.5);
  27839. super.updateMatrixWorld(force);
  27840. }
  27841. }
  27842. class PlaneHelper extends Line {
  27843. constructor(plane, size = 1, hex = 0xffff00) {
  27844. const color = hex;
  27845. 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];
  27846. const geometry = new BufferGeometry();
  27847. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  27848. geometry.computeBoundingSphere();
  27849. super(geometry, new LineBasicMaterial({
  27850. color: color,
  27851. toneMapped: false
  27852. }));
  27853. this.type = 'PlaneHelper';
  27854. this.plane = plane;
  27855. this.size = size;
  27856. const positions2 = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1];
  27857. const geometry2 = new BufferGeometry();
  27858. geometry2.setAttribute('position', new Float32BufferAttribute(positions2, 3));
  27859. geometry2.computeBoundingSphere();
  27860. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  27861. color: color,
  27862. opacity: 0.2,
  27863. transparent: true,
  27864. depthWrite: false,
  27865. toneMapped: false
  27866. })));
  27867. }
  27868. updateMatrixWorld(force) {
  27869. let scale = -this.plane.constant;
  27870. if (Math.abs(scale) < 1e-8) scale = 1e-8; // sign does not matter
  27871. this.scale.set(0.5 * this.size, 0.5 * this.size, scale);
  27872. this.children[0].material.side = scale < 0 ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  27873. this.lookAt(this.plane.normal);
  27874. super.updateMatrixWorld(force);
  27875. }
  27876. }
  27877. const _axis = /*@__PURE__*/new Vector3();
  27878. let _lineGeometry, _coneGeometry;
  27879. class ArrowHelper extends Object3D {
  27880. // dir is assumed to be normalized
  27881. 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) {
  27882. super();
  27883. this.type = 'ArrowHelper';
  27884. if (_lineGeometry === undefined) {
  27885. _lineGeometry = new BufferGeometry();
  27886. _lineGeometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
  27887. _coneGeometry = new CylinderGeometry(0, 0.5, 1, 5, 1);
  27888. _coneGeometry.translate(0, -0.5, 0);
  27889. }
  27890. this.position.copy(origin);
  27891. this.line = new Line(_lineGeometry, new LineBasicMaterial({
  27892. color: color,
  27893. toneMapped: false
  27894. }));
  27895. this.line.matrixAutoUpdate = false;
  27896. this.add(this.line);
  27897. this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
  27898. color: color,
  27899. toneMapped: false
  27900. }));
  27901. this.cone.matrixAutoUpdate = false;
  27902. this.add(this.cone);
  27903. this.setDirection(dir);
  27904. this.setLength(length, headLength, headWidth);
  27905. }
  27906. setDirection(dir) {
  27907. // dir is assumed to be normalized
  27908. if (dir.y > 0.99999) {
  27909. this.quaternion.set(0, 0, 0, 1);
  27910. } else if (dir.y < -0.99999) {
  27911. this.quaternion.set(1, 0, 0, 0);
  27912. } else {
  27913. _axis.set(dir.z, 0, -dir.x).normalize();
  27914. const radians = Math.acos(dir.y);
  27915. this.quaternion.setFromAxisAngle(_axis, radians);
  27916. }
  27917. }
  27918. setLength(length, headLength = length * 0.2, headWidth = headLength * 0.2) {
  27919. this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
  27920. this.line.updateMatrix();
  27921. this.cone.scale.set(headWidth, headLength, headWidth);
  27922. this.cone.position.y = length;
  27923. this.cone.updateMatrix();
  27924. }
  27925. setColor(color) {
  27926. this.line.material.color.set(color);
  27927. this.cone.material.color.set(color);
  27928. }
  27929. copy(source) {
  27930. super.copy(source, false);
  27931. this.line.copy(source.line);
  27932. this.cone.copy(source.cone);
  27933. return this;
  27934. }
  27935. }
  27936. class AxesHelper extends LineSegments {
  27937. constructor(size = 1) {
  27938. const vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
  27939. const colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
  27940. const geometry = new BufferGeometry();
  27941. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27942. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27943. const material = new LineBasicMaterial({
  27944. vertexColors: true,
  27945. toneMapped: false
  27946. });
  27947. super(geometry, material);
  27948. this.type = 'AxesHelper';
  27949. }
  27950. setColors(xAxisColor, yAxisColor, zAxisColor) {
  27951. const color = new Color();
  27952. const array = this.geometry.attributes.color.array;
  27953. color.set(xAxisColor);
  27954. color.toArray(array, 0);
  27955. color.toArray(array, 3);
  27956. color.set(yAxisColor);
  27957. color.toArray(array, 6);
  27958. color.toArray(array, 9);
  27959. color.set(zAxisColor);
  27960. color.toArray(array, 12);
  27961. color.toArray(array, 15);
  27962. this.geometry.attributes.color.needsUpdate = true;
  27963. return this;
  27964. }
  27965. dispose() {
  27966. this.geometry.dispose();
  27967. this.material.dispose();
  27968. }
  27969. }
  27970. class ShapePath {
  27971. constructor() {
  27972. this.type = 'ShapePath';
  27973. this.color = new Color();
  27974. this.subPaths = [];
  27975. this.currentPath = null;
  27976. }
  27977. moveTo(x, y) {
  27978. this.currentPath = new Path();
  27979. this.subPaths.push(this.currentPath);
  27980. this.currentPath.moveTo(x, y);
  27981. return this;
  27982. }
  27983. lineTo(x, y) {
  27984. this.currentPath.lineTo(x, y);
  27985. return this;
  27986. }
  27987. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  27988. this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
  27989. return this;
  27990. }
  27991. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  27992. this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
  27993. return this;
  27994. }
  27995. splineThru(pts) {
  27996. this.currentPath.splineThru(pts);
  27997. return this;
  27998. }
  27999. toShapes(isCCW, noHoles) {
  28000. function toShapesNoHoles(inSubpaths) {
  28001. const shapes = [];
  28002. for (let i = 0, l = inSubpaths.length; i < l; i++) {
  28003. const tmpPath = inSubpaths[i];
  28004. const tmpShape = new Shape();
  28005. tmpShape.curves = tmpPath.curves;
  28006. shapes.push(tmpShape);
  28007. }
  28008. return shapes;
  28009. }
  28010. function isPointInsidePolygon(inPt, inPolygon) {
  28011. const polyLen = inPolygon.length; // inPt on polygon contour => immediate success or
  28012. // toggling of inside/outside at every single! intersection point of an edge
  28013. // with the horizontal line through inPt, left of inPt
  28014. // not counting lowerY endpoints of edges and whole edges on that line
  28015. let inside = false;
  28016. for (let p = polyLen - 1, q = 0; q < polyLen; p = q++) {
  28017. let edgeLowPt = inPolygon[p];
  28018. let edgeHighPt = inPolygon[q];
  28019. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  28020. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  28021. if (Math.abs(edgeDy) > Number.EPSILON) {
  28022. // not parallel
  28023. if (edgeDy < 0) {
  28024. edgeLowPt = inPolygon[q];
  28025. edgeDx = -edgeDx;
  28026. edgeHighPt = inPolygon[p];
  28027. edgeDy = -edgeDy;
  28028. }
  28029. if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
  28030. if (inPt.y === edgeLowPt.y) {
  28031. if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
  28032. // continue; // no intersection or edgeLowPt => doesn't count !!!
  28033. } else {
  28034. const perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  28035. if (perpEdge === 0) return true; // inPt is on contour ?
  28036. if (perpEdge < 0) continue;
  28037. inside = !inside; // true intersection left of inPt
  28038. }
  28039. } else {
  28040. // parallel or collinear
  28041. if (inPt.y !== edgeLowPt.y) continue; // parallel
  28042. // edge lies on the same horizontal line as inPt
  28043. if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
  28044. // continue;
  28045. }
  28046. }
  28047. return inside;
  28048. }
  28049. const isClockWise = ShapeUtils.isClockWise;
  28050. const subPaths = this.subPaths;
  28051. if (subPaths.length === 0) return [];
  28052. if (noHoles === true) return toShapesNoHoles(subPaths);
  28053. let solid, tmpPath, tmpShape;
  28054. const shapes = [];
  28055. if (subPaths.length === 1) {
  28056. tmpPath = subPaths[0];
  28057. tmpShape = new Shape();
  28058. tmpShape.curves = tmpPath.curves;
  28059. shapes.push(tmpShape);
  28060. return shapes;
  28061. }
  28062. let holesFirst = !isClockWise(subPaths[0].getPoints());
  28063. holesFirst = isCCW ? !holesFirst : holesFirst; // console.log("Holes first", holesFirst);
  28064. const betterShapeHoles = [];
  28065. const newShapes = [];
  28066. let newShapeHoles = [];
  28067. let mainIdx = 0;
  28068. let tmpPoints;
  28069. newShapes[mainIdx] = undefined;
  28070. newShapeHoles[mainIdx] = [];
  28071. for (let i = 0, l = subPaths.length; i < l; i++) {
  28072. tmpPath = subPaths[i];
  28073. tmpPoints = tmpPath.getPoints();
  28074. solid = isClockWise(tmpPoints);
  28075. solid = isCCW ? !solid : solid;
  28076. if (solid) {
  28077. if (!holesFirst && newShapes[mainIdx]) mainIdx++;
  28078. newShapes[mainIdx] = {
  28079. s: new Shape(),
  28080. p: tmpPoints
  28081. };
  28082. newShapes[mainIdx].s.curves = tmpPath.curves;
  28083. if (holesFirst) mainIdx++;
  28084. newShapeHoles[mainIdx] = []; //console.log('cw', i);
  28085. } else {
  28086. newShapeHoles[mainIdx].push({
  28087. h: tmpPath,
  28088. p: tmpPoints[0]
  28089. }); //console.log('ccw', i);
  28090. }
  28091. } // only Holes? -> probably all Shapes with wrong orientation
  28092. if (!newShapes[0]) return toShapesNoHoles(subPaths);
  28093. if (newShapes.length > 1) {
  28094. let ambiguous = false;
  28095. const toChange = [];
  28096. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  28097. betterShapeHoles[sIdx] = [];
  28098. }
  28099. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  28100. const sho = newShapeHoles[sIdx];
  28101. for (let hIdx = 0; hIdx < sho.length; hIdx++) {
  28102. const ho = sho[hIdx];
  28103. let hole_unassigned = true;
  28104. for (let s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
  28105. if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
  28106. if (sIdx !== s2Idx) toChange.push({
  28107. froms: sIdx,
  28108. tos: s2Idx,
  28109. hole: hIdx
  28110. });
  28111. if (hole_unassigned) {
  28112. hole_unassigned = false;
  28113. betterShapeHoles[s2Idx].push(ho);
  28114. } else {
  28115. ambiguous = true;
  28116. }
  28117. }
  28118. }
  28119. if (hole_unassigned) {
  28120. betterShapeHoles[sIdx].push(ho);
  28121. }
  28122. }
  28123. } // console.log("ambiguous: ", ambiguous);
  28124. if (toChange.length > 0) {
  28125. // console.log("to change: ", toChange);
  28126. if (!ambiguous) newShapeHoles = betterShapeHoles;
  28127. }
  28128. }
  28129. let tmpHoles;
  28130. for (let i = 0, il = newShapes.length; i < il; i++) {
  28131. tmpShape = newShapes[i].s;
  28132. shapes.push(tmpShape);
  28133. tmpHoles = newShapeHoles[i];
  28134. for (let j = 0, jl = tmpHoles.length; j < jl; j++) {
  28135. tmpShape.holes.push(tmpHoles[j].h);
  28136. }
  28137. } //console.log("shape", shapes);
  28138. return shapes;
  28139. }
  28140. }
  28141. const _floatView = new Float32Array(1);
  28142. const _int32View = new Int32Array(_floatView.buffer);
  28143. class DataUtils {
  28144. // Converts float32 to float16 (stored as uint16 value).
  28145. static toHalfFloat(val) {
  28146. if (val > 65504) {
  28147. console.warn('THREE.DataUtils.toHalfFloat(): value exceeds 65504.');
  28148. val = 65504; // maximum representable value in float16
  28149. } // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
  28150. /* This method is faster than the OpenEXR implementation (very often
  28151. * used, eg. in Ogre), with the additional benefit of rounding, inspired
  28152. * by James Tursa?s half-precision code. */
  28153. _floatView[0] = val;
  28154. const x = _int32View[0];
  28155. let bits = x >> 16 & 0x8000;
  28156. /* Get the sign */
  28157. let m = x >> 12 & 0x07ff;
  28158. /* Keep one extra bit for rounding */
  28159. const e = x >> 23 & 0xff;
  28160. /* Using int is faster here */
  28161. /* If zero, or denormal, or exponent underflows too much for a denormal
  28162. * half, return signed zero. */
  28163. if (e < 103) return bits;
  28164. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  28165. if (e > 142) {
  28166. bits |= 0x7c00;
  28167. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  28168. * not Inf, so make sure we set one mantissa bit too. */
  28169. bits |= (e == 255 ? 0 : 1) && x & 0x007fffff;
  28170. return bits;
  28171. }
  28172. /* If exponent underflows but not too much, return a denormal */
  28173. if (e < 113) {
  28174. m |= 0x0800;
  28175. /* Extra rounding may overflow and set mantissa to 0 and exponent
  28176. * to 1, which is OK. */
  28177. bits |= (m >> 114 - e) + (m >> 113 - e & 1);
  28178. return bits;
  28179. }
  28180. bits |= e - 112 << 10 | m >> 1;
  28181. /* Extra rounding. An overflow will set mantissa to 0 and increment
  28182. * the exponent, which is OK. */
  28183. bits += m & 1;
  28184. return bits;
  28185. }
  28186. }
  28187. const LineStrip = 0;
  28188. const LinePieces = 1;
  28189. const NoColors = 0;
  28190. const FaceColors = 1;
  28191. const VertexColors = 2;
  28192. function MeshFaceMaterial(materials) {
  28193. console.warn('THREE.MeshFaceMaterial has been removed. Use an Array instead.');
  28194. return materials;
  28195. }
  28196. function MultiMaterial(materials = []) {
  28197. console.warn('THREE.MultiMaterial has been removed. Use an Array instead.');
  28198. materials.isMultiMaterial = true;
  28199. materials.materials = materials;
  28200. materials.clone = function () {
  28201. return materials.slice();
  28202. };
  28203. return materials;
  28204. }
  28205. function PointCloud(geometry, material) {
  28206. console.warn('THREE.PointCloud has been renamed to THREE.Points.');
  28207. return new Points(geometry, material);
  28208. }
  28209. function Particle(material) {
  28210. console.warn('THREE.Particle has been renamed to THREE.Sprite.');
  28211. return new Sprite(material);
  28212. }
  28213. function ParticleSystem(geometry, material) {
  28214. console.warn('THREE.ParticleSystem has been renamed to THREE.Points.');
  28215. return new Points(geometry, material);
  28216. }
  28217. function PointCloudMaterial(parameters) {
  28218. console.warn('THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.');
  28219. return new PointsMaterial(parameters);
  28220. }
  28221. function ParticleBasicMaterial(parameters) {
  28222. console.warn('THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.');
  28223. return new PointsMaterial(parameters);
  28224. }
  28225. function ParticleSystemMaterial(parameters) {
  28226. console.warn('THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.');
  28227. return new PointsMaterial(parameters);
  28228. }
  28229. function Vertex(x, y, z) {
  28230. console.warn('THREE.Vertex has been removed. Use THREE.Vector3 instead.');
  28231. return new Vector3(x, y, z);
  28232. } //
  28233. function DynamicBufferAttribute(array, itemSize) {
  28234. console.warn('THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.');
  28235. return new BufferAttribute(array, itemSize).setUsage(DynamicDrawUsage);
  28236. }
  28237. function Int8Attribute(array, itemSize) {
  28238. console.warn('THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.');
  28239. return new Int8BufferAttribute(array, itemSize);
  28240. }
  28241. function Uint8Attribute(array, itemSize) {
  28242. console.warn('THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.');
  28243. return new Uint8BufferAttribute(array, itemSize);
  28244. }
  28245. function Uint8ClampedAttribute(array, itemSize) {
  28246. console.warn('THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.');
  28247. return new Uint8ClampedBufferAttribute(array, itemSize);
  28248. }
  28249. function Int16Attribute(array, itemSize) {
  28250. console.warn('THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.');
  28251. return new Int16BufferAttribute(array, itemSize);
  28252. }
  28253. function Uint16Attribute(array, itemSize) {
  28254. console.warn('THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.');
  28255. return new Uint16BufferAttribute(array, itemSize);
  28256. }
  28257. function Int32Attribute(array, itemSize) {
  28258. console.warn('THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.');
  28259. return new Int32BufferAttribute(array, itemSize);
  28260. }
  28261. function Uint32Attribute(array, itemSize) {
  28262. console.warn('THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.');
  28263. return new Uint32BufferAttribute(array, itemSize);
  28264. }
  28265. function Float32Attribute(array, itemSize) {
  28266. console.warn('THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.');
  28267. return new Float32BufferAttribute(array, itemSize);
  28268. }
  28269. function Float64Attribute(array, itemSize) {
  28270. console.warn('THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.');
  28271. return new Float64BufferAttribute(array, itemSize);
  28272. } //
  28273. Curve.create = function (construct, getPoint) {
  28274. console.log('THREE.Curve.create() has been deprecated');
  28275. construct.prototype = Object.create(Curve.prototype);
  28276. construct.prototype.constructor = construct;
  28277. construct.prototype.getPoint = getPoint;
  28278. return construct;
  28279. }; //
  28280. Path.prototype.fromPoints = function (points) {
  28281. console.warn('THREE.Path: .fromPoints() has been renamed to .setFromPoints().');
  28282. return this.setFromPoints(points);
  28283. }; //
  28284. function AxisHelper(size) {
  28285. console.warn('THREE.AxisHelper has been renamed to THREE.AxesHelper.');
  28286. return new AxesHelper(size);
  28287. }
  28288. function BoundingBoxHelper(object, color) {
  28289. console.warn('THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.');
  28290. return new BoxHelper(object, color);
  28291. }
  28292. function EdgesHelper(object, hex) {
  28293. console.warn('THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.');
  28294. return new LineSegments(new EdgesGeometry(object.geometry), new LineBasicMaterial({
  28295. color: hex !== undefined ? hex : 0xffffff
  28296. }));
  28297. }
  28298. GridHelper.prototype.setColors = function () {
  28299. console.error('THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.');
  28300. };
  28301. SkeletonHelper.prototype.update = function () {
  28302. console.error('THREE.SkeletonHelper: update() no longer needs to be called.');
  28303. };
  28304. function WireframeHelper(object, hex) {
  28305. console.warn('THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.');
  28306. return new LineSegments(new WireframeGeometry(object.geometry), new LineBasicMaterial({
  28307. color: hex !== undefined ? hex : 0xffffff
  28308. }));
  28309. } //
  28310. Loader.prototype.extractUrlBase = function (url) {
  28311. console.warn('THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.');
  28312. return LoaderUtils.extractUrlBase(url);
  28313. };
  28314. Loader.Handlers = {
  28315. add: function () {
  28316. console.error('THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.');
  28317. },
  28318. get: function () {
  28319. console.error('THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.');
  28320. }
  28321. };
  28322. function XHRLoader(manager) {
  28323. console.warn('THREE.XHRLoader has been renamed to THREE.FileLoader.');
  28324. return new FileLoader(manager);
  28325. }
  28326. function BinaryTextureLoader(manager) {
  28327. console.warn('THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.');
  28328. return new DataTextureLoader(manager);
  28329. } //
  28330. Box2.prototype.center = function (optionalTarget) {
  28331. console.warn('THREE.Box2: .center() has been renamed to .getCenter().');
  28332. return this.getCenter(optionalTarget);
  28333. };
  28334. Box2.prototype.empty = function () {
  28335. console.warn('THREE.Box2: .empty() has been renamed to .isEmpty().');
  28336. return this.isEmpty();
  28337. };
  28338. Box2.prototype.isIntersectionBox = function (box) {
  28339. console.warn('THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().');
  28340. return this.intersectsBox(box);
  28341. };
  28342. Box2.prototype.size = function (optionalTarget) {
  28343. console.warn('THREE.Box2: .size() has been renamed to .getSize().');
  28344. return this.getSize(optionalTarget);
  28345. }; //
  28346. Box3.prototype.center = function (optionalTarget) {
  28347. console.warn('THREE.Box3: .center() has been renamed to .getCenter().');
  28348. return this.getCenter(optionalTarget);
  28349. };
  28350. Box3.prototype.empty = function () {
  28351. console.warn('THREE.Box3: .empty() has been renamed to .isEmpty().');
  28352. return this.isEmpty();
  28353. };
  28354. Box3.prototype.isIntersectionBox = function (box) {
  28355. console.warn('THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().');
  28356. return this.intersectsBox(box);
  28357. };
  28358. Box3.prototype.isIntersectionSphere = function (sphere) {
  28359. console.warn('THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  28360. return this.intersectsSphere(sphere);
  28361. };
  28362. Box3.prototype.size = function (optionalTarget) {
  28363. console.warn('THREE.Box3: .size() has been renamed to .getSize().');
  28364. return this.getSize(optionalTarget);
  28365. }; //
  28366. Sphere.prototype.empty = function () {
  28367. console.warn('THREE.Sphere: .empty() has been renamed to .isEmpty().');
  28368. return this.isEmpty();
  28369. }; //
  28370. Frustum.prototype.setFromMatrix = function (m) {
  28371. console.warn('THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().');
  28372. return this.setFromProjectionMatrix(m);
  28373. }; //
  28374. Line3.prototype.center = function (optionalTarget) {
  28375. console.warn('THREE.Line3: .center() has been renamed to .getCenter().');
  28376. return this.getCenter(optionalTarget);
  28377. }; //
  28378. Matrix3.prototype.flattenToArrayOffset = function (array, offset) {
  28379. console.warn('THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');
  28380. return this.toArray(array, offset);
  28381. };
  28382. Matrix3.prototype.multiplyVector3 = function (vector) {
  28383. console.warn('THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.');
  28384. return vector.applyMatrix3(this);
  28385. };
  28386. Matrix3.prototype.multiplyVector3Array = function () {
  28387. console.error('THREE.Matrix3: .multiplyVector3Array() has been removed.');
  28388. };
  28389. Matrix3.prototype.applyToBufferAttribute = function (attribute) {
  28390. console.warn('THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.');
  28391. return attribute.applyMatrix3(this);
  28392. };
  28393. Matrix3.prototype.applyToVector3Array = function () {
  28394. console.error('THREE.Matrix3: .applyToVector3Array() has been removed.');
  28395. };
  28396. Matrix3.prototype.getInverse = function (matrix) {
  28397. console.warn('THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  28398. return this.copy(matrix).invert();
  28399. }; //
  28400. Matrix4.prototype.extractPosition = function (m) {
  28401. console.warn('THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().');
  28402. return this.copyPosition(m);
  28403. };
  28404. Matrix4.prototype.flattenToArrayOffset = function (array, offset) {
  28405. console.warn('THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');
  28406. return this.toArray(array, offset);
  28407. };
  28408. Matrix4.prototype.getPosition = function () {
  28409. console.warn('THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.');
  28410. return new Vector3().setFromMatrixColumn(this, 3);
  28411. };
  28412. Matrix4.prototype.setRotationFromQuaternion = function (q) {
  28413. console.warn('THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().');
  28414. return this.makeRotationFromQuaternion(q);
  28415. };
  28416. Matrix4.prototype.multiplyToArray = function () {
  28417. console.warn('THREE.Matrix4: .multiplyToArray() has been removed.');
  28418. };
  28419. Matrix4.prototype.multiplyVector3 = function (vector) {
  28420. console.warn('THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  28421. return vector.applyMatrix4(this);
  28422. };
  28423. Matrix4.prototype.multiplyVector4 = function (vector) {
  28424. console.warn('THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  28425. return vector.applyMatrix4(this);
  28426. };
  28427. Matrix4.prototype.multiplyVector3Array = function () {
  28428. console.error('THREE.Matrix4: .multiplyVector3Array() has been removed.');
  28429. };
  28430. Matrix4.prototype.rotateAxis = function (v) {
  28431. console.warn('THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.');
  28432. v.transformDirection(this);
  28433. };
  28434. Matrix4.prototype.crossVector = function (vector) {
  28435. console.warn('THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  28436. return vector.applyMatrix4(this);
  28437. };
  28438. Matrix4.prototype.translate = function () {
  28439. console.error('THREE.Matrix4: .translate() has been removed.');
  28440. };
  28441. Matrix4.prototype.rotateX = function () {
  28442. console.error('THREE.Matrix4: .rotateX() has been removed.');
  28443. };
  28444. Matrix4.prototype.rotateY = function () {
  28445. console.error('THREE.Matrix4: .rotateY() has been removed.');
  28446. };
  28447. Matrix4.prototype.rotateZ = function () {
  28448. console.error('THREE.Matrix4: .rotateZ() has been removed.');
  28449. };
  28450. Matrix4.prototype.rotateByAxis = function () {
  28451. console.error('THREE.Matrix4: .rotateByAxis() has been removed.');
  28452. };
  28453. Matrix4.prototype.applyToBufferAttribute = function (attribute) {
  28454. console.warn('THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.');
  28455. return attribute.applyMatrix4(this);
  28456. };
  28457. Matrix4.prototype.applyToVector3Array = function () {
  28458. console.error('THREE.Matrix4: .applyToVector3Array() has been removed.');
  28459. };
  28460. Matrix4.prototype.makeFrustum = function (left, right, bottom, top, near, far) {
  28461. console.warn('THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.');
  28462. return this.makePerspective(left, right, top, bottom, near, far);
  28463. };
  28464. Matrix4.prototype.getInverse = function (matrix) {
  28465. console.warn('THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  28466. return this.copy(matrix).invert();
  28467. }; //
  28468. Plane.prototype.isIntersectionLine = function (line) {
  28469. console.warn('THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().');
  28470. return this.intersectsLine(line);
  28471. }; //
  28472. Quaternion.prototype.multiplyVector3 = function (vector) {
  28473. console.warn('THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.');
  28474. return vector.applyQuaternion(this);
  28475. };
  28476. Quaternion.prototype.inverse = function () {
  28477. console.warn('THREE.Quaternion: .inverse() has been renamed to invert().');
  28478. return this.invert();
  28479. }; //
  28480. Ray.prototype.isIntersectionBox = function (box) {
  28481. console.warn('THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().');
  28482. return this.intersectsBox(box);
  28483. };
  28484. Ray.prototype.isIntersectionPlane = function (plane) {
  28485. console.warn('THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().');
  28486. return this.intersectsPlane(plane);
  28487. };
  28488. Ray.prototype.isIntersectionSphere = function (sphere) {
  28489. console.warn('THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  28490. return this.intersectsSphere(sphere);
  28491. }; //
  28492. Triangle.prototype.area = function () {
  28493. console.warn('THREE.Triangle: .area() has been renamed to .getArea().');
  28494. return this.getArea();
  28495. };
  28496. Triangle.prototype.barycoordFromPoint = function (point, target) {
  28497. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  28498. return this.getBarycoord(point, target);
  28499. };
  28500. Triangle.prototype.midpoint = function (target) {
  28501. console.warn('THREE.Triangle: .midpoint() has been renamed to .getMidpoint().');
  28502. return this.getMidpoint(target);
  28503. };
  28504. Triangle.prototypenormal = function (target) {
  28505. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  28506. return this.getNormal(target);
  28507. };
  28508. Triangle.prototype.plane = function (target) {
  28509. console.warn('THREE.Triangle: .plane() has been renamed to .getPlane().');
  28510. return this.getPlane(target);
  28511. };
  28512. Triangle.barycoordFromPoint = function (point, a, b, c, target) {
  28513. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  28514. return Triangle.getBarycoord(point, a, b, c, target);
  28515. };
  28516. Triangle.normal = function (a, b, c, target) {
  28517. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  28518. return Triangle.getNormal(a, b, c, target);
  28519. }; //
  28520. Shape.prototype.extractAllPoints = function (divisions) {
  28521. console.warn('THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.');
  28522. return this.extractPoints(divisions);
  28523. };
  28524. Shape.prototype.extrude = function (options) {
  28525. console.warn('THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.');
  28526. return new ExtrudeGeometry(this, options);
  28527. };
  28528. Shape.prototype.makeGeometry = function (options) {
  28529. console.warn('THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.');
  28530. return new ShapeGeometry(this, options);
  28531. }; //
  28532. Vector2.prototype.fromAttribute = function (attribute, index, offset) {
  28533. console.warn('THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28534. return this.fromBufferAttribute(attribute, index, offset);
  28535. };
  28536. Vector2.prototype.distanceToManhattan = function (v) {
  28537. console.warn('THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  28538. return this.manhattanDistanceTo(v);
  28539. };
  28540. Vector2.prototype.lengthManhattan = function () {
  28541. console.warn('THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().');
  28542. return this.manhattanLength();
  28543. }; //
  28544. Vector3.prototype.setEulerFromRotationMatrix = function () {
  28545. console.error('THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.');
  28546. };
  28547. Vector3.prototype.setEulerFromQuaternion = function () {
  28548. console.error('THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.');
  28549. };
  28550. Vector3.prototype.getPositionFromMatrix = function (m) {
  28551. console.warn('THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().');
  28552. return this.setFromMatrixPosition(m);
  28553. };
  28554. Vector3.prototype.getScaleFromMatrix = function (m) {
  28555. console.warn('THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().');
  28556. return this.setFromMatrixScale(m);
  28557. };
  28558. Vector3.prototype.getColumnFromMatrix = function (index, matrix) {
  28559. console.warn('THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().');
  28560. return this.setFromMatrixColumn(matrix, index);
  28561. };
  28562. Vector3.prototype.applyProjection = function (m) {
  28563. console.warn('THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.');
  28564. return this.applyMatrix4(m);
  28565. };
  28566. Vector3.prototype.fromAttribute = function (attribute, index, offset) {
  28567. console.warn('THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28568. return this.fromBufferAttribute(attribute, index, offset);
  28569. };
  28570. Vector3.prototype.distanceToManhattan = function (v) {
  28571. console.warn('THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  28572. return this.manhattanDistanceTo(v);
  28573. };
  28574. Vector3.prototype.lengthManhattan = function () {
  28575. console.warn('THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().');
  28576. return this.manhattanLength();
  28577. }; //
  28578. Vector4.prototype.fromAttribute = function (attribute, index, offset) {
  28579. console.warn('THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28580. return this.fromBufferAttribute(attribute, index, offset);
  28581. };
  28582. Vector4.prototype.lengthManhattan = function () {
  28583. console.warn('THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().');
  28584. return this.manhattanLength();
  28585. }; //
  28586. Object3D.prototype.getChildByName = function (name) {
  28587. console.warn('THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().');
  28588. return this.getObjectByName(name);
  28589. };
  28590. Object3D.prototype.renderDepth = function () {
  28591. console.warn('THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.');
  28592. };
  28593. Object3D.prototype.translate = function (distance, axis) {
  28594. console.warn('THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.');
  28595. return this.translateOnAxis(axis, distance);
  28596. };
  28597. Object3D.prototype.getWorldRotation = function () {
  28598. console.error('THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.');
  28599. };
  28600. Object3D.prototype.applyMatrix = function (matrix) {
  28601. console.warn('THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().');
  28602. return this.applyMatrix4(matrix);
  28603. };
  28604. Object.defineProperties(Object3D.prototype, {
  28605. eulerOrder: {
  28606. get: function () {
  28607. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  28608. return this.rotation.order;
  28609. },
  28610. set: function (value) {
  28611. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  28612. this.rotation.order = value;
  28613. }
  28614. },
  28615. useQuaternion: {
  28616. get: function () {
  28617. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  28618. },
  28619. set: function () {
  28620. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  28621. }
  28622. }
  28623. });
  28624. Mesh.prototype.setDrawMode = function () {
  28625. console.error('THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  28626. };
  28627. Object.defineProperties(Mesh.prototype, {
  28628. drawMode: {
  28629. get: function () {
  28630. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.');
  28631. return TrianglesDrawMode;
  28632. },
  28633. set: function () {
  28634. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  28635. }
  28636. }
  28637. });
  28638. SkinnedMesh.prototype.initBones = function () {
  28639. console.error('THREE.SkinnedMesh: initBones() has been removed.');
  28640. }; //
  28641. PerspectiveCamera.prototype.setLens = function (focalLength, filmGauge) {
  28642. console.warn('THREE.PerspectiveCamera.setLens is deprecated. ' + 'Use .setFocalLength and .filmGauge for a photographic setup.');
  28643. if (filmGauge !== undefined) this.filmGauge = filmGauge;
  28644. this.setFocalLength(focalLength);
  28645. }; //
  28646. Object.defineProperties(Light.prototype, {
  28647. onlyShadow: {
  28648. set: function () {
  28649. console.warn('THREE.Light: .onlyShadow has been removed.');
  28650. }
  28651. },
  28652. shadowCameraFov: {
  28653. set: function (value) {
  28654. console.warn('THREE.Light: .shadowCameraFov is now .shadow.camera.fov.');
  28655. this.shadow.camera.fov = value;
  28656. }
  28657. },
  28658. shadowCameraLeft: {
  28659. set: function (value) {
  28660. console.warn('THREE.Light: .shadowCameraLeft is now .shadow.camera.left.');
  28661. this.shadow.camera.left = value;
  28662. }
  28663. },
  28664. shadowCameraRight: {
  28665. set: function (value) {
  28666. console.warn('THREE.Light: .shadowCameraRight is now .shadow.camera.right.');
  28667. this.shadow.camera.right = value;
  28668. }
  28669. },
  28670. shadowCameraTop: {
  28671. set: function (value) {
  28672. console.warn('THREE.Light: .shadowCameraTop is now .shadow.camera.top.');
  28673. this.shadow.camera.top = value;
  28674. }
  28675. },
  28676. shadowCameraBottom: {
  28677. set: function (value) {
  28678. console.warn('THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.');
  28679. this.shadow.camera.bottom = value;
  28680. }
  28681. },
  28682. shadowCameraNear: {
  28683. set: function (value) {
  28684. console.warn('THREE.Light: .shadowCameraNear is now .shadow.camera.near.');
  28685. this.shadow.camera.near = value;
  28686. }
  28687. },
  28688. shadowCameraFar: {
  28689. set: function (value) {
  28690. console.warn('THREE.Light: .shadowCameraFar is now .shadow.camera.far.');
  28691. this.shadow.camera.far = value;
  28692. }
  28693. },
  28694. shadowCameraVisible: {
  28695. set: function () {
  28696. console.warn('THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.');
  28697. }
  28698. },
  28699. shadowBias: {
  28700. set: function (value) {
  28701. console.warn('THREE.Light: .shadowBias is now .shadow.bias.');
  28702. this.shadow.bias = value;
  28703. }
  28704. },
  28705. shadowDarkness: {
  28706. set: function () {
  28707. console.warn('THREE.Light: .shadowDarkness has been removed.');
  28708. }
  28709. },
  28710. shadowMapWidth: {
  28711. set: function (value) {
  28712. console.warn('THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.');
  28713. this.shadow.mapSize.width = value;
  28714. }
  28715. },
  28716. shadowMapHeight: {
  28717. set: function (value) {
  28718. console.warn('THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.');
  28719. this.shadow.mapSize.height = value;
  28720. }
  28721. }
  28722. }); //
  28723. Object.defineProperties(BufferAttribute.prototype, {
  28724. length: {
  28725. get: function () {
  28726. console.warn('THREE.BufferAttribute: .length has been deprecated. Use .count instead.');
  28727. return this.array.length;
  28728. }
  28729. },
  28730. dynamic: {
  28731. get: function () {
  28732. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  28733. return this.usage === DynamicDrawUsage;
  28734. },
  28735. set: function () {
  28736. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  28737. this.setUsage(DynamicDrawUsage);
  28738. }
  28739. }
  28740. });
  28741. BufferAttribute.prototype.setDynamic = function (value) {
  28742. console.warn('THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.');
  28743. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  28744. return this;
  28745. };
  28746. BufferAttribute.prototype.copyIndicesArray = function () {
  28747. console.error('THREE.BufferAttribute: .copyIndicesArray() has been removed.');
  28748. }, BufferAttribute.prototype.setArray = function () {
  28749. console.error('THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  28750. }; //
  28751. BufferGeometry.prototype.addIndex = function (index) {
  28752. console.warn('THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().');
  28753. this.setIndex(index);
  28754. };
  28755. BufferGeometry.prototype.addAttribute = function (name, attribute) {
  28756. console.warn('THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().');
  28757. if (!(attribute && attribute.isBufferAttribute) && !(attribute && attribute.isInterleavedBufferAttribute)) {
  28758. console.warn('THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).');
  28759. return this.setAttribute(name, new BufferAttribute(arguments[1], arguments[2]));
  28760. }
  28761. if (name === 'index') {
  28762. console.warn('THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.');
  28763. this.setIndex(attribute);
  28764. return this;
  28765. }
  28766. return this.setAttribute(name, attribute);
  28767. };
  28768. BufferGeometry.prototype.addDrawCall = function (start, count, indexOffset) {
  28769. if (indexOffset !== undefined) {
  28770. console.warn('THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.');
  28771. }
  28772. console.warn('THREE.BufferGeometry: .addDrawCall() is now .addGroup().');
  28773. this.addGroup(start, count);
  28774. };
  28775. BufferGeometry.prototype.clearDrawCalls = function () {
  28776. console.warn('THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().');
  28777. this.clearGroups();
  28778. };
  28779. BufferGeometry.prototype.computeOffsets = function () {
  28780. console.warn('THREE.BufferGeometry: .computeOffsets() has been removed.');
  28781. };
  28782. BufferGeometry.prototype.removeAttribute = function (name) {
  28783. console.warn('THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().');
  28784. return this.deleteAttribute(name);
  28785. };
  28786. BufferGeometry.prototype.applyMatrix = function (matrix) {
  28787. console.warn('THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().');
  28788. return this.applyMatrix4(matrix);
  28789. };
  28790. Object.defineProperties(BufferGeometry.prototype, {
  28791. drawcalls: {
  28792. get: function () {
  28793. console.error('THREE.BufferGeometry: .drawcalls has been renamed to .groups.');
  28794. return this.groups;
  28795. }
  28796. },
  28797. offsets: {
  28798. get: function () {
  28799. console.warn('THREE.BufferGeometry: .offsets has been renamed to .groups.');
  28800. return this.groups;
  28801. }
  28802. }
  28803. });
  28804. InterleavedBuffer.prototype.setDynamic = function (value) {
  28805. console.warn('THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.');
  28806. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  28807. return this;
  28808. };
  28809. InterleavedBuffer.prototype.setArray = function () {
  28810. console.error('THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  28811. }; //
  28812. ExtrudeGeometry.prototype.getArrays = function () {
  28813. console.error('THREE.ExtrudeGeometry: .getArrays() has been removed.');
  28814. };
  28815. ExtrudeGeometry.prototype.addShapeList = function () {
  28816. console.error('THREE.ExtrudeGeometry: .addShapeList() has been removed.');
  28817. };
  28818. ExtrudeGeometry.prototype.addShape = function () {
  28819. console.error('THREE.ExtrudeGeometry: .addShape() has been removed.');
  28820. }; //
  28821. Scene.prototype.dispose = function () {
  28822. console.error('THREE.Scene: .dispose() has been removed.');
  28823. }; //
  28824. Uniform.prototype.onUpdate = function () {
  28825. console.warn('THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.');
  28826. return this;
  28827. }; //
  28828. Object.defineProperties(Material.prototype, {
  28829. wrapAround: {
  28830. get: function () {
  28831. console.warn('THREE.Material: .wrapAround has been removed.');
  28832. },
  28833. set: function () {
  28834. console.warn('THREE.Material: .wrapAround has been removed.');
  28835. }
  28836. },
  28837. overdraw: {
  28838. get: function () {
  28839. console.warn('THREE.Material: .overdraw has been removed.');
  28840. },
  28841. set: function () {
  28842. console.warn('THREE.Material: .overdraw has been removed.');
  28843. }
  28844. },
  28845. wrapRGB: {
  28846. get: function () {
  28847. console.warn('THREE.Material: .wrapRGB has been removed.');
  28848. return new Color();
  28849. }
  28850. },
  28851. shading: {
  28852. get: function () {
  28853. console.error('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  28854. },
  28855. set: function (value) {
  28856. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  28857. this.flatShading = value === FlatShading;
  28858. }
  28859. },
  28860. stencilMask: {
  28861. get: function () {
  28862. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  28863. return this.stencilFuncMask;
  28864. },
  28865. set: function (value) {
  28866. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  28867. this.stencilFuncMask = value;
  28868. }
  28869. },
  28870. vertexTangents: {
  28871. get: function () {
  28872. console.warn('THREE.' + this.type + ': .vertexTangents has been removed.');
  28873. },
  28874. set: function () {
  28875. console.warn('THREE.' + this.type + ': .vertexTangents has been removed.');
  28876. }
  28877. }
  28878. });
  28879. Object.defineProperties(ShaderMaterial.prototype, {
  28880. derivatives: {
  28881. get: function () {
  28882. console.warn('THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  28883. return this.extensions.derivatives;
  28884. },
  28885. set: function (value) {
  28886. console.warn('THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  28887. this.extensions.derivatives = value;
  28888. }
  28889. }
  28890. }); //
  28891. WebGLRenderer.prototype.clearTarget = function (renderTarget, color, depth, stencil) {
  28892. console.warn('THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.');
  28893. this.setRenderTarget(renderTarget);
  28894. this.clear(color, depth, stencil);
  28895. };
  28896. WebGLRenderer.prototype.animate = function (callback) {
  28897. console.warn('THREE.WebGLRenderer: .animate() is now .setAnimationLoop().');
  28898. this.setAnimationLoop(callback);
  28899. };
  28900. WebGLRenderer.prototype.getCurrentRenderTarget = function () {
  28901. console.warn('THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().');
  28902. return this.getRenderTarget();
  28903. };
  28904. WebGLRenderer.prototype.getMaxAnisotropy = function () {
  28905. console.warn('THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().');
  28906. return this.capabilities.getMaxAnisotropy();
  28907. };
  28908. WebGLRenderer.prototype.getPrecision = function () {
  28909. console.warn('THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.');
  28910. return this.capabilities.precision;
  28911. };
  28912. WebGLRenderer.prototype.resetGLState = function () {
  28913. console.warn('THREE.WebGLRenderer: .resetGLState() is now .state.reset().');
  28914. return this.state.reset();
  28915. };
  28916. WebGLRenderer.prototype.supportsFloatTextures = function () {
  28917. console.warn('THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).');
  28918. return this.extensions.get('OES_texture_float');
  28919. };
  28920. WebGLRenderer.prototype.supportsHalfFloatTextures = function () {
  28921. console.warn('THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).');
  28922. return this.extensions.get('OES_texture_half_float');
  28923. };
  28924. WebGLRenderer.prototype.supportsStandardDerivatives = function () {
  28925. console.warn('THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).');
  28926. return this.extensions.get('OES_standard_derivatives');
  28927. };
  28928. WebGLRenderer.prototype.supportsCompressedTextureS3TC = function () {
  28929. console.warn('THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).');
  28930. return this.extensions.get('WEBGL_compressed_texture_s3tc');
  28931. };
  28932. WebGLRenderer.prototype.supportsCompressedTexturePVRTC = function () {
  28933. console.warn('THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).');
  28934. return this.extensions.get('WEBGL_compressed_texture_pvrtc');
  28935. };
  28936. WebGLRenderer.prototype.supportsBlendMinMax = function () {
  28937. console.warn('THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).');
  28938. return this.extensions.get('EXT_blend_minmax');
  28939. };
  28940. WebGLRenderer.prototype.supportsVertexTextures = function () {
  28941. console.warn('THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.');
  28942. return this.capabilities.vertexTextures;
  28943. };
  28944. WebGLRenderer.prototype.supportsInstancedArrays = function () {
  28945. console.warn('THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).');
  28946. return this.extensions.get('ANGLE_instanced_arrays');
  28947. };
  28948. WebGLRenderer.prototype.enableScissorTest = function (boolean) {
  28949. console.warn('THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().');
  28950. this.setScissorTest(boolean);
  28951. };
  28952. WebGLRenderer.prototype.initMaterial = function () {
  28953. console.warn('THREE.WebGLRenderer: .initMaterial() has been removed.');
  28954. };
  28955. WebGLRenderer.prototype.addPrePlugin = function () {
  28956. console.warn('THREE.WebGLRenderer: .addPrePlugin() has been removed.');
  28957. };
  28958. WebGLRenderer.prototype.addPostPlugin = function () {
  28959. console.warn('THREE.WebGLRenderer: .addPostPlugin() has been removed.');
  28960. };
  28961. WebGLRenderer.prototype.updateShadowMap = function () {
  28962. console.warn('THREE.WebGLRenderer: .updateShadowMap() has been removed.');
  28963. };
  28964. WebGLRenderer.prototype.setFaceCulling = function () {
  28965. console.warn('THREE.WebGLRenderer: .setFaceCulling() has been removed.');
  28966. };
  28967. WebGLRenderer.prototype.allocTextureUnit = function () {
  28968. console.warn('THREE.WebGLRenderer: .allocTextureUnit() has been removed.');
  28969. };
  28970. WebGLRenderer.prototype.setTexture = function () {
  28971. console.warn('THREE.WebGLRenderer: .setTexture() has been removed.');
  28972. };
  28973. WebGLRenderer.prototype.setTexture2D = function () {
  28974. console.warn('THREE.WebGLRenderer: .setTexture2D() has been removed.');
  28975. };
  28976. WebGLRenderer.prototype.setTextureCube = function () {
  28977. console.warn('THREE.WebGLRenderer: .setTextureCube() has been removed.');
  28978. };
  28979. WebGLRenderer.prototype.getActiveMipMapLevel = function () {
  28980. console.warn('THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().');
  28981. return this.getActiveMipmapLevel();
  28982. };
  28983. Object.defineProperties(WebGLRenderer.prototype, {
  28984. shadowMapEnabled: {
  28985. get: function () {
  28986. return this.shadowMap.enabled;
  28987. },
  28988. set: function (value) {
  28989. console.warn('THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.');
  28990. this.shadowMap.enabled = value;
  28991. }
  28992. },
  28993. shadowMapType: {
  28994. get: function () {
  28995. return this.shadowMap.type;
  28996. },
  28997. set: function (value) {
  28998. console.warn('THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.');
  28999. this.shadowMap.type = value;
  29000. }
  29001. },
  29002. shadowMapCullFace: {
  29003. get: function () {
  29004. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  29005. return undefined;
  29006. },
  29007. set: function () {
  29008. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  29009. }
  29010. },
  29011. context: {
  29012. get: function () {
  29013. console.warn('THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.');
  29014. return this.getContext();
  29015. }
  29016. },
  29017. vr: {
  29018. get: function () {
  29019. console.warn('THREE.WebGLRenderer: .vr has been renamed to .xr');
  29020. return this.xr;
  29021. }
  29022. },
  29023. gammaInput: {
  29024. get: function () {
  29025. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  29026. return false;
  29027. },
  29028. set: function () {
  29029. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  29030. }
  29031. },
  29032. gammaOutput: {
  29033. get: function () {
  29034. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  29035. return false;
  29036. },
  29037. set: function (value) {
  29038. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  29039. this.outputEncoding = value === true ? sRGBEncoding : LinearEncoding;
  29040. }
  29041. },
  29042. toneMappingWhitePoint: {
  29043. get: function () {
  29044. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  29045. return 1.0;
  29046. },
  29047. set: function () {
  29048. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  29049. }
  29050. },
  29051. gammaFactor: {
  29052. get: function () {
  29053. console.warn('THREE.WebGLRenderer: .gammaFactor has been removed.');
  29054. return 2;
  29055. },
  29056. set: function () {
  29057. console.warn('THREE.WebGLRenderer: .gammaFactor has been removed.');
  29058. }
  29059. }
  29060. });
  29061. Object.defineProperties(WebGLShadowMap.prototype, {
  29062. cullFace: {
  29063. get: function () {
  29064. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  29065. return undefined;
  29066. },
  29067. set: function () {
  29068. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  29069. }
  29070. },
  29071. renderReverseSided: {
  29072. get: function () {
  29073. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  29074. return undefined;
  29075. },
  29076. set: function () {
  29077. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  29078. }
  29079. },
  29080. renderSingleSided: {
  29081. get: function () {
  29082. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  29083. return undefined;
  29084. },
  29085. set: function () {
  29086. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  29087. }
  29088. }
  29089. });
  29090. function WebGLRenderTargetCube(width, height, options) {
  29091. console.warn('THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).');
  29092. return new WebGLCubeRenderTarget(width, options);
  29093. } //
  29094. Object.defineProperties(WebGLRenderTarget.prototype, {
  29095. wrapS: {
  29096. get: function () {
  29097. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  29098. return this.texture.wrapS;
  29099. },
  29100. set: function (value) {
  29101. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  29102. this.texture.wrapS = value;
  29103. }
  29104. },
  29105. wrapT: {
  29106. get: function () {
  29107. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  29108. return this.texture.wrapT;
  29109. },
  29110. set: function (value) {
  29111. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  29112. this.texture.wrapT = value;
  29113. }
  29114. },
  29115. magFilter: {
  29116. get: function () {
  29117. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  29118. return this.texture.magFilter;
  29119. },
  29120. set: function (value) {
  29121. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  29122. this.texture.magFilter = value;
  29123. }
  29124. },
  29125. minFilter: {
  29126. get: function () {
  29127. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  29128. return this.texture.minFilter;
  29129. },
  29130. set: function (value) {
  29131. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  29132. this.texture.minFilter = value;
  29133. }
  29134. },
  29135. anisotropy: {
  29136. get: function () {
  29137. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  29138. return this.texture.anisotropy;
  29139. },
  29140. set: function (value) {
  29141. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  29142. this.texture.anisotropy = value;
  29143. }
  29144. },
  29145. offset: {
  29146. get: function () {
  29147. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  29148. return this.texture.offset;
  29149. },
  29150. set: function (value) {
  29151. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  29152. this.texture.offset = value;
  29153. }
  29154. },
  29155. repeat: {
  29156. get: function () {
  29157. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  29158. return this.texture.repeat;
  29159. },
  29160. set: function (value) {
  29161. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  29162. this.texture.repeat = value;
  29163. }
  29164. },
  29165. format: {
  29166. get: function () {
  29167. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  29168. return this.texture.format;
  29169. },
  29170. set: function (value) {
  29171. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  29172. this.texture.format = value;
  29173. }
  29174. },
  29175. type: {
  29176. get: function () {
  29177. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  29178. return this.texture.type;
  29179. },
  29180. set: function (value) {
  29181. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  29182. this.texture.type = value;
  29183. }
  29184. },
  29185. generateMipmaps: {
  29186. get: function () {
  29187. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  29188. return this.texture.generateMipmaps;
  29189. },
  29190. set: function (value) {
  29191. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  29192. this.texture.generateMipmaps = value;
  29193. }
  29194. }
  29195. }); //
  29196. Audio.prototype.load = function (file) {
  29197. console.warn('THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.');
  29198. const scope = this;
  29199. const audioLoader = new AudioLoader();
  29200. audioLoader.load(file, function (buffer) {
  29201. scope.setBuffer(buffer);
  29202. });
  29203. return this;
  29204. };
  29205. AudioAnalyser.prototype.getData = function () {
  29206. console.warn('THREE.AudioAnalyser: .getData() is now .getFrequencyData().');
  29207. return this.getFrequencyData();
  29208. }; //
  29209. CubeCamera.prototype.updateCubeMap = function (renderer, scene) {
  29210. console.warn('THREE.CubeCamera: .updateCubeMap() is now .update().');
  29211. return this.update(renderer, scene);
  29212. };
  29213. CubeCamera.prototype.clear = function (renderer, color, depth, stencil) {
  29214. console.warn('THREE.CubeCamera: .clear() is now .renderTarget.clear().');
  29215. return this.renderTarget.clear(renderer, color, depth, stencil);
  29216. };
  29217. ImageUtils.crossOrigin = undefined;
  29218. ImageUtils.loadTexture = function (url, mapping, onLoad, onError) {
  29219. console.warn('THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.');
  29220. const loader = new TextureLoader();
  29221. loader.setCrossOrigin(this.crossOrigin);
  29222. const texture = loader.load(url, onLoad, undefined, onError);
  29223. if (mapping) texture.mapping = mapping;
  29224. return texture;
  29225. };
  29226. ImageUtils.loadTextureCube = function (urls, mapping, onLoad, onError) {
  29227. console.warn('THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.');
  29228. const loader = new CubeTextureLoader();
  29229. loader.setCrossOrigin(this.crossOrigin);
  29230. const texture = loader.load(urls, onLoad, undefined, onError);
  29231. if (mapping) texture.mapping = mapping;
  29232. return texture;
  29233. };
  29234. ImageUtils.loadCompressedTexture = function () {
  29235. console.error('THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.');
  29236. };
  29237. ImageUtils.loadCompressedTextureCube = function () {
  29238. console.error('THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.');
  29239. }; //
  29240. function CanvasRenderer() {
  29241. console.error('THREE.CanvasRenderer has been removed');
  29242. } //
  29243. function JSONLoader() {
  29244. console.error('THREE.JSONLoader has been removed.');
  29245. } //
  29246. const SceneUtils = {
  29247. createMultiMaterialObject: function () {
  29248. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  29249. },
  29250. detach: function () {
  29251. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  29252. },
  29253. attach: function () {
  29254. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  29255. }
  29256. }; //
  29257. function LensFlare() {
  29258. console.error('THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js');
  29259. } //
  29260. function ParametricGeometry() {
  29261. console.error('THREE.ParametricGeometry has been moved to /examples/jsm/geometries/ParametricGeometry.js');
  29262. return new BufferGeometry();
  29263. }
  29264. function TextGeometry() {
  29265. console.error('THREE.TextGeometry has been moved to /examples/jsm/geometries/TextGeometry.js');
  29266. return new BufferGeometry();
  29267. }
  29268. function FontLoader() {
  29269. console.error('THREE.FontLoader has been moved to /examples/jsm/loaders/FontLoader.js');
  29270. }
  29271. function Font() {
  29272. console.error('THREE.Font has been moved to /examples/jsm/loaders/FontLoader.js');
  29273. }
  29274. function ImmediateRenderObject() {
  29275. console.error('THREE.ImmediateRenderObject has been removed.');
  29276. }
  29277. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  29278. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
  29279. detail: {
  29280. revision: REVISION
  29281. }
  29282. }));
  29283. }
  29284. if (typeof window !== 'undefined') {
  29285. if (window.__THREE__) {
  29286. console.warn('WARNING: Multiple instances of Three.js being imported.');
  29287. } else {
  29288. window.__THREE__ = REVISION;
  29289. }
  29290. }
  29291. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  29292. exports.AddEquation = AddEquation;
  29293. exports.AddOperation = AddOperation;
  29294. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  29295. exports.AdditiveBlending = AdditiveBlending;
  29296. exports.AlphaFormat = AlphaFormat;
  29297. exports.AlwaysDepth = AlwaysDepth;
  29298. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  29299. exports.AmbientLight = AmbientLight;
  29300. exports.AmbientLightProbe = AmbientLightProbe;
  29301. exports.AnimationClip = AnimationClip;
  29302. exports.AnimationLoader = AnimationLoader;
  29303. exports.AnimationMixer = AnimationMixer;
  29304. exports.AnimationObjectGroup = AnimationObjectGroup;
  29305. exports.AnimationUtils = AnimationUtils;
  29306. exports.ArcCurve = ArcCurve;
  29307. exports.ArrayCamera = ArrayCamera;
  29308. exports.ArrowHelper = ArrowHelper;
  29309. exports.Audio = Audio;
  29310. exports.AudioAnalyser = AudioAnalyser;
  29311. exports.AudioContext = AudioContext;
  29312. exports.AudioListener = AudioListener;
  29313. exports.AudioLoader = AudioLoader;
  29314. exports.AxesHelper = AxesHelper;
  29315. exports.AxisHelper = AxisHelper;
  29316. exports.BackSide = BackSide;
  29317. exports.BasicDepthPacking = BasicDepthPacking;
  29318. exports.BasicShadowMap = BasicShadowMap;
  29319. exports.BinaryTextureLoader = BinaryTextureLoader;
  29320. exports.Bone = Bone;
  29321. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  29322. exports.BoundingBoxHelper = BoundingBoxHelper;
  29323. exports.Box2 = Box2;
  29324. exports.Box3 = Box3;
  29325. exports.Box3Helper = Box3Helper;
  29326. exports.BoxBufferGeometry = BoxGeometry;
  29327. exports.BoxGeometry = BoxGeometry;
  29328. exports.BoxHelper = BoxHelper;
  29329. exports.BufferAttribute = BufferAttribute;
  29330. exports.BufferGeometry = BufferGeometry;
  29331. exports.BufferGeometryLoader = BufferGeometryLoader;
  29332. exports.ByteType = ByteType;
  29333. exports.Cache = Cache;
  29334. exports.Camera = Camera;
  29335. exports.CameraHelper = CameraHelper;
  29336. exports.CanvasRenderer = CanvasRenderer;
  29337. exports.CanvasTexture = CanvasTexture;
  29338. exports.CatmullRomCurve3 = CatmullRomCurve3;
  29339. exports.CineonToneMapping = CineonToneMapping;
  29340. exports.CircleBufferGeometry = CircleGeometry;
  29341. exports.CircleGeometry = CircleGeometry;
  29342. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  29343. exports.Clock = Clock;
  29344. exports.Color = Color;
  29345. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  29346. exports.CompressedTexture = CompressedTexture;
  29347. exports.CompressedTextureLoader = CompressedTextureLoader;
  29348. exports.ConeBufferGeometry = ConeGeometry;
  29349. exports.ConeGeometry = ConeGeometry;
  29350. exports.CubeCamera = CubeCamera;
  29351. exports.CubeReflectionMapping = CubeReflectionMapping;
  29352. exports.CubeRefractionMapping = CubeRefractionMapping;
  29353. exports.CubeTexture = CubeTexture;
  29354. exports.CubeTextureLoader = CubeTextureLoader;
  29355. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  29356. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  29357. exports.CubicBezierCurve = CubicBezierCurve;
  29358. exports.CubicBezierCurve3 = CubicBezierCurve3;
  29359. exports.CubicInterpolant = CubicInterpolant;
  29360. exports.CullFaceBack = CullFaceBack;
  29361. exports.CullFaceFront = CullFaceFront;
  29362. exports.CullFaceFrontBack = CullFaceFrontBack;
  29363. exports.CullFaceNone = CullFaceNone;
  29364. exports.Curve = Curve;
  29365. exports.CurvePath = CurvePath;
  29366. exports.CustomBlending = CustomBlending;
  29367. exports.CustomToneMapping = CustomToneMapping;
  29368. exports.CylinderBufferGeometry = CylinderGeometry;
  29369. exports.CylinderGeometry = CylinderGeometry;
  29370. exports.Cylindrical = Cylindrical;
  29371. exports.DataTexture = DataTexture;
  29372. exports.DataTexture2DArray = DataTexture2DArray;
  29373. exports.DataTexture3D = DataTexture3D;
  29374. exports.DataTextureLoader = DataTextureLoader;
  29375. exports.DataUtils = DataUtils;
  29376. exports.DecrementStencilOp = DecrementStencilOp;
  29377. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  29378. exports.DefaultLoadingManager = DefaultLoadingManager;
  29379. exports.DepthFormat = DepthFormat;
  29380. exports.DepthStencilFormat = DepthStencilFormat;
  29381. exports.DepthTexture = DepthTexture;
  29382. exports.DirectionalLight = DirectionalLight;
  29383. exports.DirectionalLightHelper = DirectionalLightHelper;
  29384. exports.DiscreteInterpolant = DiscreteInterpolant;
  29385. exports.DodecahedronBufferGeometry = DodecahedronGeometry;
  29386. exports.DodecahedronGeometry = DodecahedronGeometry;
  29387. exports.DoubleSide = DoubleSide;
  29388. exports.DstAlphaFactor = DstAlphaFactor;
  29389. exports.DstColorFactor = DstColorFactor;
  29390. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  29391. exports.DynamicCopyUsage = DynamicCopyUsage;
  29392. exports.DynamicDrawUsage = DynamicDrawUsage;
  29393. exports.DynamicReadUsage = DynamicReadUsage;
  29394. exports.EdgesGeometry = EdgesGeometry;
  29395. exports.EdgesHelper = EdgesHelper;
  29396. exports.EllipseCurve = EllipseCurve;
  29397. exports.EqualDepth = EqualDepth;
  29398. exports.EqualStencilFunc = EqualStencilFunc;
  29399. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  29400. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  29401. exports.Euler = Euler;
  29402. exports.EventDispatcher = EventDispatcher;
  29403. exports.ExtrudeBufferGeometry = ExtrudeGeometry;
  29404. exports.ExtrudeGeometry = ExtrudeGeometry;
  29405. exports.FaceColors = FaceColors;
  29406. exports.FileLoader = FileLoader;
  29407. exports.FlatShading = FlatShading;
  29408. exports.Float16BufferAttribute = Float16BufferAttribute;
  29409. exports.Float32Attribute = Float32Attribute;
  29410. exports.Float32BufferAttribute = Float32BufferAttribute;
  29411. exports.Float64Attribute = Float64Attribute;
  29412. exports.Float64BufferAttribute = Float64BufferAttribute;
  29413. exports.FloatType = FloatType;
  29414. exports.Fog = Fog;
  29415. exports.FogExp2 = FogExp2;
  29416. exports.Font = Font;
  29417. exports.FontLoader = FontLoader;
  29418. exports.FramebufferTexture = FramebufferTexture;
  29419. exports.FrontSide = FrontSide;
  29420. exports.Frustum = Frustum;
  29421. exports.GLBufferAttribute = GLBufferAttribute;
  29422. exports.GLSL1 = GLSL1;
  29423. exports.GLSL3 = GLSL3;
  29424. exports.GreaterDepth = GreaterDepth;
  29425. exports.GreaterEqualDepth = GreaterEqualDepth;
  29426. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  29427. exports.GreaterStencilFunc = GreaterStencilFunc;
  29428. exports.GridHelper = GridHelper;
  29429. exports.Group = Group;
  29430. exports.HalfFloatType = HalfFloatType;
  29431. exports.HemisphereLight = HemisphereLight;
  29432. exports.HemisphereLightHelper = HemisphereLightHelper;
  29433. exports.HemisphereLightProbe = HemisphereLightProbe;
  29434. exports.IcosahedronBufferGeometry = IcosahedronGeometry;
  29435. exports.IcosahedronGeometry = IcosahedronGeometry;
  29436. exports.ImageBitmapLoader = ImageBitmapLoader;
  29437. exports.ImageLoader = ImageLoader;
  29438. exports.ImageUtils = ImageUtils;
  29439. exports.ImmediateRenderObject = ImmediateRenderObject;
  29440. exports.IncrementStencilOp = IncrementStencilOp;
  29441. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  29442. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  29443. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  29444. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  29445. exports.InstancedMesh = InstancedMesh;
  29446. exports.Int16Attribute = Int16Attribute;
  29447. exports.Int16BufferAttribute = Int16BufferAttribute;
  29448. exports.Int32Attribute = Int32Attribute;
  29449. exports.Int32BufferAttribute = Int32BufferAttribute;
  29450. exports.Int8Attribute = Int8Attribute;
  29451. exports.Int8BufferAttribute = Int8BufferAttribute;
  29452. exports.IntType = IntType;
  29453. exports.InterleavedBuffer = InterleavedBuffer;
  29454. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  29455. exports.Interpolant = Interpolant;
  29456. exports.InterpolateDiscrete = InterpolateDiscrete;
  29457. exports.InterpolateLinear = InterpolateLinear;
  29458. exports.InterpolateSmooth = InterpolateSmooth;
  29459. exports.InvertStencilOp = InvertStencilOp;
  29460. exports.JSONLoader = JSONLoader;
  29461. exports.KeepStencilOp = KeepStencilOp;
  29462. exports.KeyframeTrack = KeyframeTrack;
  29463. exports.LOD = LOD;
  29464. exports.LatheBufferGeometry = LatheGeometry;
  29465. exports.LatheGeometry = LatheGeometry;
  29466. exports.Layers = Layers;
  29467. exports.LensFlare = LensFlare;
  29468. exports.LessDepth = LessDepth;
  29469. exports.LessEqualDepth = LessEqualDepth;
  29470. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  29471. exports.LessStencilFunc = LessStencilFunc;
  29472. exports.Light = Light;
  29473. exports.LightProbe = LightProbe;
  29474. exports.Line = Line;
  29475. exports.Line3 = Line3;
  29476. exports.LineBasicMaterial = LineBasicMaterial;
  29477. exports.LineCurve = LineCurve;
  29478. exports.LineCurve3 = LineCurve3;
  29479. exports.LineDashedMaterial = LineDashedMaterial;
  29480. exports.LineLoop = LineLoop;
  29481. exports.LinePieces = LinePieces;
  29482. exports.LineSegments = LineSegments;
  29483. exports.LineStrip = LineStrip;
  29484. exports.LinearEncoding = LinearEncoding;
  29485. exports.LinearFilter = LinearFilter;
  29486. exports.LinearInterpolant = LinearInterpolant;
  29487. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  29488. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  29489. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  29490. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  29491. exports.LinearToneMapping = LinearToneMapping;
  29492. exports.Loader = Loader;
  29493. exports.LoaderUtils = LoaderUtils;
  29494. exports.LoadingManager = LoadingManager;
  29495. exports.LoopOnce = LoopOnce;
  29496. exports.LoopPingPong = LoopPingPong;
  29497. exports.LoopRepeat = LoopRepeat;
  29498. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  29499. exports.LuminanceFormat = LuminanceFormat;
  29500. exports.MOUSE = MOUSE;
  29501. exports.Material = Material;
  29502. exports.MaterialLoader = MaterialLoader;
  29503. exports.Math = MathUtils;
  29504. exports.MathUtils = MathUtils;
  29505. exports.Matrix3 = Matrix3;
  29506. exports.Matrix4 = Matrix4;
  29507. exports.MaxEquation = MaxEquation;
  29508. exports.Mesh = Mesh;
  29509. exports.MeshBasicMaterial = MeshBasicMaterial;
  29510. exports.MeshDepthMaterial = MeshDepthMaterial;
  29511. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  29512. exports.MeshFaceMaterial = MeshFaceMaterial;
  29513. exports.MeshLambertMaterial = MeshLambertMaterial;
  29514. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  29515. exports.MeshNormalMaterial = MeshNormalMaterial;
  29516. exports.MeshPhongMaterial = MeshPhongMaterial;
  29517. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  29518. exports.MeshStandardMaterial = MeshStandardMaterial;
  29519. exports.MeshToonMaterial = MeshToonMaterial;
  29520. exports.MinEquation = MinEquation;
  29521. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  29522. exports.MixOperation = MixOperation;
  29523. exports.MultiMaterial = MultiMaterial;
  29524. exports.MultiplyBlending = MultiplyBlending;
  29525. exports.MultiplyOperation = MultiplyOperation;
  29526. exports.NearestFilter = NearestFilter;
  29527. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  29528. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  29529. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  29530. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  29531. exports.NeverDepth = NeverDepth;
  29532. exports.NeverStencilFunc = NeverStencilFunc;
  29533. exports.NoBlending = NoBlending;
  29534. exports.NoColors = NoColors;
  29535. exports.NoToneMapping = NoToneMapping;
  29536. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  29537. exports.NormalBlending = NormalBlending;
  29538. exports.NotEqualDepth = NotEqualDepth;
  29539. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  29540. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  29541. exports.Object3D = Object3D;
  29542. exports.ObjectLoader = ObjectLoader;
  29543. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  29544. exports.OctahedronBufferGeometry = OctahedronGeometry;
  29545. exports.OctahedronGeometry = OctahedronGeometry;
  29546. exports.OneFactor = OneFactor;
  29547. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  29548. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  29549. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  29550. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  29551. exports.OrthographicCamera = OrthographicCamera;
  29552. exports.PCFShadowMap = PCFShadowMap;
  29553. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  29554. exports.PMREMGenerator = PMREMGenerator;
  29555. exports.ParametricGeometry = ParametricGeometry;
  29556. exports.Particle = Particle;
  29557. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  29558. exports.ParticleSystem = ParticleSystem;
  29559. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  29560. exports.Path = Path;
  29561. exports.PerspectiveCamera = PerspectiveCamera;
  29562. exports.Plane = Plane;
  29563. exports.PlaneBufferGeometry = PlaneGeometry;
  29564. exports.PlaneGeometry = PlaneGeometry;
  29565. exports.PlaneHelper = PlaneHelper;
  29566. exports.PointCloud = PointCloud;
  29567. exports.PointCloudMaterial = PointCloudMaterial;
  29568. exports.PointLight = PointLight;
  29569. exports.PointLightHelper = PointLightHelper;
  29570. exports.Points = Points;
  29571. exports.PointsMaterial = PointsMaterial;
  29572. exports.PolarGridHelper = PolarGridHelper;
  29573. exports.PolyhedronBufferGeometry = PolyhedronGeometry;
  29574. exports.PolyhedronGeometry = PolyhedronGeometry;
  29575. exports.PositionalAudio = PositionalAudio;
  29576. exports.PropertyBinding = PropertyBinding;
  29577. exports.PropertyMixer = PropertyMixer;
  29578. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  29579. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  29580. exports.Quaternion = Quaternion;
  29581. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  29582. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  29583. exports.REVISION = REVISION;
  29584. exports.RGBADepthPacking = RGBADepthPacking;
  29585. exports.RGBAFormat = RGBAFormat;
  29586. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  29587. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  29588. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  29589. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  29590. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  29591. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  29592. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  29593. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  29594. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  29595. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  29596. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  29597. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  29598. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  29599. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  29600. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  29601. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  29602. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  29603. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  29604. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  29605. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  29606. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  29607. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  29608. exports.RGBFormat = RGBFormat;
  29609. exports.RGBIntegerFormat = RGBIntegerFormat;
  29610. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  29611. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  29612. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  29613. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  29614. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  29615. exports.RGFormat = RGFormat;
  29616. exports.RGIntegerFormat = RGIntegerFormat;
  29617. exports.RawShaderMaterial = RawShaderMaterial;
  29618. exports.Ray = Ray;
  29619. exports.Raycaster = Raycaster;
  29620. exports.RectAreaLight = RectAreaLight;
  29621. exports.RedFormat = RedFormat;
  29622. exports.RedIntegerFormat = RedIntegerFormat;
  29623. exports.ReinhardToneMapping = ReinhardToneMapping;
  29624. exports.RepeatWrapping = RepeatWrapping;
  29625. exports.ReplaceStencilOp = ReplaceStencilOp;
  29626. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  29627. exports.RingBufferGeometry = RingGeometry;
  29628. exports.RingGeometry = RingGeometry;
  29629. exports.SRGB8_ALPHA8_ASTC_10x10_Format = SRGB8_ALPHA8_ASTC_10x10_Format;
  29630. exports.SRGB8_ALPHA8_ASTC_10x5_Format = SRGB8_ALPHA8_ASTC_10x5_Format;
  29631. exports.SRGB8_ALPHA8_ASTC_10x6_Format = SRGB8_ALPHA8_ASTC_10x6_Format;
  29632. exports.SRGB8_ALPHA8_ASTC_10x8_Format = SRGB8_ALPHA8_ASTC_10x8_Format;
  29633. exports.SRGB8_ALPHA8_ASTC_12x10_Format = SRGB8_ALPHA8_ASTC_12x10_Format;
  29634. exports.SRGB8_ALPHA8_ASTC_12x12_Format = SRGB8_ALPHA8_ASTC_12x12_Format;
  29635. exports.SRGB8_ALPHA8_ASTC_4x4_Format = SRGB8_ALPHA8_ASTC_4x4_Format;
  29636. exports.SRGB8_ALPHA8_ASTC_5x4_Format = SRGB8_ALPHA8_ASTC_5x4_Format;
  29637. exports.SRGB8_ALPHA8_ASTC_5x5_Format = SRGB8_ALPHA8_ASTC_5x5_Format;
  29638. exports.SRGB8_ALPHA8_ASTC_6x5_Format = SRGB8_ALPHA8_ASTC_6x5_Format;
  29639. exports.SRGB8_ALPHA8_ASTC_6x6_Format = SRGB8_ALPHA8_ASTC_6x6_Format;
  29640. exports.SRGB8_ALPHA8_ASTC_8x5_Format = SRGB8_ALPHA8_ASTC_8x5_Format;
  29641. exports.SRGB8_ALPHA8_ASTC_8x6_Format = SRGB8_ALPHA8_ASTC_8x6_Format;
  29642. exports.SRGB8_ALPHA8_ASTC_8x8_Format = SRGB8_ALPHA8_ASTC_8x8_Format;
  29643. exports.Scene = Scene;
  29644. exports.SceneUtils = SceneUtils;
  29645. exports.ShaderChunk = ShaderChunk;
  29646. exports.ShaderLib = ShaderLib;
  29647. exports.ShaderMaterial = ShaderMaterial;
  29648. exports.ShadowMaterial = ShadowMaterial;
  29649. exports.Shape = Shape;
  29650. exports.ShapeBufferGeometry = ShapeGeometry;
  29651. exports.ShapeGeometry = ShapeGeometry;
  29652. exports.ShapePath = ShapePath;
  29653. exports.ShapeUtils = ShapeUtils;
  29654. exports.ShortType = ShortType;
  29655. exports.Skeleton = Skeleton;
  29656. exports.SkeletonHelper = SkeletonHelper;
  29657. exports.SkinnedMesh = SkinnedMesh;
  29658. exports.SmoothShading = SmoothShading;
  29659. exports.Sphere = Sphere;
  29660. exports.SphereBufferGeometry = SphereGeometry;
  29661. exports.SphereGeometry = SphereGeometry;
  29662. exports.Spherical = Spherical;
  29663. exports.SphericalHarmonics3 = SphericalHarmonics3;
  29664. exports.SplineCurve = SplineCurve;
  29665. exports.SpotLight = SpotLight;
  29666. exports.SpotLightHelper = SpotLightHelper;
  29667. exports.Sprite = Sprite;
  29668. exports.SpriteMaterial = SpriteMaterial;
  29669. exports.SrcAlphaFactor = SrcAlphaFactor;
  29670. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  29671. exports.SrcColorFactor = SrcColorFactor;
  29672. exports.StaticCopyUsage = StaticCopyUsage;
  29673. exports.StaticDrawUsage = StaticDrawUsage;
  29674. exports.StaticReadUsage = StaticReadUsage;
  29675. exports.StereoCamera = StereoCamera;
  29676. exports.StreamCopyUsage = StreamCopyUsage;
  29677. exports.StreamDrawUsage = StreamDrawUsage;
  29678. exports.StreamReadUsage = StreamReadUsage;
  29679. exports.StringKeyframeTrack = StringKeyframeTrack;
  29680. exports.SubtractEquation = SubtractEquation;
  29681. exports.SubtractiveBlending = SubtractiveBlending;
  29682. exports.TOUCH = TOUCH;
  29683. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  29684. exports.TetrahedronBufferGeometry = TetrahedronGeometry;
  29685. exports.TetrahedronGeometry = TetrahedronGeometry;
  29686. exports.TextGeometry = TextGeometry;
  29687. exports.Texture = Texture;
  29688. exports.TextureLoader = TextureLoader;
  29689. exports.TorusBufferGeometry = TorusGeometry;
  29690. exports.TorusGeometry = TorusGeometry;
  29691. exports.TorusKnotBufferGeometry = TorusKnotGeometry;
  29692. exports.TorusKnotGeometry = TorusKnotGeometry;
  29693. exports.Triangle = Triangle;
  29694. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  29695. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  29696. exports.TrianglesDrawMode = TrianglesDrawMode;
  29697. exports.TubeBufferGeometry = TubeGeometry;
  29698. exports.TubeGeometry = TubeGeometry;
  29699. exports.UVMapping = UVMapping;
  29700. exports.Uint16Attribute = Uint16Attribute;
  29701. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  29702. exports.Uint32Attribute = Uint32Attribute;
  29703. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  29704. exports.Uint8Attribute = Uint8Attribute;
  29705. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  29706. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  29707. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  29708. exports.Uniform = Uniform;
  29709. exports.UniformsLib = UniformsLib;
  29710. exports.UniformsUtils = UniformsUtils;
  29711. exports.UnsignedByteType = UnsignedByteType;
  29712. exports.UnsignedInt248Type = UnsignedInt248Type;
  29713. exports.UnsignedIntType = UnsignedIntType;
  29714. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  29715. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  29716. exports.UnsignedShort565Type = UnsignedShort565Type;
  29717. exports.UnsignedShortType = UnsignedShortType;
  29718. exports.VSMShadowMap = VSMShadowMap;
  29719. exports.Vector2 = Vector2;
  29720. exports.Vector3 = Vector3;
  29721. exports.Vector4 = Vector4;
  29722. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  29723. exports.Vertex = Vertex;
  29724. exports.VertexColors = VertexColors;
  29725. exports.VideoTexture = VideoTexture;
  29726. exports.WebGL1Renderer = WebGL1Renderer;
  29727. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  29728. exports.WebGLMultipleRenderTargets = WebGLMultipleRenderTargets;
  29729. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  29730. exports.WebGLRenderTarget = WebGLRenderTarget;
  29731. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  29732. exports.WebGLRenderer = WebGLRenderer;
  29733. exports.WebGLUtils = WebGLUtils;
  29734. exports.WireframeGeometry = WireframeGeometry;
  29735. exports.WireframeHelper = WireframeHelper;
  29736. exports.WrapAroundEnding = WrapAroundEnding;
  29737. exports.XHRLoader = XHRLoader;
  29738. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  29739. exports.ZeroFactor = ZeroFactor;
  29740. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  29741. exports.ZeroStencilOp = ZeroStencilOp;
  29742. exports.sRGBEncoding = sRGBEncoding;
  29743. Object.defineProperty(exports, '__esModule', { value: true });
  29744. }));
粤ICP备19079148号