three.js 1.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099
  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 = '129dev';
  12. const MOUSE = {
  13. LEFT: 0,
  14. MIDDLE: 1,
  15. RIGHT: 2,
  16. ROTATE: 0,
  17. DOLLY: 1,
  18. PAN: 2
  19. };
  20. const TOUCH = {
  21. ROTATE: 0,
  22. PAN: 1,
  23. DOLLY_PAN: 2,
  24. DOLLY_ROTATE: 3
  25. };
  26. const CullFaceNone = 0;
  27. const CullFaceBack = 1;
  28. const CullFaceFront = 2;
  29. const CullFaceFrontBack = 3;
  30. const BasicShadowMap = 0;
  31. const PCFShadowMap = 1;
  32. const PCFSoftShadowMap = 2;
  33. const VSMShadowMap = 3;
  34. const FrontSide = 0;
  35. const BackSide = 1;
  36. const DoubleSide = 2;
  37. const FlatShading = 1;
  38. const SmoothShading = 2;
  39. const NoBlending = 0;
  40. const NormalBlending = 1;
  41. const AdditiveBlending = 2;
  42. const SubtractiveBlending = 3;
  43. const MultiplyBlending = 4;
  44. const CustomBlending = 5;
  45. const AddEquation = 100;
  46. const SubtractEquation = 101;
  47. const ReverseSubtractEquation = 102;
  48. const MinEquation = 103;
  49. const MaxEquation = 104;
  50. const ZeroFactor = 200;
  51. const OneFactor = 201;
  52. const SrcColorFactor = 202;
  53. const OneMinusSrcColorFactor = 203;
  54. const SrcAlphaFactor = 204;
  55. const OneMinusSrcAlphaFactor = 205;
  56. const DstAlphaFactor = 206;
  57. const OneMinusDstAlphaFactor = 207;
  58. const DstColorFactor = 208;
  59. const OneMinusDstColorFactor = 209;
  60. const SrcAlphaSaturateFactor = 210;
  61. const NeverDepth = 0;
  62. const AlwaysDepth = 1;
  63. const LessDepth = 2;
  64. const LessEqualDepth = 3;
  65. const EqualDepth = 4;
  66. const GreaterEqualDepth = 5;
  67. const GreaterDepth = 6;
  68. const NotEqualDepth = 7;
  69. const MultiplyOperation = 0;
  70. const MixOperation = 1;
  71. const AddOperation = 2;
  72. const NoToneMapping = 0;
  73. const LinearToneMapping = 1;
  74. const ReinhardToneMapping = 2;
  75. const CineonToneMapping = 3;
  76. const ACESFilmicToneMapping = 4;
  77. const CustomToneMapping = 5;
  78. const UVMapping = 300;
  79. const CubeReflectionMapping = 301;
  80. const CubeRefractionMapping = 302;
  81. const EquirectangularReflectionMapping = 303;
  82. const EquirectangularRefractionMapping = 304;
  83. const CubeUVReflectionMapping = 306;
  84. const CubeUVRefractionMapping = 307;
  85. const RepeatWrapping = 1000;
  86. const ClampToEdgeWrapping = 1001;
  87. const MirroredRepeatWrapping = 1002;
  88. const NearestFilter = 1003;
  89. const NearestMipmapNearestFilter = 1004;
  90. const NearestMipMapNearestFilter = 1004;
  91. const NearestMipmapLinearFilter = 1005;
  92. const NearestMipMapLinearFilter = 1005;
  93. const LinearFilter = 1006;
  94. const LinearMipmapNearestFilter = 1007;
  95. const LinearMipMapNearestFilter = 1007;
  96. const LinearMipmapLinearFilter = 1008;
  97. const LinearMipMapLinearFilter = 1008;
  98. const UnsignedByteType = 1009;
  99. const ByteType = 1010;
  100. const ShortType = 1011;
  101. const UnsignedShortType = 1012;
  102. const IntType = 1013;
  103. const UnsignedIntType = 1014;
  104. const FloatType = 1015;
  105. const HalfFloatType = 1016;
  106. const UnsignedShort4444Type = 1017;
  107. const UnsignedShort5551Type = 1018;
  108. const UnsignedShort565Type = 1019;
  109. const UnsignedInt248Type = 1020;
  110. const AlphaFormat = 1021;
  111. const RGBFormat = 1022;
  112. const RGBAFormat = 1023;
  113. const LuminanceFormat = 1024;
  114. const LuminanceAlphaFormat = 1025;
  115. const RGBEFormat = RGBAFormat;
  116. const DepthFormat = 1026;
  117. const DepthStencilFormat = 1027;
  118. const RedFormat = 1028;
  119. const RedIntegerFormat = 1029;
  120. const RGFormat = 1030;
  121. const RGIntegerFormat = 1031;
  122. const RGBIntegerFormat = 1032;
  123. const RGBAIntegerFormat = 1033;
  124. const RGB_S3TC_DXT1_Format = 33776;
  125. const RGBA_S3TC_DXT1_Format = 33777;
  126. const RGBA_S3TC_DXT3_Format = 33778;
  127. const RGBA_S3TC_DXT5_Format = 33779;
  128. const RGB_PVRTC_4BPPV1_Format = 35840;
  129. const RGB_PVRTC_2BPPV1_Format = 35841;
  130. const RGBA_PVRTC_4BPPV1_Format = 35842;
  131. const RGBA_PVRTC_2BPPV1_Format = 35843;
  132. const RGB_ETC1_Format = 36196;
  133. const RGB_ETC2_Format = 37492;
  134. const RGBA_ETC2_EAC_Format = 37496;
  135. const RGBA_ASTC_4x4_Format = 37808;
  136. const RGBA_ASTC_5x4_Format = 37809;
  137. const RGBA_ASTC_5x5_Format = 37810;
  138. const RGBA_ASTC_6x5_Format = 37811;
  139. const RGBA_ASTC_6x6_Format = 37812;
  140. const RGBA_ASTC_8x5_Format = 37813;
  141. const RGBA_ASTC_8x6_Format = 37814;
  142. const RGBA_ASTC_8x8_Format = 37815;
  143. const RGBA_ASTC_10x5_Format = 37816;
  144. const RGBA_ASTC_10x6_Format = 37817;
  145. const RGBA_ASTC_10x8_Format = 37818;
  146. const RGBA_ASTC_10x10_Format = 37819;
  147. const RGBA_ASTC_12x10_Format = 37820;
  148. const RGBA_ASTC_12x12_Format = 37821;
  149. const RGBA_BPTC_Format = 36492;
  150. const SRGB8_ALPHA8_ASTC_4x4_Format = 37840;
  151. const SRGB8_ALPHA8_ASTC_5x4_Format = 37841;
  152. const SRGB8_ALPHA8_ASTC_5x5_Format = 37842;
  153. const SRGB8_ALPHA8_ASTC_6x5_Format = 37843;
  154. const SRGB8_ALPHA8_ASTC_6x6_Format = 37844;
  155. const SRGB8_ALPHA8_ASTC_8x5_Format = 37845;
  156. const SRGB8_ALPHA8_ASTC_8x6_Format = 37846;
  157. const SRGB8_ALPHA8_ASTC_8x8_Format = 37847;
  158. const SRGB8_ALPHA8_ASTC_10x5_Format = 37848;
  159. const SRGB8_ALPHA8_ASTC_10x6_Format = 37849;
  160. const SRGB8_ALPHA8_ASTC_10x8_Format = 37850;
  161. const SRGB8_ALPHA8_ASTC_10x10_Format = 37851;
  162. const SRGB8_ALPHA8_ASTC_12x10_Format = 37852;
  163. const SRGB8_ALPHA8_ASTC_12x12_Format = 37853;
  164. const LoopOnce = 2200;
  165. const LoopRepeat = 2201;
  166. const LoopPingPong = 2202;
  167. const InterpolateDiscrete = 2300;
  168. const InterpolateLinear = 2301;
  169. const InterpolateSmooth = 2302;
  170. const ZeroCurvatureEnding = 2400;
  171. const ZeroSlopeEnding = 2401;
  172. const WrapAroundEnding = 2402;
  173. const NormalAnimationBlendMode = 2500;
  174. const AdditiveAnimationBlendMode = 2501;
  175. const TrianglesDrawMode = 0;
  176. const TriangleStripDrawMode = 1;
  177. const TriangleFanDrawMode = 2;
  178. const LinearEncoding = 3000;
  179. const sRGBEncoding = 3001;
  180. const GammaEncoding = 3007;
  181. const RGBEEncoding = 3002;
  182. const LogLuvEncoding = 3003;
  183. const RGBM7Encoding = 3004;
  184. const RGBM16Encoding = 3005;
  185. const RGBDEncoding = 3006;
  186. const BasicDepthPacking = 3200;
  187. const RGBADepthPacking = 3201;
  188. const TangentSpaceNormalMap = 0;
  189. const ObjectSpaceNormalMap = 1;
  190. const ZeroStencilOp = 0;
  191. const KeepStencilOp = 7680;
  192. const ReplaceStencilOp = 7681;
  193. const IncrementStencilOp = 7682;
  194. const DecrementStencilOp = 7683;
  195. const IncrementWrapStencilOp = 34055;
  196. const DecrementWrapStencilOp = 34056;
  197. const InvertStencilOp = 5386;
  198. const NeverStencilFunc = 512;
  199. const LessStencilFunc = 513;
  200. const EqualStencilFunc = 514;
  201. const LessEqualStencilFunc = 515;
  202. const GreaterStencilFunc = 516;
  203. const NotEqualStencilFunc = 517;
  204. const GreaterEqualStencilFunc = 518;
  205. const AlwaysStencilFunc = 519;
  206. const StaticDrawUsage = 35044;
  207. const DynamicDrawUsage = 35048;
  208. const StreamDrawUsage = 35040;
  209. const StaticReadUsage = 35045;
  210. const DynamicReadUsage = 35049;
  211. const StreamReadUsage = 35041;
  212. const StaticCopyUsage = 35046;
  213. const DynamicCopyUsage = 35050;
  214. const StreamCopyUsage = 35042;
  215. const GLSL1 = '100';
  216. const GLSL3 = '300 es';
  217. /**
  218. * https://github.com/mrdoob/eventdispatcher.js/
  219. */
  220. class EventDispatcher {
  221. addEventListener(type, listener) {
  222. if (this._listeners === undefined) this._listeners = {};
  223. const listeners = this._listeners;
  224. if (listeners[type] === undefined) {
  225. listeners[type] = [];
  226. }
  227. if (listeners[type].indexOf(listener) === -1) {
  228. listeners[type].push(listener);
  229. }
  230. }
  231. hasEventListener(type, listener) {
  232. if (this._listeners === undefined) return false;
  233. const listeners = this._listeners;
  234. return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
  235. }
  236. removeEventListener(type, listener) {
  237. if (this._listeners === undefined) return;
  238. const listeners = this._listeners;
  239. const listenerArray = listeners[type];
  240. if (listenerArray !== undefined) {
  241. const index = listenerArray.indexOf(listener);
  242. if (index !== -1) {
  243. listenerArray.splice(index, 1);
  244. }
  245. }
  246. }
  247. dispatchEvent(event) {
  248. if (this._listeners === undefined) return;
  249. const listeners = this._listeners;
  250. const listenerArray = listeners[event.type];
  251. if (listenerArray !== undefined) {
  252. event.target = this; // Make a copy, in case listeners are removed while iterating.
  253. const array = listenerArray.slice(0);
  254. for (let i = 0, l = array.length; i < l; i++) {
  255. array[i].call(this, event);
  256. }
  257. event.target = null;
  258. }
  259. }
  260. }
  261. const _lut = [];
  262. for (let i = 0; i < 256; i++) {
  263. _lut[i] = (i < 16 ? '0' : '') + i.toString(16);
  264. }
  265. let _seed = 1234567;
  266. const DEG2RAD = Math.PI / 180;
  267. const RAD2DEG = 180 / Math.PI; // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  268. function generateUUID() {
  269. const d0 = Math.random() * 0xffffffff | 0;
  270. const d1 = Math.random() * 0xffffffff | 0;
  271. const d2 = Math.random() * 0xffffffff | 0;
  272. const d3 = Math.random() * 0xffffffff | 0;
  273. const uuid = _lut[d0 & 0xff] + _lut[d0 >> 8 & 0xff] + _lut[d0 >> 16 & 0xff] + _lut[d0 >> 24 & 0xff] + '-' + _lut[d1 & 0xff] + _lut[d1 >> 8 & 0xff] + '-' + _lut[d1 >> 16 & 0x0f | 0x40] + _lut[d1 >> 24 & 0xff] + '-' + _lut[d2 & 0x3f | 0x80] + _lut[d2 >> 8 & 0xff] + '-' + _lut[d2 >> 16 & 0xff] + _lut[d2 >> 24 & 0xff] + _lut[d3 & 0xff] + _lut[d3 >> 8 & 0xff] + _lut[d3 >> 16 & 0xff] + _lut[d3 >> 24 & 0xff]; // .toUpperCase() here flattens concatenated strings to save heap memory space.
  274. return uuid.toUpperCase();
  275. }
  276. function clamp(value, min, max) {
  277. return Math.max(min, Math.min(max, value));
  278. } // compute euclidian modulo of m % n
  279. // https://en.wikipedia.org/wiki/Modulo_operation
  280. function euclideanModulo(n, m) {
  281. return (n % m + m) % m;
  282. } // Linear mapping from range <a1, a2> to range <b1, b2>
  283. function mapLinear(x, a1, a2, b1, b2) {
  284. return b1 + (x - a1) * (b2 - b1) / (a2 - a1);
  285. } // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  286. function inverseLerp(x, y, value) {
  287. if (x !== y) {
  288. return (value - x) / (y - x);
  289. } else {
  290. return 0;
  291. }
  292. } // https://en.wikipedia.org/wiki/Linear_interpolation
  293. function lerp(x, y, t) {
  294. return (1 - t) * x + t * y;
  295. } // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  296. function damp(x, y, lambda, dt) {
  297. return lerp(x, y, 1 - Math.exp(-lambda * dt));
  298. } // https://www.desmos.com/calculator/vcsjnyz7x4
  299. function pingpong(x, length = 1) {
  300. return length - Math.abs(euclideanModulo(x, length * 2) - length);
  301. } // http://en.wikipedia.org/wiki/Smoothstep
  302. function smoothstep(x, min, max) {
  303. if (x <= min) return 0;
  304. if (x >= max) return 1;
  305. x = (x - min) / (max - min);
  306. return x * x * (3 - 2 * x);
  307. }
  308. function smootherstep(x, min, max) {
  309. if (x <= min) return 0;
  310. if (x >= max) return 1;
  311. x = (x - min) / (max - min);
  312. return x * x * x * (x * (x * 6 - 15) + 10);
  313. } // Random integer from <low, high> interval
  314. function randInt(low, high) {
  315. return low + Math.floor(Math.random() * (high - low + 1));
  316. } // Random float from <low, high> interval
  317. function randFloat(low, high) {
  318. return low + Math.random() * (high - low);
  319. } // Random float from <-range/2, range/2> interval
  320. function randFloatSpread(range) {
  321. return range * (0.5 - Math.random());
  322. } // Deterministic pseudo-random float in the interval [ 0, 1 ]
  323. function seededRandom(s) {
  324. if (s !== undefined) _seed = s % 2147483647; // Park-Miller algorithm
  325. _seed = _seed * 16807 % 2147483647;
  326. return (_seed - 1) / 2147483646;
  327. }
  328. function degToRad(degrees) {
  329. return degrees * DEG2RAD;
  330. }
  331. function radToDeg(radians) {
  332. return radians * RAD2DEG;
  333. }
  334. function isPowerOfTwo(value) {
  335. return (value & value - 1) === 0 && value !== 0;
  336. }
  337. function ceilPowerOfTwo(value) {
  338. return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
  339. }
  340. function floorPowerOfTwo(value) {
  341. return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
  342. }
  343. function setQuaternionFromProperEuler(q, a, b, c, order) {
  344. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  345. // rotations are applied to the axes in the order specified by 'order'
  346. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  347. // angles are in radians
  348. const cos = Math.cos;
  349. const sin = Math.sin;
  350. const c2 = cos(b / 2);
  351. const s2 = sin(b / 2);
  352. const c13 = cos((a + c) / 2);
  353. const s13 = sin((a + c) / 2);
  354. const c1_3 = cos((a - c) / 2);
  355. const s1_3 = sin((a - c) / 2);
  356. const c3_1 = cos((c - a) / 2);
  357. const s3_1 = sin((c - a) / 2);
  358. switch (order) {
  359. case 'XYX':
  360. q.set(c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13);
  361. break;
  362. case 'YZY':
  363. q.set(s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13);
  364. break;
  365. case 'ZXZ':
  366. q.set(s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13);
  367. break;
  368. case 'XZX':
  369. q.set(c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13);
  370. break;
  371. case 'YXY':
  372. q.set(s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13);
  373. break;
  374. case 'ZYZ':
  375. q.set(s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13);
  376. break;
  377. default:
  378. console.warn('THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order);
  379. }
  380. }
  381. var MathUtils = /*#__PURE__*/Object.freeze({
  382. __proto__: null,
  383. DEG2RAD: DEG2RAD,
  384. RAD2DEG: RAD2DEG,
  385. generateUUID: generateUUID,
  386. clamp: clamp,
  387. euclideanModulo: euclideanModulo,
  388. mapLinear: mapLinear,
  389. inverseLerp: inverseLerp,
  390. lerp: lerp,
  391. damp: damp,
  392. pingpong: pingpong,
  393. smoothstep: smoothstep,
  394. smootherstep: smootherstep,
  395. randInt: randInt,
  396. randFloat: randFloat,
  397. randFloatSpread: randFloatSpread,
  398. seededRandom: seededRandom,
  399. degToRad: degToRad,
  400. radToDeg: radToDeg,
  401. isPowerOfTwo: isPowerOfTwo,
  402. ceilPowerOfTwo: ceilPowerOfTwo,
  403. floorPowerOfTwo: floorPowerOfTwo,
  404. setQuaternionFromProperEuler: setQuaternionFromProperEuler
  405. });
  406. class Vector2 {
  407. constructor(x = 0, y = 0) {
  408. this.x = x;
  409. this.y = y;
  410. }
  411. get width() {
  412. return this.x;
  413. }
  414. set width(value) {
  415. this.x = value;
  416. }
  417. get height() {
  418. return this.y;
  419. }
  420. set height(value) {
  421. this.y = value;
  422. }
  423. set(x, y) {
  424. this.x = x;
  425. this.y = y;
  426. return this;
  427. }
  428. setScalar(scalar) {
  429. this.x = scalar;
  430. this.y = scalar;
  431. return this;
  432. }
  433. setX(x) {
  434. this.x = x;
  435. return this;
  436. }
  437. setY(y) {
  438. this.y = y;
  439. return this;
  440. }
  441. setComponent(index, value) {
  442. switch (index) {
  443. case 0:
  444. this.x = value;
  445. break;
  446. case 1:
  447. this.y = value;
  448. break;
  449. default:
  450. throw new Error('index is out of range: ' + index);
  451. }
  452. return this;
  453. }
  454. getComponent(index) {
  455. switch (index) {
  456. case 0:
  457. return this.x;
  458. case 1:
  459. return this.y;
  460. default:
  461. throw new Error('index is out of range: ' + index);
  462. }
  463. }
  464. clone() {
  465. return new this.constructor(this.x, this.y);
  466. }
  467. copy(v) {
  468. this.x = v.x;
  469. this.y = v.y;
  470. return this;
  471. }
  472. add(v, w) {
  473. if (w !== undefined) {
  474. console.warn('THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  475. return this.addVectors(v, w);
  476. }
  477. this.x += v.x;
  478. this.y += v.y;
  479. return this;
  480. }
  481. addScalar(s) {
  482. this.x += s;
  483. this.y += s;
  484. return this;
  485. }
  486. addVectors(a, b) {
  487. this.x = a.x + b.x;
  488. this.y = a.y + b.y;
  489. return this;
  490. }
  491. addScaledVector(v, s) {
  492. this.x += v.x * s;
  493. this.y += v.y * s;
  494. return this;
  495. }
  496. sub(v, w) {
  497. if (w !== undefined) {
  498. console.warn('THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  499. return this.subVectors(v, w);
  500. }
  501. this.x -= v.x;
  502. this.y -= v.y;
  503. return this;
  504. }
  505. subScalar(s) {
  506. this.x -= s;
  507. this.y -= s;
  508. return this;
  509. }
  510. subVectors(a, b) {
  511. this.x = a.x - b.x;
  512. this.y = a.y - b.y;
  513. return this;
  514. }
  515. multiply(v) {
  516. this.x *= v.x;
  517. this.y *= v.y;
  518. return this;
  519. }
  520. multiplyScalar(scalar) {
  521. this.x *= scalar;
  522. this.y *= scalar;
  523. return this;
  524. }
  525. divide(v) {
  526. this.x /= v.x;
  527. this.y /= v.y;
  528. return this;
  529. }
  530. divideScalar(scalar) {
  531. return this.multiplyScalar(1 / scalar);
  532. }
  533. applyMatrix3(m) {
  534. const x = this.x,
  535. y = this.y;
  536. const e = m.elements;
  537. this.x = e[0] * x + e[3] * y + e[6];
  538. this.y = e[1] * x + e[4] * y + e[7];
  539. return this;
  540. }
  541. min(v) {
  542. this.x = Math.min(this.x, v.x);
  543. this.y = Math.min(this.y, v.y);
  544. return this;
  545. }
  546. max(v) {
  547. this.x = Math.max(this.x, v.x);
  548. this.y = Math.max(this.y, v.y);
  549. return this;
  550. }
  551. clamp(min, max) {
  552. // assumes min < max, componentwise
  553. this.x = Math.max(min.x, Math.min(max.x, this.x));
  554. this.y = Math.max(min.y, Math.min(max.y, this.y));
  555. return this;
  556. }
  557. clampScalar(minVal, maxVal) {
  558. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  559. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  560. return this;
  561. }
  562. clampLength(min, max) {
  563. const length = this.length();
  564. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  565. }
  566. floor() {
  567. this.x = Math.floor(this.x);
  568. this.y = Math.floor(this.y);
  569. return this;
  570. }
  571. ceil() {
  572. this.x = Math.ceil(this.x);
  573. this.y = Math.ceil(this.y);
  574. return this;
  575. }
  576. round() {
  577. this.x = Math.round(this.x);
  578. this.y = Math.round(this.y);
  579. return this;
  580. }
  581. roundToZero() {
  582. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  583. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  584. return this;
  585. }
  586. negate() {
  587. this.x = -this.x;
  588. this.y = -this.y;
  589. return this;
  590. }
  591. dot(v) {
  592. return this.x * v.x + this.y * v.y;
  593. }
  594. cross(v) {
  595. return this.x * v.y - this.y * v.x;
  596. }
  597. lengthSq() {
  598. return this.x * this.x + this.y * this.y;
  599. }
  600. length() {
  601. return Math.sqrt(this.x * this.x + this.y * this.y);
  602. }
  603. manhattanLength() {
  604. return Math.abs(this.x) + Math.abs(this.y);
  605. }
  606. normalize() {
  607. return this.divideScalar(this.length() || 1);
  608. }
  609. angle() {
  610. // computes the angle in radians with respect to the positive x-axis
  611. const angle = Math.atan2(-this.y, -this.x) + Math.PI;
  612. return angle;
  613. }
  614. distanceTo(v) {
  615. return Math.sqrt(this.distanceToSquared(v));
  616. }
  617. distanceToSquared(v) {
  618. const dx = this.x - v.x,
  619. dy = this.y - v.y;
  620. return dx * dx + dy * dy;
  621. }
  622. manhattanDistanceTo(v) {
  623. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);
  624. }
  625. setLength(length) {
  626. return this.normalize().multiplyScalar(length);
  627. }
  628. lerp(v, alpha) {
  629. this.x += (v.x - this.x) * alpha;
  630. this.y += (v.y - this.y) * alpha;
  631. return this;
  632. }
  633. lerpVectors(v1, v2, alpha) {
  634. this.x = v1.x + (v2.x - v1.x) * alpha;
  635. this.y = v1.y + (v2.y - v1.y) * alpha;
  636. return this;
  637. }
  638. equals(v) {
  639. return v.x === this.x && v.y === this.y;
  640. }
  641. fromArray(array, offset = 0) {
  642. this.x = array[offset];
  643. this.y = array[offset + 1];
  644. return this;
  645. }
  646. toArray(array = [], offset = 0) {
  647. array[offset] = this.x;
  648. array[offset + 1] = this.y;
  649. return array;
  650. }
  651. fromBufferAttribute(attribute, index, offset) {
  652. if (offset !== undefined) {
  653. console.warn('THREE.Vector2: offset has been removed from .fromBufferAttribute().');
  654. }
  655. this.x = attribute.getX(index);
  656. this.y = attribute.getY(index);
  657. return this;
  658. }
  659. rotateAround(center, angle) {
  660. const c = Math.cos(angle),
  661. s = Math.sin(angle);
  662. const x = this.x - center.x;
  663. const y = this.y - center.y;
  664. this.x = x * c - y * s + center.x;
  665. this.y = x * s + y * c + center.y;
  666. return this;
  667. }
  668. random() {
  669. this.x = Math.random();
  670. this.y = Math.random();
  671. return this;
  672. }
  673. }
  674. Vector2.prototype.isVector2 = true;
  675. class Matrix3 {
  676. constructor() {
  677. this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  678. if (arguments.length > 0) {
  679. console.error('THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.');
  680. }
  681. }
  682. set(n11, n12, n13, n21, n22, n23, n31, n32, n33) {
  683. const te = this.elements;
  684. te[0] = n11;
  685. te[1] = n21;
  686. te[2] = n31;
  687. te[3] = n12;
  688. te[4] = n22;
  689. te[5] = n32;
  690. te[6] = n13;
  691. te[7] = n23;
  692. te[8] = n33;
  693. return this;
  694. }
  695. identity() {
  696. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  697. return this;
  698. }
  699. copy(m) {
  700. const te = this.elements;
  701. const me = m.elements;
  702. te[0] = me[0];
  703. te[1] = me[1];
  704. te[2] = me[2];
  705. te[3] = me[3];
  706. te[4] = me[4];
  707. te[5] = me[5];
  708. te[6] = me[6];
  709. te[7] = me[7];
  710. te[8] = me[8];
  711. return this;
  712. }
  713. extractBasis(xAxis, yAxis, zAxis) {
  714. xAxis.setFromMatrix3Column(this, 0);
  715. yAxis.setFromMatrix3Column(this, 1);
  716. zAxis.setFromMatrix3Column(this, 2);
  717. return this;
  718. }
  719. setFromMatrix4(m) {
  720. const me = m.elements;
  721. this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]);
  722. return this;
  723. }
  724. multiply(m) {
  725. return this.multiplyMatrices(this, m);
  726. }
  727. premultiply(m) {
  728. return this.multiplyMatrices(m, this);
  729. }
  730. multiplyMatrices(a, b) {
  731. const ae = a.elements;
  732. const be = b.elements;
  733. const te = this.elements;
  734. const a11 = ae[0],
  735. a12 = ae[3],
  736. a13 = ae[6];
  737. const a21 = ae[1],
  738. a22 = ae[4],
  739. a23 = ae[7];
  740. const a31 = ae[2],
  741. a32 = ae[5],
  742. a33 = ae[8];
  743. const b11 = be[0],
  744. b12 = be[3],
  745. b13 = be[6];
  746. const b21 = be[1],
  747. b22 = be[4],
  748. b23 = be[7];
  749. const b31 = be[2],
  750. b32 = be[5],
  751. b33 = be[8];
  752. te[0] = a11 * b11 + a12 * b21 + a13 * b31;
  753. te[3] = a11 * b12 + a12 * b22 + a13 * b32;
  754. te[6] = a11 * b13 + a12 * b23 + a13 * b33;
  755. te[1] = a21 * b11 + a22 * b21 + a23 * b31;
  756. te[4] = a21 * b12 + a22 * b22 + a23 * b32;
  757. te[7] = a21 * b13 + a22 * b23 + a23 * b33;
  758. te[2] = a31 * b11 + a32 * b21 + a33 * b31;
  759. te[5] = a31 * b12 + a32 * b22 + a33 * b32;
  760. te[8] = a31 * b13 + a32 * b23 + a33 * b33;
  761. return this;
  762. }
  763. multiplyScalar(s) {
  764. const te = this.elements;
  765. te[0] *= s;
  766. te[3] *= s;
  767. te[6] *= s;
  768. te[1] *= s;
  769. te[4] *= s;
  770. te[7] *= s;
  771. te[2] *= s;
  772. te[5] *= s;
  773. te[8] *= s;
  774. return this;
  775. }
  776. determinant() {
  777. const te = this.elements;
  778. const a = te[0],
  779. b = te[1],
  780. c = te[2],
  781. d = te[3],
  782. e = te[4],
  783. f = te[5],
  784. g = te[6],
  785. h = te[7],
  786. i = te[8];
  787. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  788. }
  789. invert() {
  790. const te = this.elements,
  791. n11 = te[0],
  792. n21 = te[1],
  793. n31 = te[2],
  794. n12 = te[3],
  795. n22 = te[4],
  796. n32 = te[5],
  797. n13 = te[6],
  798. n23 = te[7],
  799. n33 = te[8],
  800. t11 = n33 * n22 - n32 * n23,
  801. t12 = n32 * n13 - n33 * n12,
  802. t13 = n23 * n12 - n22 * n13,
  803. det = n11 * t11 + n21 * t12 + n31 * t13;
  804. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  805. const detInv = 1 / det;
  806. te[0] = t11 * detInv;
  807. te[1] = (n31 * n23 - n33 * n21) * detInv;
  808. te[2] = (n32 * n21 - n31 * n22) * detInv;
  809. te[3] = t12 * detInv;
  810. te[4] = (n33 * n11 - n31 * n13) * detInv;
  811. te[5] = (n31 * n12 - n32 * n11) * detInv;
  812. te[6] = t13 * detInv;
  813. te[7] = (n21 * n13 - n23 * n11) * detInv;
  814. te[8] = (n22 * n11 - n21 * n12) * detInv;
  815. return this;
  816. }
  817. transpose() {
  818. let tmp;
  819. const m = this.elements;
  820. tmp = m[1];
  821. m[1] = m[3];
  822. m[3] = tmp;
  823. tmp = m[2];
  824. m[2] = m[6];
  825. m[6] = tmp;
  826. tmp = m[5];
  827. m[5] = m[7];
  828. m[7] = tmp;
  829. return this;
  830. }
  831. getNormalMatrix(matrix4) {
  832. return this.setFromMatrix4(matrix4).invert().transpose();
  833. }
  834. transposeIntoArray(r) {
  835. const m = this.elements;
  836. r[0] = m[0];
  837. r[1] = m[3];
  838. r[2] = m[6];
  839. r[3] = m[1];
  840. r[4] = m[4];
  841. r[5] = m[7];
  842. r[6] = m[2];
  843. r[7] = m[5];
  844. r[8] = m[8];
  845. return this;
  846. }
  847. setUvTransform(tx, ty, sx, sy, rotation, cx, cy) {
  848. const c = Math.cos(rotation);
  849. const s = Math.sin(rotation);
  850. this.set(sx * c, sx * s, -sx * (c * cx + s * cy) + cx + tx, -sy * s, sy * c, -sy * (-s * cx + c * cy) + cy + ty, 0, 0, 1);
  851. return this;
  852. }
  853. scale(sx, sy) {
  854. const te = this.elements;
  855. te[0] *= sx;
  856. te[3] *= sx;
  857. te[6] *= sx;
  858. te[1] *= sy;
  859. te[4] *= sy;
  860. te[7] *= sy;
  861. return this;
  862. }
  863. rotate(theta) {
  864. const c = Math.cos(theta);
  865. const s = Math.sin(theta);
  866. const te = this.elements;
  867. const a11 = te[0],
  868. a12 = te[3],
  869. a13 = te[6];
  870. const a21 = te[1],
  871. a22 = te[4],
  872. a23 = te[7];
  873. te[0] = c * a11 + s * a21;
  874. te[3] = c * a12 + s * a22;
  875. te[6] = c * a13 + s * a23;
  876. te[1] = -s * a11 + c * a21;
  877. te[4] = -s * a12 + c * a22;
  878. te[7] = -s * a13 + c * a23;
  879. return this;
  880. }
  881. translate(tx, ty) {
  882. const te = this.elements;
  883. te[0] += tx * te[2];
  884. te[3] += tx * te[5];
  885. te[6] += tx * te[8];
  886. te[1] += ty * te[2];
  887. te[4] += ty * te[5];
  888. te[7] += ty * te[8];
  889. return this;
  890. }
  891. equals(matrix) {
  892. const te = this.elements;
  893. const me = matrix.elements;
  894. for (let i = 0; i < 9; i++) {
  895. if (te[i] !== me[i]) return false;
  896. }
  897. return true;
  898. }
  899. fromArray(array, offset = 0) {
  900. for (let i = 0; i < 9; i++) {
  901. this.elements[i] = array[i + offset];
  902. }
  903. return this;
  904. }
  905. toArray(array = [], offset = 0) {
  906. const te = this.elements;
  907. array[offset] = te[0];
  908. array[offset + 1] = te[1];
  909. array[offset + 2] = te[2];
  910. array[offset + 3] = te[3];
  911. array[offset + 4] = te[4];
  912. array[offset + 5] = te[5];
  913. array[offset + 6] = te[6];
  914. array[offset + 7] = te[7];
  915. array[offset + 8] = te[8];
  916. return array;
  917. }
  918. clone() {
  919. return new this.constructor().fromArray(this.elements);
  920. }
  921. }
  922. Matrix3.prototype.isMatrix3 = true;
  923. let _canvas;
  924. class ImageUtils {
  925. static getDataURL(image) {
  926. if (/^data:/i.test(image.src)) {
  927. return image.src;
  928. }
  929. if (typeof HTMLCanvasElement == 'undefined') {
  930. return image.src;
  931. }
  932. let canvas;
  933. if (image instanceof HTMLCanvasElement) {
  934. canvas = image;
  935. } else {
  936. if (_canvas === undefined) _canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  937. _canvas.width = image.width;
  938. _canvas.height = image.height;
  939. const context = _canvas.getContext('2d');
  940. if (image instanceof ImageData) {
  941. context.putImageData(image, 0, 0);
  942. } else {
  943. context.drawImage(image, 0, 0, image.width, image.height);
  944. }
  945. canvas = _canvas;
  946. }
  947. if (canvas.width > 2048 || canvas.height > 2048) {
  948. console.warn('THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image);
  949. return canvas.toDataURL('image/jpeg', 0.6);
  950. } else {
  951. return canvas.toDataURL('image/png');
  952. }
  953. }
  954. }
  955. let textureId = 0;
  956. class Texture extends EventDispatcher {
  957. constructor(image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = 1, encoding = LinearEncoding) {
  958. super();
  959. Object.defineProperty(this, 'id', {
  960. value: textureId++
  961. });
  962. this.uuid = generateUUID();
  963. this.name = '';
  964. this.image = image;
  965. this.mipmaps = [];
  966. this.mapping = mapping;
  967. this.wrapS = wrapS;
  968. this.wrapT = wrapT;
  969. this.magFilter = magFilter;
  970. this.minFilter = minFilter;
  971. this.anisotropy = anisotropy;
  972. this.format = format;
  973. this.internalFormat = null;
  974. this.type = type;
  975. this.offset = new Vector2(0, 0);
  976. this.repeat = new Vector2(1, 1);
  977. this.center = new Vector2(0, 0);
  978. this.rotation = 0;
  979. this.matrixAutoUpdate = true;
  980. this.matrix = new Matrix3();
  981. this.generateMipmaps = true;
  982. this.premultiplyAlpha = false;
  983. this.flipY = true;
  984. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  985. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  986. //
  987. // Also changing the encoding after already used by a Material will not automatically make the Material
  988. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  989. this.encoding = encoding;
  990. this.version = 0;
  991. this.onUpdate = null;
  992. }
  993. updateMatrix() {
  994. this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  995. }
  996. clone() {
  997. return new this.constructor().copy(this);
  998. }
  999. copy(source) {
  1000. this.name = source.name;
  1001. this.image = source.image;
  1002. this.mipmaps = source.mipmaps.slice(0);
  1003. this.mapping = source.mapping;
  1004. this.wrapS = source.wrapS;
  1005. this.wrapT = source.wrapT;
  1006. this.magFilter = source.magFilter;
  1007. this.minFilter = source.minFilter;
  1008. this.anisotropy = source.anisotropy;
  1009. this.format = source.format;
  1010. this.internalFormat = source.internalFormat;
  1011. this.type = source.type;
  1012. this.offset.copy(source.offset);
  1013. this.repeat.copy(source.repeat);
  1014. this.center.copy(source.center);
  1015. this.rotation = source.rotation;
  1016. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1017. this.matrix.copy(source.matrix);
  1018. this.generateMipmaps = source.generateMipmaps;
  1019. this.premultiplyAlpha = source.premultiplyAlpha;
  1020. this.flipY = source.flipY;
  1021. this.unpackAlignment = source.unpackAlignment;
  1022. this.encoding = source.encoding;
  1023. return this;
  1024. }
  1025. toJSON(meta) {
  1026. const isRootObject = meta === undefined || typeof meta === 'string';
  1027. if (!isRootObject && meta.textures[this.uuid] !== undefined) {
  1028. return meta.textures[this.uuid];
  1029. }
  1030. const output = {
  1031. metadata: {
  1032. version: 4.5,
  1033. type: 'Texture',
  1034. generator: 'Texture.toJSON'
  1035. },
  1036. uuid: this.uuid,
  1037. name: this.name,
  1038. mapping: this.mapping,
  1039. repeat: [this.repeat.x, this.repeat.y],
  1040. offset: [this.offset.x, this.offset.y],
  1041. center: [this.center.x, this.center.y],
  1042. rotation: this.rotation,
  1043. wrap: [this.wrapS, this.wrapT],
  1044. format: this.format,
  1045. type: this.type,
  1046. encoding: this.encoding,
  1047. minFilter: this.minFilter,
  1048. magFilter: this.magFilter,
  1049. anisotropy: this.anisotropy,
  1050. flipY: this.flipY,
  1051. premultiplyAlpha: this.premultiplyAlpha,
  1052. unpackAlignment: this.unpackAlignment
  1053. };
  1054. if (this.image !== undefined) {
  1055. // TODO: Move to THREE.Image
  1056. const image = this.image;
  1057. if (image.uuid === undefined) {
  1058. image.uuid = generateUUID(); // UGH
  1059. }
  1060. if (!isRootObject && meta.images[image.uuid] === undefined) {
  1061. let url;
  1062. if (Array.isArray(image)) {
  1063. // process array of images e.g. CubeTexture
  1064. url = [];
  1065. for (let i = 0, l = image.length; i < l; i++) {
  1066. // check cube texture with data textures
  1067. if (image[i].isDataTexture) {
  1068. url.push(serializeImage(image[i].image));
  1069. } else {
  1070. url.push(serializeImage(image[i]));
  1071. }
  1072. }
  1073. } else {
  1074. // process single image
  1075. url = serializeImage(image);
  1076. }
  1077. meta.images[image.uuid] = {
  1078. uuid: image.uuid,
  1079. url: url
  1080. };
  1081. }
  1082. output.image = image.uuid;
  1083. }
  1084. if (!isRootObject) {
  1085. meta.textures[this.uuid] = output;
  1086. }
  1087. return output;
  1088. }
  1089. dispose() {
  1090. this.dispatchEvent({
  1091. type: 'dispose'
  1092. });
  1093. }
  1094. transformUv(uv) {
  1095. if (this.mapping !== UVMapping) return uv;
  1096. uv.applyMatrix3(this.matrix);
  1097. if (uv.x < 0 || uv.x > 1) {
  1098. switch (this.wrapS) {
  1099. case RepeatWrapping:
  1100. uv.x = uv.x - Math.floor(uv.x);
  1101. break;
  1102. case ClampToEdgeWrapping:
  1103. uv.x = uv.x < 0 ? 0 : 1;
  1104. break;
  1105. case MirroredRepeatWrapping:
  1106. if (Math.abs(Math.floor(uv.x) % 2) === 1) {
  1107. uv.x = Math.ceil(uv.x) - uv.x;
  1108. } else {
  1109. uv.x = uv.x - Math.floor(uv.x);
  1110. }
  1111. break;
  1112. }
  1113. }
  1114. if (uv.y < 0 || uv.y > 1) {
  1115. switch (this.wrapT) {
  1116. case RepeatWrapping:
  1117. uv.y = uv.y - Math.floor(uv.y);
  1118. break;
  1119. case ClampToEdgeWrapping:
  1120. uv.y = uv.y < 0 ? 0 : 1;
  1121. break;
  1122. case MirroredRepeatWrapping:
  1123. if (Math.abs(Math.floor(uv.y) % 2) === 1) {
  1124. uv.y = Math.ceil(uv.y) - uv.y;
  1125. } else {
  1126. uv.y = uv.y - Math.floor(uv.y);
  1127. }
  1128. break;
  1129. }
  1130. }
  1131. if (this.flipY) {
  1132. uv.y = 1 - uv.y;
  1133. }
  1134. return uv;
  1135. }
  1136. set needsUpdate(value) {
  1137. if (value === true) this.version++;
  1138. }
  1139. }
  1140. Texture.DEFAULT_IMAGE = undefined;
  1141. Texture.DEFAULT_MAPPING = UVMapping;
  1142. Texture.prototype.isTexture = true;
  1143. function serializeImage(image) {
  1144. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  1145. // default images
  1146. return ImageUtils.getDataURL(image);
  1147. } else {
  1148. if (image.data) {
  1149. // images of DataTexture
  1150. return {
  1151. data: Array.prototype.slice.call(image.data),
  1152. width: image.width,
  1153. height: image.height,
  1154. type: image.data.constructor.name
  1155. };
  1156. } else {
  1157. console.warn('THREE.Texture: Unable to serialize Texture.');
  1158. return {};
  1159. }
  1160. }
  1161. }
  1162. class Vector4 {
  1163. constructor(x = 0, y = 0, z = 0, w = 1) {
  1164. this.x = x;
  1165. this.y = y;
  1166. this.z = z;
  1167. this.w = w;
  1168. }
  1169. get width() {
  1170. return this.z;
  1171. }
  1172. set width(value) {
  1173. this.z = value;
  1174. }
  1175. get height() {
  1176. return this.w;
  1177. }
  1178. set height(value) {
  1179. this.w = value;
  1180. }
  1181. set(x, y, z, w) {
  1182. this.x = x;
  1183. this.y = y;
  1184. this.z = z;
  1185. this.w = w;
  1186. return this;
  1187. }
  1188. setScalar(scalar) {
  1189. this.x = scalar;
  1190. this.y = scalar;
  1191. this.z = scalar;
  1192. this.w = scalar;
  1193. return this;
  1194. }
  1195. setX(x) {
  1196. this.x = x;
  1197. return this;
  1198. }
  1199. setY(y) {
  1200. this.y = y;
  1201. return this;
  1202. }
  1203. setZ(z) {
  1204. this.z = z;
  1205. return this;
  1206. }
  1207. setW(w) {
  1208. this.w = w;
  1209. return this;
  1210. }
  1211. setComponent(index, value) {
  1212. switch (index) {
  1213. case 0:
  1214. this.x = value;
  1215. break;
  1216. case 1:
  1217. this.y = value;
  1218. break;
  1219. case 2:
  1220. this.z = value;
  1221. break;
  1222. case 3:
  1223. this.w = value;
  1224. break;
  1225. default:
  1226. throw new Error('index is out of range: ' + index);
  1227. }
  1228. return this;
  1229. }
  1230. getComponent(index) {
  1231. switch (index) {
  1232. case 0:
  1233. return this.x;
  1234. case 1:
  1235. return this.y;
  1236. case 2:
  1237. return this.z;
  1238. case 3:
  1239. return this.w;
  1240. default:
  1241. throw new Error('index is out of range: ' + index);
  1242. }
  1243. }
  1244. clone() {
  1245. return new this.constructor(this.x, this.y, this.z, this.w);
  1246. }
  1247. copy(v) {
  1248. this.x = v.x;
  1249. this.y = v.y;
  1250. this.z = v.z;
  1251. this.w = v.w !== undefined ? v.w : 1;
  1252. return this;
  1253. }
  1254. add(v, w) {
  1255. if (w !== undefined) {
  1256. console.warn('THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  1257. return this.addVectors(v, w);
  1258. }
  1259. this.x += v.x;
  1260. this.y += v.y;
  1261. this.z += v.z;
  1262. this.w += v.w;
  1263. return this;
  1264. }
  1265. addScalar(s) {
  1266. this.x += s;
  1267. this.y += s;
  1268. this.z += s;
  1269. this.w += s;
  1270. return this;
  1271. }
  1272. addVectors(a, b) {
  1273. this.x = a.x + b.x;
  1274. this.y = a.y + b.y;
  1275. this.z = a.z + b.z;
  1276. this.w = a.w + b.w;
  1277. return this;
  1278. }
  1279. addScaledVector(v, s) {
  1280. this.x += v.x * s;
  1281. this.y += v.y * s;
  1282. this.z += v.z * s;
  1283. this.w += v.w * s;
  1284. return this;
  1285. }
  1286. sub(v, w) {
  1287. if (w !== undefined) {
  1288. console.warn('THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  1289. return this.subVectors(v, w);
  1290. }
  1291. this.x -= v.x;
  1292. this.y -= v.y;
  1293. this.z -= v.z;
  1294. this.w -= v.w;
  1295. return this;
  1296. }
  1297. subScalar(s) {
  1298. this.x -= s;
  1299. this.y -= s;
  1300. this.z -= s;
  1301. this.w -= s;
  1302. return this;
  1303. }
  1304. subVectors(a, b) {
  1305. this.x = a.x - b.x;
  1306. this.y = a.y - b.y;
  1307. this.z = a.z - b.z;
  1308. this.w = a.w - b.w;
  1309. return this;
  1310. }
  1311. multiply(v) {
  1312. this.x *= v.x;
  1313. this.y *= v.y;
  1314. this.z *= v.z;
  1315. this.w *= v.w;
  1316. return this;
  1317. }
  1318. multiplyScalar(scalar) {
  1319. this.x *= scalar;
  1320. this.y *= scalar;
  1321. this.z *= scalar;
  1322. this.w *= scalar;
  1323. return this;
  1324. }
  1325. applyMatrix4(m) {
  1326. const x = this.x,
  1327. y = this.y,
  1328. z = this.z,
  1329. w = this.w;
  1330. const e = m.elements;
  1331. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1332. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1333. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1334. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1335. return this;
  1336. }
  1337. divideScalar(scalar) {
  1338. return this.multiplyScalar(1 / scalar);
  1339. }
  1340. setAxisAngleFromQuaternion(q) {
  1341. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1342. // q is assumed to be normalized
  1343. this.w = 2 * Math.acos(q.w);
  1344. const s = Math.sqrt(1 - q.w * q.w);
  1345. if (s < 0.0001) {
  1346. this.x = 1;
  1347. this.y = 0;
  1348. this.z = 0;
  1349. } else {
  1350. this.x = q.x / s;
  1351. this.y = q.y / s;
  1352. this.z = q.z / s;
  1353. }
  1354. return this;
  1355. }
  1356. setAxisAngleFromRotationMatrix(m) {
  1357. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1358. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1359. let angle, x, y, z; // variables for result
  1360. const epsilon = 0.01,
  1361. // margin to allow for rounding errors
  1362. epsilon2 = 0.1,
  1363. // margin to distinguish between 0 and 180 degrees
  1364. te = m.elements,
  1365. m11 = te[0],
  1366. m12 = te[4],
  1367. m13 = te[8],
  1368. m21 = te[1],
  1369. m22 = te[5],
  1370. m23 = te[9],
  1371. m31 = te[2],
  1372. m32 = te[6],
  1373. m33 = te[10];
  1374. if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) {
  1375. // singularity found
  1376. // first check for identity matrix which must have +1 for all terms
  1377. // in leading diagonal and zero in other terms
  1378. if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) {
  1379. // this singularity is identity matrix so angle = 0
  1380. this.set(1, 0, 0, 0);
  1381. return this; // zero angle, arbitrary axis
  1382. } // otherwise this singularity is angle = 180
  1383. angle = Math.PI;
  1384. const xx = (m11 + 1) / 2;
  1385. const yy = (m22 + 1) / 2;
  1386. const zz = (m33 + 1) / 2;
  1387. const xy = (m12 + m21) / 4;
  1388. const xz = (m13 + m31) / 4;
  1389. const yz = (m23 + m32) / 4;
  1390. if (xx > yy && xx > zz) {
  1391. // m11 is the largest diagonal term
  1392. if (xx < epsilon) {
  1393. x = 0;
  1394. y = 0.707106781;
  1395. z = 0.707106781;
  1396. } else {
  1397. x = Math.sqrt(xx);
  1398. y = xy / x;
  1399. z = xz / x;
  1400. }
  1401. } else if (yy > zz) {
  1402. // m22 is the largest diagonal term
  1403. if (yy < epsilon) {
  1404. x = 0.707106781;
  1405. y = 0;
  1406. z = 0.707106781;
  1407. } else {
  1408. y = Math.sqrt(yy);
  1409. x = xy / y;
  1410. z = yz / y;
  1411. }
  1412. } else {
  1413. // m33 is the largest diagonal term so base result on this
  1414. if (zz < epsilon) {
  1415. x = 0.707106781;
  1416. y = 0.707106781;
  1417. z = 0;
  1418. } else {
  1419. z = Math.sqrt(zz);
  1420. x = xz / z;
  1421. y = yz / z;
  1422. }
  1423. }
  1424. this.set(x, y, z, angle);
  1425. return this; // return 180 deg rotation
  1426. } // as we have reached here there are no singularities so we can handle normally
  1427. let s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); // used to normalize
  1428. if (Math.abs(s) < 0.001) s = 1; // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1429. // caught by singularity test above, but I've left it in just in case
  1430. this.x = (m32 - m23) / s;
  1431. this.y = (m13 - m31) / s;
  1432. this.z = (m21 - m12) / s;
  1433. this.w = Math.acos((m11 + m22 + m33 - 1) / 2);
  1434. return this;
  1435. }
  1436. min(v) {
  1437. this.x = Math.min(this.x, v.x);
  1438. this.y = Math.min(this.y, v.y);
  1439. this.z = Math.min(this.z, v.z);
  1440. this.w = Math.min(this.w, v.w);
  1441. return this;
  1442. }
  1443. max(v) {
  1444. this.x = Math.max(this.x, v.x);
  1445. this.y = Math.max(this.y, v.y);
  1446. this.z = Math.max(this.z, v.z);
  1447. this.w = Math.max(this.w, v.w);
  1448. return this;
  1449. }
  1450. clamp(min, max) {
  1451. // assumes min < max, componentwise
  1452. this.x = Math.max(min.x, Math.min(max.x, this.x));
  1453. this.y = Math.max(min.y, Math.min(max.y, this.y));
  1454. this.z = Math.max(min.z, Math.min(max.z, this.z));
  1455. this.w = Math.max(min.w, Math.min(max.w, this.w));
  1456. return this;
  1457. }
  1458. clampScalar(minVal, maxVal) {
  1459. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  1460. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  1461. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  1462. this.w = Math.max(minVal, Math.min(maxVal, this.w));
  1463. return this;
  1464. }
  1465. clampLength(min, max) {
  1466. const length = this.length();
  1467. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  1468. }
  1469. floor() {
  1470. this.x = Math.floor(this.x);
  1471. this.y = Math.floor(this.y);
  1472. this.z = Math.floor(this.z);
  1473. this.w = Math.floor(this.w);
  1474. return this;
  1475. }
  1476. ceil() {
  1477. this.x = Math.ceil(this.x);
  1478. this.y = Math.ceil(this.y);
  1479. this.z = Math.ceil(this.z);
  1480. this.w = Math.ceil(this.w);
  1481. return this;
  1482. }
  1483. round() {
  1484. this.x = Math.round(this.x);
  1485. this.y = Math.round(this.y);
  1486. this.z = Math.round(this.z);
  1487. this.w = Math.round(this.w);
  1488. return this;
  1489. }
  1490. roundToZero() {
  1491. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  1492. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  1493. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  1494. this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w);
  1495. return this;
  1496. }
  1497. negate() {
  1498. this.x = -this.x;
  1499. this.y = -this.y;
  1500. this.z = -this.z;
  1501. this.w = -this.w;
  1502. return this;
  1503. }
  1504. dot(v) {
  1505. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1506. }
  1507. lengthSq() {
  1508. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1509. }
  1510. length() {
  1511. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1512. }
  1513. manhattanLength() {
  1514. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  1515. }
  1516. normalize() {
  1517. return this.divideScalar(this.length() || 1);
  1518. }
  1519. setLength(length) {
  1520. return this.normalize().multiplyScalar(length);
  1521. }
  1522. lerp(v, alpha) {
  1523. this.x += (v.x - this.x) * alpha;
  1524. this.y += (v.y - this.y) * alpha;
  1525. this.z += (v.z - this.z) * alpha;
  1526. this.w += (v.w - this.w) * alpha;
  1527. return this;
  1528. }
  1529. lerpVectors(v1, v2, alpha) {
  1530. this.x = v1.x + (v2.x - v1.x) * alpha;
  1531. this.y = v1.y + (v2.y - v1.y) * alpha;
  1532. this.z = v1.z + (v2.z - v1.z) * alpha;
  1533. this.w = v1.w + (v2.w - v1.w) * alpha;
  1534. return this;
  1535. }
  1536. equals(v) {
  1537. return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;
  1538. }
  1539. fromArray(array, offset = 0) {
  1540. this.x = array[offset];
  1541. this.y = array[offset + 1];
  1542. this.z = array[offset + 2];
  1543. this.w = array[offset + 3];
  1544. return this;
  1545. }
  1546. toArray(array = [], offset = 0) {
  1547. array[offset] = this.x;
  1548. array[offset + 1] = this.y;
  1549. array[offset + 2] = this.z;
  1550. array[offset + 3] = this.w;
  1551. return array;
  1552. }
  1553. fromBufferAttribute(attribute, index, offset) {
  1554. if (offset !== undefined) {
  1555. console.warn('THREE.Vector4: offset has been removed from .fromBufferAttribute().');
  1556. }
  1557. this.x = attribute.getX(index);
  1558. this.y = attribute.getY(index);
  1559. this.z = attribute.getZ(index);
  1560. this.w = attribute.getW(index);
  1561. return this;
  1562. }
  1563. random() {
  1564. this.x = Math.random();
  1565. this.y = Math.random();
  1566. this.z = Math.random();
  1567. this.w = Math.random();
  1568. return this;
  1569. }
  1570. }
  1571. Vector4.prototype.isVector4 = true;
  1572. /*
  1573. In options, we can specify:
  1574. * Texture parameters for an auto-generated target texture
  1575. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1576. */
  1577. class WebGLRenderTarget extends EventDispatcher {
  1578. constructor(width, height, options) {
  1579. super();
  1580. this.width = width;
  1581. this.height = height;
  1582. this.depth = 1;
  1583. this.scissor = new Vector4(0, 0, width, height);
  1584. this.scissorTest = false;
  1585. this.viewport = new Vector4(0, 0, width, height);
  1586. options = options || {};
  1587. this.texture = new Texture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  1588. this.texture.image = {};
  1589. this.texture.image.width = width;
  1590. this.texture.image.height = height;
  1591. this.texture.image.depth = 1;
  1592. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  1593. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  1594. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  1595. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  1596. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  1597. }
  1598. setTexture(texture) {
  1599. texture.image = {
  1600. width: this.width,
  1601. height: this.height,
  1602. depth: this.depth
  1603. };
  1604. this.texture = texture;
  1605. }
  1606. setSize(width, height, depth = 1) {
  1607. if (this.width !== width || this.height !== height || this.depth !== depth) {
  1608. this.width = width;
  1609. this.height = height;
  1610. this.depth = depth;
  1611. this.texture.image.width = width;
  1612. this.texture.image.height = height;
  1613. this.texture.image.depth = depth;
  1614. this.dispose();
  1615. }
  1616. this.viewport.set(0, 0, width, height);
  1617. this.scissor.set(0, 0, width, height);
  1618. }
  1619. clone() {
  1620. return new this.constructor().copy(this);
  1621. }
  1622. copy(source) {
  1623. this.width = source.width;
  1624. this.height = source.height;
  1625. this.depth = source.depth;
  1626. this.viewport.copy(source.viewport);
  1627. this.texture = source.texture.clone();
  1628. this.depthBuffer = source.depthBuffer;
  1629. this.stencilBuffer = source.stencilBuffer;
  1630. this.depthTexture = source.depthTexture;
  1631. return this;
  1632. }
  1633. dispose() {
  1634. this.dispatchEvent({
  1635. type: 'dispose'
  1636. });
  1637. }
  1638. }
  1639. WebGLRenderTarget.prototype.isWebGLRenderTarget = true;
  1640. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  1641. constructor(width, height, count) {
  1642. super(width, height);
  1643. const texture = this.texture;
  1644. this.texture = [];
  1645. for (let i = 0; i < count; i++) {
  1646. this.texture[i] = texture.clone();
  1647. }
  1648. }
  1649. setSize(width, height, depth = 1) {
  1650. if (this.width !== width || this.height !== height || this.depth !== depth) {
  1651. this.width = width;
  1652. this.height = height;
  1653. this.depth = depth;
  1654. for (let i = 0, il = this.texture.length; i < il; i++) {
  1655. this.texture[i].image.width = width;
  1656. this.texture[i].image.height = height;
  1657. this.texture[i].image.depth = depth;
  1658. }
  1659. this.dispose();
  1660. }
  1661. this.viewport.set(0, 0, width, height);
  1662. this.scissor.set(0, 0, width, height);
  1663. return this;
  1664. }
  1665. copy(source) {
  1666. this.dispose();
  1667. this.width = source.width;
  1668. this.height = source.height;
  1669. this.depth = source.depth;
  1670. this.viewport.set(0, 0, this.width, this.height);
  1671. this.scissor.set(0, 0, this.width, this.height);
  1672. this.depthBuffer = source.depthBuffer;
  1673. this.stencilBuffer = source.stencilBuffer;
  1674. this.depthTexture = source.depthTexture;
  1675. this.texture.length = 0;
  1676. for (let i = 0, il = source.texture.length; i < il; i++) {
  1677. this.texture[i] = source.texture[i].clone();
  1678. }
  1679. return this;
  1680. }
  1681. }
  1682. WebGLMultipleRenderTargets.prototype.isWebGLMultipleRenderTargets = true;
  1683. class WebGLMultisampleRenderTarget extends WebGLRenderTarget {
  1684. constructor(width, height, options) {
  1685. super(width, height, options);
  1686. this.samples = 4;
  1687. }
  1688. copy(source) {
  1689. super.copy.call(this, source);
  1690. this.samples = source.samples;
  1691. return this;
  1692. }
  1693. }
  1694. WebGLMultisampleRenderTarget.prototype.isWebGLMultisampleRenderTarget = true;
  1695. class Quaternion {
  1696. constructor(x = 0, y = 0, z = 0, w = 1) {
  1697. this._x = x;
  1698. this._y = y;
  1699. this._z = z;
  1700. this._w = w;
  1701. }
  1702. static slerp(qa, qb, qm, t) {
  1703. console.warn('THREE.Quaternion: Static .slerp() has been deprecated. Use qm.slerpQuaternions( qa, qb, t ) instead.');
  1704. return qm.slerpQuaternions(qa, qb, t);
  1705. }
  1706. static slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
  1707. // fuzz-free, array-based Quaternion SLERP operation
  1708. let x0 = src0[srcOffset0 + 0],
  1709. y0 = src0[srcOffset0 + 1],
  1710. z0 = src0[srcOffset0 + 2],
  1711. w0 = src0[srcOffset0 + 3];
  1712. const x1 = src1[srcOffset1 + 0],
  1713. y1 = src1[srcOffset1 + 1],
  1714. z1 = src1[srcOffset1 + 2],
  1715. w1 = src1[srcOffset1 + 3];
  1716. if (t === 0) {
  1717. dst[dstOffset + 0] = x0;
  1718. dst[dstOffset + 1] = y0;
  1719. dst[dstOffset + 2] = z0;
  1720. dst[dstOffset + 3] = w0;
  1721. return;
  1722. }
  1723. if (t === 1) {
  1724. dst[dstOffset + 0] = x1;
  1725. dst[dstOffset + 1] = y1;
  1726. dst[dstOffset + 2] = z1;
  1727. dst[dstOffset + 3] = w1;
  1728. return;
  1729. }
  1730. if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
  1731. let s = 1 - t;
  1732. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1733. dir = cos >= 0 ? 1 : -1,
  1734. sqrSin = 1 - cos * cos; // Skip the Slerp for tiny steps to avoid numeric problems:
  1735. if (sqrSin > Number.EPSILON) {
  1736. const sin = Math.sqrt(sqrSin),
  1737. len = Math.atan2(sin, cos * dir);
  1738. s = Math.sin(s * len) / sin;
  1739. t = Math.sin(t * len) / sin;
  1740. }
  1741. const tDir = t * dir;
  1742. x0 = x0 * s + x1 * tDir;
  1743. y0 = y0 * s + y1 * tDir;
  1744. z0 = z0 * s + z1 * tDir;
  1745. w0 = w0 * s + w1 * tDir; // Normalize in case we just did a lerp:
  1746. if (s === 1 - t) {
  1747. const f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
  1748. x0 *= f;
  1749. y0 *= f;
  1750. z0 *= f;
  1751. w0 *= f;
  1752. }
  1753. }
  1754. dst[dstOffset] = x0;
  1755. dst[dstOffset + 1] = y0;
  1756. dst[dstOffset + 2] = z0;
  1757. dst[dstOffset + 3] = w0;
  1758. }
  1759. static multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) {
  1760. const x0 = src0[srcOffset0];
  1761. const y0 = src0[srcOffset0 + 1];
  1762. const z0 = src0[srcOffset0 + 2];
  1763. const w0 = src0[srcOffset0 + 3];
  1764. const x1 = src1[srcOffset1];
  1765. const y1 = src1[srcOffset1 + 1];
  1766. const z1 = src1[srcOffset1 + 2];
  1767. const w1 = src1[srcOffset1 + 3];
  1768. dst[dstOffset] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  1769. dst[dstOffset + 1] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  1770. dst[dstOffset + 2] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  1771. dst[dstOffset + 3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  1772. return dst;
  1773. }
  1774. get x() {
  1775. return this._x;
  1776. }
  1777. set x(value) {
  1778. this._x = value;
  1779. this._onChangeCallback();
  1780. }
  1781. get y() {
  1782. return this._y;
  1783. }
  1784. set y(value) {
  1785. this._y = value;
  1786. this._onChangeCallback();
  1787. }
  1788. get z() {
  1789. return this._z;
  1790. }
  1791. set z(value) {
  1792. this._z = value;
  1793. this._onChangeCallback();
  1794. }
  1795. get w() {
  1796. return this._w;
  1797. }
  1798. set w(value) {
  1799. this._w = value;
  1800. this._onChangeCallback();
  1801. }
  1802. set(x, y, z, w) {
  1803. this._x = x;
  1804. this._y = y;
  1805. this._z = z;
  1806. this._w = w;
  1807. this._onChangeCallback();
  1808. return this;
  1809. }
  1810. clone() {
  1811. return new this.constructor(this._x, this._y, this._z, this._w);
  1812. }
  1813. copy(quaternion) {
  1814. this._x = quaternion.x;
  1815. this._y = quaternion.y;
  1816. this._z = quaternion.z;
  1817. this._w = quaternion.w;
  1818. this._onChangeCallback();
  1819. return this;
  1820. }
  1821. setFromEuler(euler, update) {
  1822. if (!(euler && euler.isEuler)) {
  1823. throw new Error('THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.');
  1824. }
  1825. const x = euler._x,
  1826. y = euler._y,
  1827. z = euler._z,
  1828. order = euler._order; // http://www.mathworks.com/matlabcentral/fileexchange/
  1829. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1830. // content/SpinCalc.m
  1831. const cos = Math.cos;
  1832. const sin = Math.sin;
  1833. const c1 = cos(x / 2);
  1834. const c2 = cos(y / 2);
  1835. const c3 = cos(z / 2);
  1836. const s1 = sin(x / 2);
  1837. const s2 = sin(y / 2);
  1838. const s3 = sin(z / 2);
  1839. switch (order) {
  1840. case 'XYZ':
  1841. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1842. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1843. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1844. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1845. break;
  1846. case 'YXZ':
  1847. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1848. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1849. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1850. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1851. break;
  1852. case 'ZXY':
  1853. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1854. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1855. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1856. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1857. break;
  1858. case 'ZYX':
  1859. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1860. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1861. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1862. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1863. break;
  1864. case 'YZX':
  1865. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1866. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1867. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1868. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1869. break;
  1870. case 'XZY':
  1871. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1872. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1873. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1874. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1875. break;
  1876. default:
  1877. console.warn('THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order);
  1878. }
  1879. if (update !== false) this._onChangeCallback();
  1880. return this;
  1881. }
  1882. setFromAxisAngle(axis, angle) {
  1883. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  1884. // assumes axis is normalized
  1885. const halfAngle = angle / 2,
  1886. s = Math.sin(halfAngle);
  1887. this._x = axis.x * s;
  1888. this._y = axis.y * s;
  1889. this._z = axis.z * s;
  1890. this._w = Math.cos(halfAngle);
  1891. this._onChangeCallback();
  1892. return this;
  1893. }
  1894. setFromRotationMatrix(m) {
  1895. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  1896. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1897. const te = m.elements,
  1898. m11 = te[0],
  1899. m12 = te[4],
  1900. m13 = te[8],
  1901. m21 = te[1],
  1902. m22 = te[5],
  1903. m23 = te[9],
  1904. m31 = te[2],
  1905. m32 = te[6],
  1906. m33 = te[10],
  1907. trace = m11 + m22 + m33;
  1908. if (trace > 0) {
  1909. const s = 0.5 / Math.sqrt(trace + 1.0);
  1910. this._w = 0.25 / s;
  1911. this._x = (m32 - m23) * s;
  1912. this._y = (m13 - m31) * s;
  1913. this._z = (m21 - m12) * s;
  1914. } else if (m11 > m22 && m11 > m33) {
  1915. const s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1916. this._w = (m32 - m23) / s;
  1917. this._x = 0.25 * s;
  1918. this._y = (m12 + m21) / s;
  1919. this._z = (m13 + m31) / s;
  1920. } else if (m22 > m33) {
  1921. const s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1922. this._w = (m13 - m31) / s;
  1923. this._x = (m12 + m21) / s;
  1924. this._y = 0.25 * s;
  1925. this._z = (m23 + m32) / s;
  1926. } else {
  1927. const s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1928. this._w = (m21 - m12) / s;
  1929. this._x = (m13 + m31) / s;
  1930. this._y = (m23 + m32) / s;
  1931. this._z = 0.25 * s;
  1932. }
  1933. this._onChangeCallback();
  1934. return this;
  1935. }
  1936. setFromUnitVectors(vFrom, vTo) {
  1937. // assumes direction vectors vFrom and vTo are normalized
  1938. let r = vFrom.dot(vTo) + 1;
  1939. if (r < Number.EPSILON) {
  1940. // vFrom and vTo point in opposite directions
  1941. r = 0;
  1942. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  1943. this._x = -vFrom.y;
  1944. this._y = vFrom.x;
  1945. this._z = 0;
  1946. this._w = r;
  1947. } else {
  1948. this._x = 0;
  1949. this._y = -vFrom.z;
  1950. this._z = vFrom.y;
  1951. this._w = r;
  1952. }
  1953. } else {
  1954. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  1955. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  1956. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  1957. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  1958. this._w = r;
  1959. }
  1960. return this.normalize();
  1961. }
  1962. angleTo(q) {
  1963. return 2 * Math.acos(Math.abs(clamp(this.dot(q), -1, 1)));
  1964. }
  1965. rotateTowards(q, step) {
  1966. const angle = this.angleTo(q);
  1967. if (angle === 0) return this;
  1968. const t = Math.min(1, step / angle);
  1969. this.slerp(q, t);
  1970. return this;
  1971. }
  1972. identity() {
  1973. return this.set(0, 0, 0, 1);
  1974. }
  1975. invert() {
  1976. // quaternion is assumed to have unit length
  1977. return this.conjugate();
  1978. }
  1979. conjugate() {
  1980. this._x *= -1;
  1981. this._y *= -1;
  1982. this._z *= -1;
  1983. this._onChangeCallback();
  1984. return this;
  1985. }
  1986. dot(v) {
  1987. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  1988. }
  1989. lengthSq() {
  1990. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  1991. }
  1992. length() {
  1993. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  1994. }
  1995. normalize() {
  1996. let l = this.length();
  1997. if (l === 0) {
  1998. this._x = 0;
  1999. this._y = 0;
  2000. this._z = 0;
  2001. this._w = 1;
  2002. } else {
  2003. l = 1 / l;
  2004. this._x = this._x * l;
  2005. this._y = this._y * l;
  2006. this._z = this._z * l;
  2007. this._w = this._w * l;
  2008. }
  2009. this._onChangeCallback();
  2010. return this;
  2011. }
  2012. multiply(q, p) {
  2013. if (p !== undefined) {
  2014. console.warn('THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.');
  2015. return this.multiplyQuaternions(q, p);
  2016. }
  2017. return this.multiplyQuaternions(this, q);
  2018. }
  2019. premultiply(q) {
  2020. return this.multiplyQuaternions(q, this);
  2021. }
  2022. multiplyQuaternions(a, b) {
  2023. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2024. const qax = a._x,
  2025. qay = a._y,
  2026. qaz = a._z,
  2027. qaw = a._w;
  2028. const qbx = b._x,
  2029. qby = b._y,
  2030. qbz = b._z,
  2031. qbw = b._w;
  2032. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2033. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2034. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2035. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2036. this._onChangeCallback();
  2037. return this;
  2038. }
  2039. slerp(qb, t) {
  2040. if (t === 0) return this;
  2041. if (t === 1) return this.copy(qb);
  2042. const x = this._x,
  2043. y = this._y,
  2044. z = this._z,
  2045. w = this._w; // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2046. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2047. if (cosHalfTheta < 0) {
  2048. this._w = -qb._w;
  2049. this._x = -qb._x;
  2050. this._y = -qb._y;
  2051. this._z = -qb._z;
  2052. cosHalfTheta = -cosHalfTheta;
  2053. } else {
  2054. this.copy(qb);
  2055. }
  2056. if (cosHalfTheta >= 1.0) {
  2057. this._w = w;
  2058. this._x = x;
  2059. this._y = y;
  2060. this._z = z;
  2061. return this;
  2062. }
  2063. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2064. if (sqrSinHalfTheta <= Number.EPSILON) {
  2065. const s = 1 - t;
  2066. this._w = s * w + t * this._w;
  2067. this._x = s * x + t * this._x;
  2068. this._y = s * y + t * this._y;
  2069. this._z = s * z + t * this._z;
  2070. this.normalize();
  2071. this._onChangeCallback();
  2072. return this;
  2073. }
  2074. const sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
  2075. const halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
  2076. const ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  2077. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  2078. this._w = w * ratioA + this._w * ratioB;
  2079. this._x = x * ratioA + this._x * ratioB;
  2080. this._y = y * ratioA + this._y * ratioB;
  2081. this._z = z * ratioA + this._z * ratioB;
  2082. this._onChangeCallback();
  2083. return this;
  2084. }
  2085. slerpQuaternions(qa, qb, t) {
  2086. this.copy(qa).slerp(qb, t);
  2087. }
  2088. equals(quaternion) {
  2089. return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
  2090. }
  2091. fromArray(array, offset = 0) {
  2092. this._x = array[offset];
  2093. this._y = array[offset + 1];
  2094. this._z = array[offset + 2];
  2095. this._w = array[offset + 3];
  2096. this._onChangeCallback();
  2097. return this;
  2098. }
  2099. toArray(array = [], offset = 0) {
  2100. array[offset] = this._x;
  2101. array[offset + 1] = this._y;
  2102. array[offset + 2] = this._z;
  2103. array[offset + 3] = this._w;
  2104. return array;
  2105. }
  2106. fromBufferAttribute(attribute, index) {
  2107. this._x = attribute.getX(index);
  2108. this._y = attribute.getY(index);
  2109. this._z = attribute.getZ(index);
  2110. this._w = attribute.getW(index);
  2111. return this;
  2112. }
  2113. _onChange(callback) {
  2114. this._onChangeCallback = callback;
  2115. return this;
  2116. }
  2117. _onChangeCallback() {}
  2118. }
  2119. Quaternion.prototype.isQuaternion = true;
  2120. class Vector3 {
  2121. constructor(x = 0, y = 0, z = 0) {
  2122. this.x = x;
  2123. this.y = y;
  2124. this.z = z;
  2125. }
  2126. set(x, y, z) {
  2127. if (z === undefined) z = this.z; // sprite.scale.set(x,y)
  2128. this.x = x;
  2129. this.y = y;
  2130. this.z = z;
  2131. return this;
  2132. }
  2133. setScalar(scalar) {
  2134. this.x = scalar;
  2135. this.y = scalar;
  2136. this.z = scalar;
  2137. return this;
  2138. }
  2139. setX(x) {
  2140. this.x = x;
  2141. return this;
  2142. }
  2143. setY(y) {
  2144. this.y = y;
  2145. return this;
  2146. }
  2147. setZ(z) {
  2148. this.z = z;
  2149. return this;
  2150. }
  2151. setComponent(index, value) {
  2152. switch (index) {
  2153. case 0:
  2154. this.x = value;
  2155. break;
  2156. case 1:
  2157. this.y = value;
  2158. break;
  2159. case 2:
  2160. this.z = value;
  2161. break;
  2162. default:
  2163. throw new Error('index is out of range: ' + index);
  2164. }
  2165. return this;
  2166. }
  2167. getComponent(index) {
  2168. switch (index) {
  2169. case 0:
  2170. return this.x;
  2171. case 1:
  2172. return this.y;
  2173. case 2:
  2174. return this.z;
  2175. default:
  2176. throw new Error('index is out of range: ' + index);
  2177. }
  2178. }
  2179. clone() {
  2180. return new this.constructor(this.x, this.y, this.z);
  2181. }
  2182. copy(v) {
  2183. this.x = v.x;
  2184. this.y = v.y;
  2185. this.z = v.z;
  2186. return this;
  2187. }
  2188. add(v, w) {
  2189. if (w !== undefined) {
  2190. console.warn('THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  2191. return this.addVectors(v, w);
  2192. }
  2193. this.x += v.x;
  2194. this.y += v.y;
  2195. this.z += v.z;
  2196. return this;
  2197. }
  2198. addScalar(s) {
  2199. this.x += s;
  2200. this.y += s;
  2201. this.z += s;
  2202. return this;
  2203. }
  2204. addVectors(a, b) {
  2205. this.x = a.x + b.x;
  2206. this.y = a.y + b.y;
  2207. this.z = a.z + b.z;
  2208. return this;
  2209. }
  2210. addScaledVector(v, s) {
  2211. this.x += v.x * s;
  2212. this.y += v.y * s;
  2213. this.z += v.z * s;
  2214. return this;
  2215. }
  2216. sub(v, w) {
  2217. if (w !== undefined) {
  2218. console.warn('THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  2219. return this.subVectors(v, w);
  2220. }
  2221. this.x -= v.x;
  2222. this.y -= v.y;
  2223. this.z -= v.z;
  2224. return this;
  2225. }
  2226. subScalar(s) {
  2227. this.x -= s;
  2228. this.y -= s;
  2229. this.z -= s;
  2230. return this;
  2231. }
  2232. subVectors(a, b) {
  2233. this.x = a.x - b.x;
  2234. this.y = a.y - b.y;
  2235. this.z = a.z - b.z;
  2236. return this;
  2237. }
  2238. multiply(v, w) {
  2239. if (w !== undefined) {
  2240. console.warn('THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.');
  2241. return this.multiplyVectors(v, w);
  2242. }
  2243. this.x *= v.x;
  2244. this.y *= v.y;
  2245. this.z *= v.z;
  2246. return this;
  2247. }
  2248. multiplyScalar(scalar) {
  2249. this.x *= scalar;
  2250. this.y *= scalar;
  2251. this.z *= scalar;
  2252. return this;
  2253. }
  2254. multiplyVectors(a, b) {
  2255. this.x = a.x * b.x;
  2256. this.y = a.y * b.y;
  2257. this.z = a.z * b.z;
  2258. return this;
  2259. }
  2260. applyEuler(euler) {
  2261. if (!(euler && euler.isEuler)) {
  2262. console.error('THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.');
  2263. }
  2264. return this.applyQuaternion(_quaternion$4.setFromEuler(euler));
  2265. }
  2266. applyAxisAngle(axis, angle) {
  2267. return this.applyQuaternion(_quaternion$4.setFromAxisAngle(axis, angle));
  2268. }
  2269. applyMatrix3(m) {
  2270. const x = this.x,
  2271. y = this.y,
  2272. z = this.z;
  2273. const e = m.elements;
  2274. this.x = e[0] * x + e[3] * y + e[6] * z;
  2275. this.y = e[1] * x + e[4] * y + e[7] * z;
  2276. this.z = e[2] * x + e[5] * y + e[8] * z;
  2277. return this;
  2278. }
  2279. applyNormalMatrix(m) {
  2280. return this.applyMatrix3(m).normalize();
  2281. }
  2282. applyMatrix4(m) {
  2283. const x = this.x,
  2284. y = this.y,
  2285. z = this.z;
  2286. const e = m.elements;
  2287. const w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
  2288. this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
  2289. this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
  2290. this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
  2291. return this;
  2292. }
  2293. applyQuaternion(q) {
  2294. const x = this.x,
  2295. y = this.y,
  2296. z = this.z;
  2297. const qx = q.x,
  2298. qy = q.y,
  2299. qz = q.z,
  2300. qw = q.w; // calculate quat * vector
  2301. const ix = qw * x + qy * z - qz * y;
  2302. const iy = qw * y + qz * x - qx * z;
  2303. const iz = qw * z + qx * y - qy * x;
  2304. const iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  2305. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2306. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2307. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2308. return this;
  2309. }
  2310. project(camera) {
  2311. return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
  2312. }
  2313. unproject(camera) {
  2314. return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
  2315. }
  2316. transformDirection(m) {
  2317. // input: THREE.Matrix4 affine matrix
  2318. // vector interpreted as a direction
  2319. const x = this.x,
  2320. y = this.y,
  2321. z = this.z;
  2322. const e = m.elements;
  2323. this.x = e[0] * x + e[4] * y + e[8] * z;
  2324. this.y = e[1] * x + e[5] * y + e[9] * z;
  2325. this.z = e[2] * x + e[6] * y + e[10] * z;
  2326. return this.normalize();
  2327. }
  2328. divide(v) {
  2329. this.x /= v.x;
  2330. this.y /= v.y;
  2331. this.z /= v.z;
  2332. return this;
  2333. }
  2334. divideScalar(scalar) {
  2335. return this.multiplyScalar(1 / scalar);
  2336. }
  2337. min(v) {
  2338. this.x = Math.min(this.x, v.x);
  2339. this.y = Math.min(this.y, v.y);
  2340. this.z = Math.min(this.z, v.z);
  2341. return this;
  2342. }
  2343. max(v) {
  2344. this.x = Math.max(this.x, v.x);
  2345. this.y = Math.max(this.y, v.y);
  2346. this.z = Math.max(this.z, v.z);
  2347. return this;
  2348. }
  2349. clamp(min, max) {
  2350. // assumes min < max, componentwise
  2351. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2352. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2353. this.z = Math.max(min.z, Math.min(max.z, this.z));
  2354. return this;
  2355. }
  2356. clampScalar(minVal, maxVal) {
  2357. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2358. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2359. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  2360. return this;
  2361. }
  2362. clampLength(min, max) {
  2363. const length = this.length();
  2364. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2365. }
  2366. floor() {
  2367. this.x = Math.floor(this.x);
  2368. this.y = Math.floor(this.y);
  2369. this.z = Math.floor(this.z);
  2370. return this;
  2371. }
  2372. ceil() {
  2373. this.x = Math.ceil(this.x);
  2374. this.y = Math.ceil(this.y);
  2375. this.z = Math.ceil(this.z);
  2376. return this;
  2377. }
  2378. round() {
  2379. this.x = Math.round(this.x);
  2380. this.y = Math.round(this.y);
  2381. this.z = Math.round(this.z);
  2382. return this;
  2383. }
  2384. roundToZero() {
  2385. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2386. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2387. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  2388. return this;
  2389. }
  2390. negate() {
  2391. this.x = -this.x;
  2392. this.y = -this.y;
  2393. this.z = -this.z;
  2394. return this;
  2395. }
  2396. dot(v) {
  2397. return this.x * v.x + this.y * v.y + this.z * v.z;
  2398. } // TODO lengthSquared?
  2399. lengthSq() {
  2400. return this.x * this.x + this.y * this.y + this.z * this.z;
  2401. }
  2402. length() {
  2403. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2404. }
  2405. manhattanLength() {
  2406. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  2407. }
  2408. normalize() {
  2409. return this.divideScalar(this.length() || 1);
  2410. }
  2411. setLength(length) {
  2412. return this.normalize().multiplyScalar(length);
  2413. }
  2414. lerp(v, alpha) {
  2415. this.x += (v.x - this.x) * alpha;
  2416. this.y += (v.y - this.y) * alpha;
  2417. this.z += (v.z - this.z) * alpha;
  2418. return this;
  2419. }
  2420. lerpVectors(v1, v2, alpha) {
  2421. this.x = v1.x + (v2.x - v1.x) * alpha;
  2422. this.y = v1.y + (v2.y - v1.y) * alpha;
  2423. this.z = v1.z + (v2.z - v1.z) * alpha;
  2424. return this;
  2425. }
  2426. cross(v, w) {
  2427. if (w !== undefined) {
  2428. console.warn('THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.');
  2429. return this.crossVectors(v, w);
  2430. }
  2431. return this.crossVectors(this, v);
  2432. }
  2433. crossVectors(a, b) {
  2434. const ax = a.x,
  2435. ay = a.y,
  2436. az = a.z;
  2437. const bx = b.x,
  2438. by = b.y,
  2439. bz = b.z;
  2440. this.x = ay * bz - az * by;
  2441. this.y = az * bx - ax * bz;
  2442. this.z = ax * by - ay * bx;
  2443. return this;
  2444. }
  2445. projectOnVector(v) {
  2446. const denominator = v.lengthSq();
  2447. if (denominator === 0) return this.set(0, 0, 0);
  2448. const scalar = v.dot(this) / denominator;
  2449. return this.copy(v).multiplyScalar(scalar);
  2450. }
  2451. projectOnPlane(planeNormal) {
  2452. _vector$c.copy(this).projectOnVector(planeNormal);
  2453. return this.sub(_vector$c);
  2454. }
  2455. reflect(normal) {
  2456. // reflect incident vector off plane orthogonal to normal
  2457. // normal is assumed to have unit length
  2458. return this.sub(_vector$c.copy(normal).multiplyScalar(2 * this.dot(normal)));
  2459. }
  2460. angleTo(v) {
  2461. const denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
  2462. if (denominator === 0) return Math.PI / 2;
  2463. const theta = this.dot(v) / denominator; // clamp, to handle numerical problems
  2464. return Math.acos(clamp(theta, -1, 1));
  2465. }
  2466. distanceTo(v) {
  2467. return Math.sqrt(this.distanceToSquared(v));
  2468. }
  2469. distanceToSquared(v) {
  2470. const dx = this.x - v.x,
  2471. dy = this.y - v.y,
  2472. dz = this.z - v.z;
  2473. return dx * dx + dy * dy + dz * dz;
  2474. }
  2475. manhattanDistanceTo(v) {
  2476. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
  2477. }
  2478. setFromSpherical(s) {
  2479. return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
  2480. }
  2481. setFromSphericalCoords(radius, phi, theta) {
  2482. const sinPhiRadius = Math.sin(phi) * radius;
  2483. this.x = sinPhiRadius * Math.sin(theta);
  2484. this.y = Math.cos(phi) * radius;
  2485. this.z = sinPhiRadius * Math.cos(theta);
  2486. return this;
  2487. }
  2488. setFromCylindrical(c) {
  2489. return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
  2490. }
  2491. setFromCylindricalCoords(radius, theta, y) {
  2492. this.x = radius * Math.sin(theta);
  2493. this.y = y;
  2494. this.z = radius * Math.cos(theta);
  2495. return this;
  2496. }
  2497. setFromMatrixPosition(m) {
  2498. const e = m.elements;
  2499. this.x = e[12];
  2500. this.y = e[13];
  2501. this.z = e[14];
  2502. return this;
  2503. }
  2504. setFromMatrixScale(m) {
  2505. const sx = this.setFromMatrixColumn(m, 0).length();
  2506. const sy = this.setFromMatrixColumn(m, 1).length();
  2507. const sz = this.setFromMatrixColumn(m, 2).length();
  2508. this.x = sx;
  2509. this.y = sy;
  2510. this.z = sz;
  2511. return this;
  2512. }
  2513. setFromMatrixColumn(m, index) {
  2514. return this.fromArray(m.elements, index * 4);
  2515. }
  2516. setFromMatrix3Column(m, index) {
  2517. return this.fromArray(m.elements, index * 3);
  2518. }
  2519. equals(v) {
  2520. return v.x === this.x && v.y === this.y && v.z === this.z;
  2521. }
  2522. fromArray(array, offset = 0) {
  2523. this.x = array[offset];
  2524. this.y = array[offset + 1];
  2525. this.z = array[offset + 2];
  2526. return this;
  2527. }
  2528. toArray(array = [], offset = 0) {
  2529. array[offset] = this.x;
  2530. array[offset + 1] = this.y;
  2531. array[offset + 2] = this.z;
  2532. return array;
  2533. }
  2534. fromBufferAttribute(attribute, index, offset) {
  2535. if (offset !== undefined) {
  2536. console.warn('THREE.Vector3: offset has been removed from .fromBufferAttribute().');
  2537. }
  2538. this.x = attribute.getX(index);
  2539. this.y = attribute.getY(index);
  2540. this.z = attribute.getZ(index);
  2541. return this;
  2542. }
  2543. random() {
  2544. this.x = Math.random();
  2545. this.y = Math.random();
  2546. this.z = Math.random();
  2547. return this;
  2548. }
  2549. }
  2550. Vector3.prototype.isVector3 = true;
  2551. const _vector$c = /*@__PURE__*/new Vector3();
  2552. const _quaternion$4 = /*@__PURE__*/new Quaternion();
  2553. class Box3 {
  2554. constructor(min = new Vector3(+Infinity, +Infinity, +Infinity), max = new Vector3(-Infinity, -Infinity, -Infinity)) {
  2555. this.min = min;
  2556. this.max = max;
  2557. }
  2558. set(min, max) {
  2559. this.min.copy(min);
  2560. this.max.copy(max);
  2561. return this;
  2562. }
  2563. setFromArray(array) {
  2564. let minX = +Infinity;
  2565. let minY = +Infinity;
  2566. let minZ = +Infinity;
  2567. let maxX = -Infinity;
  2568. let maxY = -Infinity;
  2569. let maxZ = -Infinity;
  2570. for (let i = 0, l = array.length; i < l; i += 3) {
  2571. const x = array[i];
  2572. const y = array[i + 1];
  2573. const z = array[i + 2];
  2574. if (x < minX) minX = x;
  2575. if (y < minY) minY = y;
  2576. if (z < minZ) minZ = z;
  2577. if (x > maxX) maxX = x;
  2578. if (y > maxY) maxY = y;
  2579. if (z > maxZ) maxZ = z;
  2580. }
  2581. this.min.set(minX, minY, minZ);
  2582. this.max.set(maxX, maxY, maxZ);
  2583. return this;
  2584. }
  2585. setFromBufferAttribute(attribute) {
  2586. let minX = +Infinity;
  2587. let minY = +Infinity;
  2588. let minZ = +Infinity;
  2589. let maxX = -Infinity;
  2590. let maxY = -Infinity;
  2591. let maxZ = -Infinity;
  2592. for (let i = 0, l = attribute.count; i < l; i++) {
  2593. const x = attribute.getX(i);
  2594. const y = attribute.getY(i);
  2595. const z = attribute.getZ(i);
  2596. if (x < minX) minX = x;
  2597. if (y < minY) minY = y;
  2598. if (z < minZ) minZ = z;
  2599. if (x > maxX) maxX = x;
  2600. if (y > maxY) maxY = y;
  2601. if (z > maxZ) maxZ = z;
  2602. }
  2603. this.min.set(minX, minY, minZ);
  2604. this.max.set(maxX, maxY, maxZ);
  2605. return this;
  2606. }
  2607. setFromPoints(points) {
  2608. this.makeEmpty();
  2609. for (let i = 0, il = points.length; i < il; i++) {
  2610. this.expandByPoint(points[i]);
  2611. }
  2612. return this;
  2613. }
  2614. setFromCenterAndSize(center, size) {
  2615. const halfSize = _vector$b.copy(size).multiplyScalar(0.5);
  2616. this.min.copy(center).sub(halfSize);
  2617. this.max.copy(center).add(halfSize);
  2618. return this;
  2619. }
  2620. setFromObject(object) {
  2621. this.makeEmpty();
  2622. return this.expandByObject(object);
  2623. }
  2624. clone() {
  2625. return new this.constructor().copy(this);
  2626. }
  2627. copy(box) {
  2628. this.min.copy(box.min);
  2629. this.max.copy(box.max);
  2630. return this;
  2631. }
  2632. makeEmpty() {
  2633. this.min.x = this.min.y = this.min.z = +Infinity;
  2634. this.max.x = this.max.y = this.max.z = -Infinity;
  2635. return this;
  2636. }
  2637. isEmpty() {
  2638. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2639. return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  2640. }
  2641. getCenter(target) {
  2642. if (target === undefined) {
  2643. console.warn('THREE.Box3: .getCenter() target is now required');
  2644. target = new Vector3();
  2645. }
  2646. return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  2647. }
  2648. getSize(target) {
  2649. if (target === undefined) {
  2650. console.warn('THREE.Box3: .getSize() target is now required');
  2651. target = new Vector3();
  2652. }
  2653. return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
  2654. }
  2655. expandByPoint(point) {
  2656. this.min.min(point);
  2657. this.max.max(point);
  2658. return this;
  2659. }
  2660. expandByVector(vector) {
  2661. this.min.sub(vector);
  2662. this.max.add(vector);
  2663. return this;
  2664. }
  2665. expandByScalar(scalar) {
  2666. this.min.addScalar(-scalar);
  2667. this.max.addScalar(scalar);
  2668. return this;
  2669. }
  2670. expandByObject(object) {
  2671. // Computes the world-axis-aligned bounding box of an object (including its children),
  2672. // accounting for both the object's, and children's, world transforms
  2673. object.updateWorldMatrix(false, false);
  2674. const geometry = object.geometry;
  2675. if (geometry !== undefined) {
  2676. if (geometry.boundingBox === null) {
  2677. geometry.computeBoundingBox();
  2678. }
  2679. _box$3.copy(geometry.boundingBox);
  2680. _box$3.applyMatrix4(object.matrixWorld);
  2681. this.union(_box$3);
  2682. }
  2683. const children = object.children;
  2684. for (let i = 0, l = children.length; i < l; i++) {
  2685. this.expandByObject(children[i]);
  2686. }
  2687. return this;
  2688. }
  2689. containsPoint(point) {
  2690. 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;
  2691. }
  2692. containsBox(box) {
  2693. 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;
  2694. }
  2695. getParameter(point, target) {
  2696. // This can potentially have a divide by zero if the box
  2697. // has a size dimension of 0.
  2698. if (target === undefined) {
  2699. console.warn('THREE.Box3: .getParameter() target is now required');
  2700. target = new Vector3();
  2701. }
  2702. 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));
  2703. }
  2704. intersectsBox(box) {
  2705. // using 6 splitting planes to rule out intersections.
  2706. 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;
  2707. }
  2708. intersectsSphere(sphere) {
  2709. // Find the point on the AABB closest to the sphere center.
  2710. this.clampPoint(sphere.center, _vector$b); // If that point is inside the sphere, the AABB and sphere intersect.
  2711. return _vector$b.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  2712. }
  2713. intersectsPlane(plane) {
  2714. // We compute the minimum and maximum dot product values. If those values
  2715. // are on the same side (back or front) of the plane, then there is no intersection.
  2716. let min, max;
  2717. if (plane.normal.x > 0) {
  2718. min = plane.normal.x * this.min.x;
  2719. max = plane.normal.x * this.max.x;
  2720. } else {
  2721. min = plane.normal.x * this.max.x;
  2722. max = plane.normal.x * this.min.x;
  2723. }
  2724. if (plane.normal.y > 0) {
  2725. min += plane.normal.y * this.min.y;
  2726. max += plane.normal.y * this.max.y;
  2727. } else {
  2728. min += plane.normal.y * this.max.y;
  2729. max += plane.normal.y * this.min.y;
  2730. }
  2731. if (plane.normal.z > 0) {
  2732. min += plane.normal.z * this.min.z;
  2733. max += plane.normal.z * this.max.z;
  2734. } else {
  2735. min += plane.normal.z * this.max.z;
  2736. max += plane.normal.z * this.min.z;
  2737. }
  2738. return min <= -plane.constant && max >= -plane.constant;
  2739. }
  2740. intersectsTriangle(triangle) {
  2741. if (this.isEmpty()) {
  2742. return false;
  2743. } // compute box center and extents
  2744. this.getCenter(_center);
  2745. _extents.subVectors(this.max, _center); // translate triangle to aabb origin
  2746. _v0$2.subVectors(triangle.a, _center);
  2747. _v1$7.subVectors(triangle.b, _center);
  2748. _v2$3.subVectors(triangle.c, _center); // compute edge vectors for triangle
  2749. _f0.subVectors(_v1$7, _v0$2);
  2750. _f1.subVectors(_v2$3, _v1$7);
  2751. _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
  2752. // 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
  2753. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2754. 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];
  2755. if (!satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents)) {
  2756. return false;
  2757. } // test 3 face normals from the aabb
  2758. axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  2759. if (!satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents)) {
  2760. return false;
  2761. } // finally testing the face normal of the triangle
  2762. // use already existing triangle edge vectors here
  2763. _triangleNormal.crossVectors(_f0, _f1);
  2764. axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
  2765. return satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents);
  2766. }
  2767. clampPoint(point, target) {
  2768. if (target === undefined) {
  2769. console.warn('THREE.Box3: .clampPoint() target is now required');
  2770. target = new Vector3();
  2771. }
  2772. return target.copy(point).clamp(this.min, this.max);
  2773. }
  2774. distanceToPoint(point) {
  2775. const clampedPoint = _vector$b.copy(point).clamp(this.min, this.max);
  2776. return clampedPoint.sub(point).length();
  2777. }
  2778. getBoundingSphere(target) {
  2779. if (target === undefined) {
  2780. console.error('THREE.Box3: .getBoundingSphere() target is now required'); //target = new Sphere(); // removed to avoid cyclic dependency
  2781. }
  2782. this.getCenter(target.center);
  2783. target.radius = this.getSize(_vector$b).length() * 0.5;
  2784. return target;
  2785. }
  2786. intersect(box) {
  2787. this.min.max(box.min);
  2788. 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.
  2789. if (this.isEmpty()) this.makeEmpty();
  2790. return this;
  2791. }
  2792. union(box) {
  2793. this.min.min(box.min);
  2794. this.max.max(box.max);
  2795. return this;
  2796. }
  2797. applyMatrix4(matrix) {
  2798. // transform of empty box is an empty box.
  2799. if (this.isEmpty()) return this; // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2800. _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000
  2801. _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001
  2802. _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010
  2803. _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011
  2804. _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100
  2805. _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101
  2806. _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110
  2807. _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111
  2808. this.setFromPoints(_points);
  2809. return this;
  2810. }
  2811. translate(offset) {
  2812. this.min.add(offset);
  2813. this.max.add(offset);
  2814. return this;
  2815. }
  2816. equals(box) {
  2817. return box.min.equals(this.min) && box.max.equals(this.max);
  2818. }
  2819. }
  2820. Box3.prototype.isBox3 = true;
  2821. 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()];
  2822. const _vector$b = /*@__PURE__*/new Vector3();
  2823. const _box$3 = /*@__PURE__*/new Box3(); // triangle centered vertices
  2824. const _v0$2 = /*@__PURE__*/new Vector3();
  2825. const _v1$7 = /*@__PURE__*/new Vector3();
  2826. const _v2$3 = /*@__PURE__*/new Vector3(); // triangle edge vectors
  2827. const _f0 = /*@__PURE__*/new Vector3();
  2828. const _f1 = /*@__PURE__*/new Vector3();
  2829. const _f2 = /*@__PURE__*/new Vector3();
  2830. const _center = /*@__PURE__*/new Vector3();
  2831. const _extents = /*@__PURE__*/new Vector3();
  2832. const _triangleNormal = /*@__PURE__*/new Vector3();
  2833. const _testAxis = /*@__PURE__*/new Vector3();
  2834. function satForAxes(axes, v0, v1, v2, extents) {
  2835. for (let i = 0, j = axes.length - 3; i <= j; i += 3) {
  2836. _testAxis.fromArray(axes, i); // project the aabb onto the seperating axis
  2837. 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
  2838. const p0 = v0.dot(_testAxis);
  2839. const p1 = v1.dot(_testAxis);
  2840. const p2 = v2.dot(_testAxis); // actual test, basically see if either of the most extreme of the triangle points intersects r
  2841. if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
  2842. // points of the projected triangle are outside the projected half-length of the aabb
  2843. // the axis is seperating and we can exit
  2844. return false;
  2845. }
  2846. }
  2847. return true;
  2848. }
  2849. const _box$2 = /*@__PURE__*/new Box3();
  2850. const _v1$6 = /*@__PURE__*/new Vector3();
  2851. const _toFarthestPoint = /*@__PURE__*/new Vector3();
  2852. const _toPoint = /*@__PURE__*/new Vector3();
  2853. class Sphere {
  2854. constructor(center = new Vector3(), radius = -1) {
  2855. this.center = center;
  2856. this.radius = radius;
  2857. }
  2858. set(center, radius) {
  2859. this.center.copy(center);
  2860. this.radius = radius;
  2861. return this;
  2862. }
  2863. setFromPoints(points, optionalCenter) {
  2864. const center = this.center;
  2865. if (optionalCenter !== undefined) {
  2866. center.copy(optionalCenter);
  2867. } else {
  2868. _box$2.setFromPoints(points).getCenter(center);
  2869. }
  2870. let maxRadiusSq = 0;
  2871. for (let i = 0, il = points.length; i < il; i++) {
  2872. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
  2873. }
  2874. this.radius = Math.sqrt(maxRadiusSq);
  2875. return this;
  2876. }
  2877. copy(sphere) {
  2878. this.center.copy(sphere.center);
  2879. this.radius = sphere.radius;
  2880. return this;
  2881. }
  2882. isEmpty() {
  2883. return this.radius < 0;
  2884. }
  2885. makeEmpty() {
  2886. this.center.set(0, 0, 0);
  2887. this.radius = -1;
  2888. return this;
  2889. }
  2890. containsPoint(point) {
  2891. return point.distanceToSquared(this.center) <= this.radius * this.radius;
  2892. }
  2893. distanceToPoint(point) {
  2894. return point.distanceTo(this.center) - this.radius;
  2895. }
  2896. intersectsSphere(sphere) {
  2897. const radiusSum = this.radius + sphere.radius;
  2898. return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
  2899. }
  2900. intersectsBox(box) {
  2901. return box.intersectsSphere(this);
  2902. }
  2903. intersectsPlane(plane) {
  2904. return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
  2905. }
  2906. clampPoint(point, target) {
  2907. const deltaLengthSq = this.center.distanceToSquared(point);
  2908. if (target === undefined) {
  2909. console.warn('THREE.Sphere: .clampPoint() target is now required');
  2910. target = new Vector3();
  2911. }
  2912. target.copy(point);
  2913. if (deltaLengthSq > this.radius * this.radius) {
  2914. target.sub(this.center).normalize();
  2915. target.multiplyScalar(this.radius).add(this.center);
  2916. }
  2917. return target;
  2918. }
  2919. getBoundingBox(target) {
  2920. if (target === undefined) {
  2921. console.warn('THREE.Sphere: .getBoundingBox() target is now required');
  2922. target = new Box3();
  2923. }
  2924. if (this.isEmpty()) {
  2925. // Empty sphere produces empty bounding box
  2926. target.makeEmpty();
  2927. return target;
  2928. }
  2929. target.set(this.center, this.center);
  2930. target.expandByScalar(this.radius);
  2931. return target;
  2932. }
  2933. applyMatrix4(matrix) {
  2934. this.center.applyMatrix4(matrix);
  2935. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  2936. return this;
  2937. }
  2938. translate(offset) {
  2939. this.center.add(offset);
  2940. return this;
  2941. }
  2942. expandByPoint(point) {
  2943. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L649-L671
  2944. _toPoint.subVectors(point, this.center);
  2945. const lengthSq = _toPoint.lengthSq();
  2946. if (lengthSq > this.radius * this.radius) {
  2947. const length = Math.sqrt(lengthSq);
  2948. const missingRadiusHalf = (length - this.radius) * 0.5; // Nudge this sphere towards the target point. Add half the missing distance to radius,
  2949. // and the other half to position. This gives a tighter enclosure, instead of if
  2950. // the whole missing distance were just added to radius.
  2951. this.center.add(_toPoint.multiplyScalar(missingRadiusHalf / length));
  2952. this.radius += missingRadiusHalf;
  2953. }
  2954. return this;
  2955. }
  2956. union(sphere) {
  2957. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L759-L769
  2958. // To enclose another sphere into this sphere, we only need to enclose two points:
  2959. // 1) Enclose the farthest point on the other sphere into this sphere.
  2960. // 2) Enclose the opposite point of the farthest point into this sphere.
  2961. _toFarthestPoint.subVectors(sphere.center, this.center).normalize().multiplyScalar(sphere.radius);
  2962. this.expandByPoint(_v1$6.copy(sphere.center).add(_toFarthestPoint));
  2963. this.expandByPoint(_v1$6.copy(sphere.center).sub(_toFarthestPoint));
  2964. return this;
  2965. }
  2966. equals(sphere) {
  2967. return sphere.center.equals(this.center) && sphere.radius === this.radius;
  2968. }
  2969. clone() {
  2970. return new this.constructor().copy(this);
  2971. }
  2972. }
  2973. const _vector$a = /*@__PURE__*/new Vector3();
  2974. const _segCenter = /*@__PURE__*/new Vector3();
  2975. const _segDir = /*@__PURE__*/new Vector3();
  2976. const _diff = /*@__PURE__*/new Vector3();
  2977. const _edge1 = /*@__PURE__*/new Vector3();
  2978. const _edge2 = /*@__PURE__*/new Vector3();
  2979. const _normal$1 = /*@__PURE__*/new Vector3();
  2980. class Ray {
  2981. constructor(origin = new Vector3(), direction = new Vector3(0, 0, -1)) {
  2982. this.origin = origin;
  2983. this.direction = direction;
  2984. }
  2985. set(origin, direction) {
  2986. this.origin.copy(origin);
  2987. this.direction.copy(direction);
  2988. return this;
  2989. }
  2990. copy(ray) {
  2991. this.origin.copy(ray.origin);
  2992. this.direction.copy(ray.direction);
  2993. return this;
  2994. }
  2995. at(t, target) {
  2996. if (target === undefined) {
  2997. console.warn('THREE.Ray: .at() target is now required');
  2998. target = new Vector3();
  2999. }
  3000. return target.copy(this.direction).multiplyScalar(t).add(this.origin);
  3001. }
  3002. lookAt(v) {
  3003. this.direction.copy(v).sub(this.origin).normalize();
  3004. return this;
  3005. }
  3006. recast(t) {
  3007. this.origin.copy(this.at(t, _vector$a));
  3008. return this;
  3009. }
  3010. closestPointToPoint(point, target) {
  3011. if (target === undefined) {
  3012. console.warn('THREE.Ray: .closestPointToPoint() target is now required');
  3013. target = new Vector3();
  3014. }
  3015. target.subVectors(point, this.origin);
  3016. const directionDistance = target.dot(this.direction);
  3017. if (directionDistance < 0) {
  3018. return target.copy(this.origin);
  3019. }
  3020. return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  3021. }
  3022. distanceToPoint(point) {
  3023. return Math.sqrt(this.distanceSqToPoint(point));
  3024. }
  3025. distanceSqToPoint(point) {
  3026. const directionDistance = _vector$a.subVectors(point, this.origin).dot(this.direction); // point behind the ray
  3027. if (directionDistance < 0) {
  3028. return this.origin.distanceToSquared(point);
  3029. }
  3030. _vector$a.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  3031. return _vector$a.distanceToSquared(point);
  3032. }
  3033. distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) {
  3034. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3035. // It returns the min distance between the ray and the segment
  3036. // defined by v0 and v1
  3037. // It can also set two optional targets :
  3038. // - The closest point on the ray
  3039. // - The closest point on the segment
  3040. _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
  3041. _segDir.copy(v1).sub(v0).normalize();
  3042. _diff.copy(this.origin).sub(_segCenter);
  3043. const segExtent = v0.distanceTo(v1) * 0.5;
  3044. const a01 = -this.direction.dot(_segDir);
  3045. const b0 = _diff.dot(this.direction);
  3046. const b1 = -_diff.dot(_segDir);
  3047. const c = _diff.lengthSq();
  3048. const det = Math.abs(1 - a01 * a01);
  3049. let s0, s1, sqrDist, extDet;
  3050. if (det > 0) {
  3051. // The ray and segment are not parallel.
  3052. s0 = a01 * b1 - b0;
  3053. s1 = a01 * b0 - b1;
  3054. extDet = segExtent * det;
  3055. if (s0 >= 0) {
  3056. if (s1 >= -extDet) {
  3057. if (s1 <= extDet) {
  3058. // region 0
  3059. // Minimum at interior points of ray and segment.
  3060. const invDet = 1 / det;
  3061. s0 *= invDet;
  3062. s1 *= invDet;
  3063. sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
  3064. } else {
  3065. // region 1
  3066. s1 = segExtent;
  3067. s0 = Math.max(0, -(a01 * s1 + b0));
  3068. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3069. }
  3070. } else {
  3071. // region 5
  3072. s1 = -segExtent;
  3073. s0 = Math.max(0, -(a01 * s1 + b0));
  3074. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3075. }
  3076. } else {
  3077. if (s1 <= -extDet) {
  3078. // region 4
  3079. s0 = Math.max(0, -(-a01 * segExtent + b0));
  3080. s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3081. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3082. } else if (s1 <= extDet) {
  3083. // region 3
  3084. s0 = 0;
  3085. s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
  3086. sqrDist = s1 * (s1 + 2 * b1) + c;
  3087. } else {
  3088. // region 2
  3089. s0 = Math.max(0, -(a01 * segExtent + b0));
  3090. s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3091. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3092. }
  3093. }
  3094. } else {
  3095. // Ray and segment are parallel.
  3096. s1 = a01 > 0 ? -segExtent : segExtent;
  3097. s0 = Math.max(0, -(a01 * s1 + b0));
  3098. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3099. }
  3100. if (optionalPointOnRay) {
  3101. optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);
  3102. }
  3103. if (optionalPointOnSegment) {
  3104. optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
  3105. }
  3106. return sqrDist;
  3107. }
  3108. intersectSphere(sphere, target) {
  3109. _vector$a.subVectors(sphere.center, this.origin);
  3110. const tca = _vector$a.dot(this.direction);
  3111. const d2 = _vector$a.dot(_vector$a) - tca * tca;
  3112. const radius2 = sphere.radius * sphere.radius;
  3113. if (d2 > radius2) return null;
  3114. const thc = Math.sqrt(radius2 - d2); // t0 = first intersect point - entrance on front of sphere
  3115. const t0 = tca - thc; // t1 = second intersect point - exit point on back of sphere
  3116. const t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return null
  3117. if (t0 < 0 && t1 < 0) return null; // test to see if t0 is behind the ray:
  3118. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3119. // in order to always return an intersect point that is in front of the ray.
  3120. 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
  3121. return this.at(t0, target);
  3122. }
  3123. intersectsSphere(sphere) {
  3124. return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
  3125. }
  3126. distanceToPlane(plane) {
  3127. const denominator = plane.normal.dot(this.direction);
  3128. if (denominator === 0) {
  3129. // line is coplanar, return origin
  3130. if (plane.distanceToPoint(this.origin) === 0) {
  3131. return 0;
  3132. } // Null is preferable to undefined since undefined means.... it is undefined
  3133. return null;
  3134. }
  3135. const t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; // Return if the ray never intersects the plane
  3136. return t >= 0 ? t : null;
  3137. }
  3138. intersectPlane(plane, target) {
  3139. const t = this.distanceToPlane(plane);
  3140. if (t === null) {
  3141. return null;
  3142. }
  3143. return this.at(t, target);
  3144. }
  3145. intersectsPlane(plane) {
  3146. // check if the ray lies on the plane first
  3147. const distToPoint = plane.distanceToPoint(this.origin);
  3148. if (distToPoint === 0) {
  3149. return true;
  3150. }
  3151. const denominator = plane.normal.dot(this.direction);
  3152. if (denominator * distToPoint < 0) {
  3153. return true;
  3154. } // ray origin is behind the plane (and is pointing behind it)
  3155. return false;
  3156. }
  3157. intersectBox(box, target) {
  3158. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3159. const invdirx = 1 / this.direction.x,
  3160. invdiry = 1 / this.direction.y,
  3161. invdirz = 1 / this.direction.z;
  3162. const origin = this.origin;
  3163. if (invdirx >= 0) {
  3164. tmin = (box.min.x - origin.x) * invdirx;
  3165. tmax = (box.max.x - origin.x) * invdirx;
  3166. } else {
  3167. tmin = (box.max.x - origin.x) * invdirx;
  3168. tmax = (box.min.x - origin.x) * invdirx;
  3169. }
  3170. if (invdiry >= 0) {
  3171. tymin = (box.min.y - origin.y) * invdiry;
  3172. tymax = (box.max.y - origin.y) * invdiry;
  3173. } else {
  3174. tymin = (box.max.y - origin.y) * invdiry;
  3175. tymax = (box.min.y - origin.y) * invdiry;
  3176. }
  3177. if (tmin > tymax || tymin > tmax) return null; // These lines also handle the case where tmin or tmax is NaN
  3178. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3179. if (tymin > tmin || tmin !== tmin) tmin = tymin;
  3180. if (tymax < tmax || tmax !== tmax) tmax = tymax;
  3181. if (invdirz >= 0) {
  3182. tzmin = (box.min.z - origin.z) * invdirz;
  3183. tzmax = (box.max.z - origin.z) * invdirz;
  3184. } else {
  3185. tzmin = (box.max.z - origin.z) * invdirz;
  3186. tzmax = (box.min.z - origin.z) * invdirz;
  3187. }
  3188. if (tmin > tzmax || tzmin > tmax) return null;
  3189. if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
  3190. if (tzmax < tmax || tmax !== tmax) tmax = tzmax; //return point closest to the ray (positive side)
  3191. if (tmax < 0) return null;
  3192. return this.at(tmin >= 0 ? tmin : tmax, target);
  3193. }
  3194. intersectsBox(box) {
  3195. return this.intersectBox(box, _vector$a) !== null;
  3196. }
  3197. intersectTriangle(a, b, c, backfaceCulling, target) {
  3198. // Compute the offset origin, edges, and normal.
  3199. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3200. _edge1.subVectors(b, a);
  3201. _edge2.subVectors(c, a);
  3202. _normal$1.crossVectors(_edge1, _edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3203. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3204. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3205. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3206. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3207. let DdN = this.direction.dot(_normal$1);
  3208. let sign;
  3209. if (DdN > 0) {
  3210. if (backfaceCulling) return null;
  3211. sign = 1;
  3212. } else if (DdN < 0) {
  3213. sign = -1;
  3214. DdN = -DdN;
  3215. } else {
  3216. return null;
  3217. }
  3218. _diff.subVectors(this.origin, a);
  3219. const DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); // b1 < 0, no intersection
  3220. if (DdQxE2 < 0) {
  3221. return null;
  3222. }
  3223. const DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); // b2 < 0, no intersection
  3224. if (DdE1xQ < 0) {
  3225. return null;
  3226. } // b1+b2 > 1, no intersection
  3227. if (DdQxE2 + DdE1xQ > DdN) {
  3228. return null;
  3229. } // Line intersects triangle, check if ray does.
  3230. const QdN = -sign * _diff.dot(_normal$1); // t < 0, no intersection
  3231. if (QdN < 0) {
  3232. return null;
  3233. } // Ray intersects triangle.
  3234. return this.at(QdN / DdN, target);
  3235. }
  3236. applyMatrix4(matrix4) {
  3237. this.origin.applyMatrix4(matrix4);
  3238. this.direction.transformDirection(matrix4);
  3239. return this;
  3240. }
  3241. equals(ray) {
  3242. return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
  3243. }
  3244. clone() {
  3245. return new this.constructor().copy(this);
  3246. }
  3247. }
  3248. class Matrix4 {
  3249. constructor() {
  3250. this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  3251. if (arguments.length > 0) {
  3252. console.error('THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.');
  3253. }
  3254. }
  3255. set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  3256. const te = this.elements;
  3257. te[0] = n11;
  3258. te[4] = n12;
  3259. te[8] = n13;
  3260. te[12] = n14;
  3261. te[1] = n21;
  3262. te[5] = n22;
  3263. te[9] = n23;
  3264. te[13] = n24;
  3265. te[2] = n31;
  3266. te[6] = n32;
  3267. te[10] = n33;
  3268. te[14] = n34;
  3269. te[3] = n41;
  3270. te[7] = n42;
  3271. te[11] = n43;
  3272. te[15] = n44;
  3273. return this;
  3274. }
  3275. identity() {
  3276. this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3277. return this;
  3278. }
  3279. clone() {
  3280. return new Matrix4().fromArray(this.elements);
  3281. }
  3282. copy(m) {
  3283. const te = this.elements;
  3284. const me = m.elements;
  3285. te[0] = me[0];
  3286. te[1] = me[1];
  3287. te[2] = me[2];
  3288. te[3] = me[3];
  3289. te[4] = me[4];
  3290. te[5] = me[5];
  3291. te[6] = me[6];
  3292. te[7] = me[7];
  3293. te[8] = me[8];
  3294. te[9] = me[9];
  3295. te[10] = me[10];
  3296. te[11] = me[11];
  3297. te[12] = me[12];
  3298. te[13] = me[13];
  3299. te[14] = me[14];
  3300. te[15] = me[15];
  3301. return this;
  3302. }
  3303. copyPosition(m) {
  3304. const te = this.elements,
  3305. me = m.elements;
  3306. te[12] = me[12];
  3307. te[13] = me[13];
  3308. te[14] = me[14];
  3309. return this;
  3310. }
  3311. setFromMatrix3(m) {
  3312. const me = m.elements;
  3313. 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);
  3314. return this;
  3315. }
  3316. extractBasis(xAxis, yAxis, zAxis) {
  3317. xAxis.setFromMatrixColumn(this, 0);
  3318. yAxis.setFromMatrixColumn(this, 1);
  3319. zAxis.setFromMatrixColumn(this, 2);
  3320. return this;
  3321. }
  3322. makeBasis(xAxis, yAxis, zAxis) {
  3323. 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);
  3324. return this;
  3325. }
  3326. extractRotation(m) {
  3327. // this method does not support reflection matrices
  3328. const te = this.elements;
  3329. const me = m.elements;
  3330. const scaleX = 1 / _v1$5.setFromMatrixColumn(m, 0).length();
  3331. const scaleY = 1 / _v1$5.setFromMatrixColumn(m, 1).length();
  3332. const scaleZ = 1 / _v1$5.setFromMatrixColumn(m, 2).length();
  3333. te[0] = me[0] * scaleX;
  3334. te[1] = me[1] * scaleX;
  3335. te[2] = me[2] * scaleX;
  3336. te[3] = 0;
  3337. te[4] = me[4] * scaleY;
  3338. te[5] = me[5] * scaleY;
  3339. te[6] = me[6] * scaleY;
  3340. te[7] = 0;
  3341. te[8] = me[8] * scaleZ;
  3342. te[9] = me[9] * scaleZ;
  3343. te[10] = me[10] * scaleZ;
  3344. te[11] = 0;
  3345. te[12] = 0;
  3346. te[13] = 0;
  3347. te[14] = 0;
  3348. te[15] = 1;
  3349. return this;
  3350. }
  3351. makeRotationFromEuler(euler) {
  3352. if (!(euler && euler.isEuler)) {
  3353. console.error('THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.');
  3354. }
  3355. const te = this.elements;
  3356. const x = euler.x,
  3357. y = euler.y,
  3358. z = euler.z;
  3359. const a = Math.cos(x),
  3360. b = Math.sin(x);
  3361. const c = Math.cos(y),
  3362. d = Math.sin(y);
  3363. const e = Math.cos(z),
  3364. f = Math.sin(z);
  3365. if (euler.order === 'XYZ') {
  3366. const ae = a * e,
  3367. af = a * f,
  3368. be = b * e,
  3369. bf = b * f;
  3370. te[0] = c * e;
  3371. te[4] = -c * f;
  3372. te[8] = d;
  3373. te[1] = af + be * d;
  3374. te[5] = ae - bf * d;
  3375. te[9] = -b * c;
  3376. te[2] = bf - ae * d;
  3377. te[6] = be + af * d;
  3378. te[10] = a * c;
  3379. } else if (euler.order === 'YXZ') {
  3380. const ce = c * e,
  3381. cf = c * f,
  3382. de = d * e,
  3383. df = d * f;
  3384. te[0] = ce + df * b;
  3385. te[4] = de * b - cf;
  3386. te[8] = a * d;
  3387. te[1] = a * f;
  3388. te[5] = a * e;
  3389. te[9] = -b;
  3390. te[2] = cf * b - de;
  3391. te[6] = df + ce * b;
  3392. te[10] = a * c;
  3393. } else if (euler.order === 'ZXY') {
  3394. const ce = c * e,
  3395. cf = c * f,
  3396. de = d * e,
  3397. df = d * f;
  3398. te[0] = ce - df * b;
  3399. te[4] = -a * f;
  3400. te[8] = de + cf * b;
  3401. te[1] = cf + de * b;
  3402. te[5] = a * e;
  3403. te[9] = df - ce * b;
  3404. te[2] = -a * d;
  3405. te[6] = b;
  3406. te[10] = a * c;
  3407. } else if (euler.order === 'ZYX') {
  3408. const ae = a * e,
  3409. af = a * f,
  3410. be = b * e,
  3411. bf = b * f;
  3412. te[0] = c * e;
  3413. te[4] = be * d - af;
  3414. te[8] = ae * d + bf;
  3415. te[1] = c * f;
  3416. te[5] = bf * d + ae;
  3417. te[9] = af * d - be;
  3418. te[2] = -d;
  3419. te[6] = b * c;
  3420. te[10] = a * c;
  3421. } else if (euler.order === 'YZX') {
  3422. const ac = a * c,
  3423. ad = a * d,
  3424. bc = b * c,
  3425. bd = b * d;
  3426. te[0] = c * e;
  3427. te[4] = bd - ac * f;
  3428. te[8] = bc * f + ad;
  3429. te[1] = f;
  3430. te[5] = a * e;
  3431. te[9] = -b * e;
  3432. te[2] = -d * e;
  3433. te[6] = ad * f + bc;
  3434. te[10] = ac - bd * f;
  3435. } else if (euler.order === 'XZY') {
  3436. const ac = a * c,
  3437. ad = a * d,
  3438. bc = b * c,
  3439. bd = b * d;
  3440. te[0] = c * e;
  3441. te[4] = -f;
  3442. te[8] = d * e;
  3443. te[1] = ac * f + bd;
  3444. te[5] = a * e;
  3445. te[9] = ad * f - bc;
  3446. te[2] = bc * f - ad;
  3447. te[6] = b * e;
  3448. te[10] = bd * f + ac;
  3449. } // bottom row
  3450. te[3] = 0;
  3451. te[7] = 0;
  3452. te[11] = 0; // last column
  3453. te[12] = 0;
  3454. te[13] = 0;
  3455. te[14] = 0;
  3456. te[15] = 1;
  3457. return this;
  3458. }
  3459. makeRotationFromQuaternion(q) {
  3460. return this.compose(_zero, q, _one);
  3461. }
  3462. lookAt(eye, target, up) {
  3463. const te = this.elements;
  3464. _z.subVectors(eye, target);
  3465. if (_z.lengthSq() === 0) {
  3466. // eye and target are in the same position
  3467. _z.z = 1;
  3468. }
  3469. _z.normalize();
  3470. _x.crossVectors(up, _z);
  3471. if (_x.lengthSq() === 0) {
  3472. // up and z are parallel
  3473. if (Math.abs(up.z) === 1) {
  3474. _z.x += 0.0001;
  3475. } else {
  3476. _z.z += 0.0001;
  3477. }
  3478. _z.normalize();
  3479. _x.crossVectors(up, _z);
  3480. }
  3481. _x.normalize();
  3482. _y.crossVectors(_z, _x);
  3483. te[0] = _x.x;
  3484. te[4] = _y.x;
  3485. te[8] = _z.x;
  3486. te[1] = _x.y;
  3487. te[5] = _y.y;
  3488. te[9] = _z.y;
  3489. te[2] = _x.z;
  3490. te[6] = _y.z;
  3491. te[10] = _z.z;
  3492. return this;
  3493. }
  3494. multiply(m, n) {
  3495. if (n !== undefined) {
  3496. console.warn('THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.');
  3497. return this.multiplyMatrices(m, n);
  3498. }
  3499. return this.multiplyMatrices(this, m);
  3500. }
  3501. premultiply(m) {
  3502. return this.multiplyMatrices(m, this);
  3503. }
  3504. multiplyMatrices(a, b) {
  3505. const ae = a.elements;
  3506. const be = b.elements;
  3507. const te = this.elements;
  3508. const a11 = ae[0],
  3509. a12 = ae[4],
  3510. a13 = ae[8],
  3511. a14 = ae[12];
  3512. const a21 = ae[1],
  3513. a22 = ae[5],
  3514. a23 = ae[9],
  3515. a24 = ae[13];
  3516. const a31 = ae[2],
  3517. a32 = ae[6],
  3518. a33 = ae[10],
  3519. a34 = ae[14];
  3520. const a41 = ae[3],
  3521. a42 = ae[7],
  3522. a43 = ae[11],
  3523. a44 = ae[15];
  3524. const b11 = be[0],
  3525. b12 = be[4],
  3526. b13 = be[8],
  3527. b14 = be[12];
  3528. const b21 = be[1],
  3529. b22 = be[5],
  3530. b23 = be[9],
  3531. b24 = be[13];
  3532. const b31 = be[2],
  3533. b32 = be[6],
  3534. b33 = be[10],
  3535. b34 = be[14];
  3536. const b41 = be[3],
  3537. b42 = be[7],
  3538. b43 = be[11],
  3539. b44 = be[15];
  3540. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3541. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3542. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3543. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3544. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3545. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3546. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3547. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3548. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3549. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3550. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3551. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3552. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3553. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3554. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3555. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3556. return this;
  3557. }
  3558. multiplyScalar(s) {
  3559. const te = this.elements;
  3560. te[0] *= s;
  3561. te[4] *= s;
  3562. te[8] *= s;
  3563. te[12] *= s;
  3564. te[1] *= s;
  3565. te[5] *= s;
  3566. te[9] *= s;
  3567. te[13] *= s;
  3568. te[2] *= s;
  3569. te[6] *= s;
  3570. te[10] *= s;
  3571. te[14] *= s;
  3572. te[3] *= s;
  3573. te[7] *= s;
  3574. te[11] *= s;
  3575. te[15] *= s;
  3576. return this;
  3577. }
  3578. determinant() {
  3579. const te = this.elements;
  3580. const n11 = te[0],
  3581. n12 = te[4],
  3582. n13 = te[8],
  3583. n14 = te[12];
  3584. const n21 = te[1],
  3585. n22 = te[5],
  3586. n23 = te[9],
  3587. n24 = te[13];
  3588. const n31 = te[2],
  3589. n32 = te[6],
  3590. n33 = te[10],
  3591. n34 = te[14];
  3592. const n41 = te[3],
  3593. n42 = te[7],
  3594. n43 = te[11],
  3595. n44 = te[15]; //TODO: make this more efficient
  3596. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3597. 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);
  3598. }
  3599. transpose() {
  3600. const te = this.elements;
  3601. let tmp;
  3602. tmp = te[1];
  3603. te[1] = te[4];
  3604. te[4] = tmp;
  3605. tmp = te[2];
  3606. te[2] = te[8];
  3607. te[8] = tmp;
  3608. tmp = te[6];
  3609. te[6] = te[9];
  3610. te[9] = tmp;
  3611. tmp = te[3];
  3612. te[3] = te[12];
  3613. te[12] = tmp;
  3614. tmp = te[7];
  3615. te[7] = te[13];
  3616. te[13] = tmp;
  3617. tmp = te[11];
  3618. te[11] = te[14];
  3619. te[14] = tmp;
  3620. return this;
  3621. }
  3622. setPosition(x, y, z) {
  3623. const te = this.elements;
  3624. if (x.isVector3) {
  3625. te[12] = x.x;
  3626. te[13] = x.y;
  3627. te[14] = x.z;
  3628. } else {
  3629. te[12] = x;
  3630. te[13] = y;
  3631. te[14] = z;
  3632. }
  3633. return this;
  3634. }
  3635. invert() {
  3636. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3637. const te = this.elements,
  3638. n11 = te[0],
  3639. n21 = te[1],
  3640. n31 = te[2],
  3641. n41 = te[3],
  3642. n12 = te[4],
  3643. n22 = te[5],
  3644. n32 = te[6],
  3645. n42 = te[7],
  3646. n13 = te[8],
  3647. n23 = te[9],
  3648. n33 = te[10],
  3649. n43 = te[11],
  3650. n14 = te[12],
  3651. n24 = te[13],
  3652. n34 = te[14],
  3653. n44 = te[15],
  3654. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3655. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3656. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3657. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3658. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3659. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  3660. const detInv = 1 / det;
  3661. te[0] = t11 * detInv;
  3662. te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
  3663. te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
  3664. te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
  3665. te[4] = t12 * detInv;
  3666. te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
  3667. te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
  3668. te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
  3669. te[8] = t13 * detInv;
  3670. te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
  3671. te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
  3672. te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
  3673. te[12] = t14 * detInv;
  3674. te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
  3675. te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
  3676. te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
  3677. return this;
  3678. }
  3679. scale(v) {
  3680. const te = this.elements;
  3681. const x = v.x,
  3682. y = v.y,
  3683. z = v.z;
  3684. te[0] *= x;
  3685. te[4] *= y;
  3686. te[8] *= z;
  3687. te[1] *= x;
  3688. te[5] *= y;
  3689. te[9] *= z;
  3690. te[2] *= x;
  3691. te[6] *= y;
  3692. te[10] *= z;
  3693. te[3] *= x;
  3694. te[7] *= y;
  3695. te[11] *= z;
  3696. return this;
  3697. }
  3698. getMaxScaleOnAxis() {
  3699. const te = this.elements;
  3700. const scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  3701. const scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  3702. const scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  3703. return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
  3704. }
  3705. makeTranslation(x, y, z) {
  3706. this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
  3707. return this;
  3708. }
  3709. makeRotationX(theta) {
  3710. const c = Math.cos(theta),
  3711. s = Math.sin(theta);
  3712. this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
  3713. return this;
  3714. }
  3715. makeRotationY(theta) {
  3716. const c = Math.cos(theta),
  3717. s = Math.sin(theta);
  3718. this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
  3719. return this;
  3720. }
  3721. makeRotationZ(theta) {
  3722. const c = Math.cos(theta),
  3723. s = Math.sin(theta);
  3724. this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3725. return this;
  3726. }
  3727. makeRotationAxis(axis, angle) {
  3728. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3729. const c = Math.cos(angle);
  3730. const s = Math.sin(angle);
  3731. const t = 1 - c;
  3732. const x = axis.x,
  3733. y = axis.y,
  3734. z = axis.z;
  3735. const tx = t * x,
  3736. ty = t * y;
  3737. 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);
  3738. return this;
  3739. }
  3740. makeScale(x, y, z) {
  3741. this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
  3742. return this;
  3743. }
  3744. makeShear(x, y, z) {
  3745. this.set(1, y, z, 0, x, 1, z, 0, x, y, 1, 0, 0, 0, 0, 1);
  3746. return this;
  3747. }
  3748. compose(position, quaternion, scale) {
  3749. const te = this.elements;
  3750. const x = quaternion._x,
  3751. y = quaternion._y,
  3752. z = quaternion._z,
  3753. w = quaternion._w;
  3754. const x2 = x + x,
  3755. y2 = y + y,
  3756. z2 = z + z;
  3757. const xx = x * x2,
  3758. xy = x * y2,
  3759. xz = x * z2;
  3760. const yy = y * y2,
  3761. yz = y * z2,
  3762. zz = z * z2;
  3763. const wx = w * x2,
  3764. wy = w * y2,
  3765. wz = w * z2;
  3766. const sx = scale.x,
  3767. sy = scale.y,
  3768. sz = scale.z;
  3769. te[0] = (1 - (yy + zz)) * sx;
  3770. te[1] = (xy + wz) * sx;
  3771. te[2] = (xz - wy) * sx;
  3772. te[3] = 0;
  3773. te[4] = (xy - wz) * sy;
  3774. te[5] = (1 - (xx + zz)) * sy;
  3775. te[6] = (yz + wx) * sy;
  3776. te[7] = 0;
  3777. te[8] = (xz + wy) * sz;
  3778. te[9] = (yz - wx) * sz;
  3779. te[10] = (1 - (xx + yy)) * sz;
  3780. te[11] = 0;
  3781. te[12] = position.x;
  3782. te[13] = position.y;
  3783. te[14] = position.z;
  3784. te[15] = 1;
  3785. return this;
  3786. }
  3787. decompose(position, quaternion, scale) {
  3788. const te = this.elements;
  3789. let sx = _v1$5.set(te[0], te[1], te[2]).length();
  3790. const sy = _v1$5.set(te[4], te[5], te[6]).length();
  3791. const sz = _v1$5.set(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale
  3792. const det = this.determinant();
  3793. if (det < 0) sx = -sx;
  3794. position.x = te[12];
  3795. position.y = te[13];
  3796. position.z = te[14]; // scale the rotation part
  3797. _m1$2.copy(this);
  3798. const invSX = 1 / sx;
  3799. const invSY = 1 / sy;
  3800. const invSZ = 1 / sz;
  3801. _m1$2.elements[0] *= invSX;
  3802. _m1$2.elements[1] *= invSX;
  3803. _m1$2.elements[2] *= invSX;
  3804. _m1$2.elements[4] *= invSY;
  3805. _m1$2.elements[5] *= invSY;
  3806. _m1$2.elements[6] *= invSY;
  3807. _m1$2.elements[8] *= invSZ;
  3808. _m1$2.elements[9] *= invSZ;
  3809. _m1$2.elements[10] *= invSZ;
  3810. quaternion.setFromRotationMatrix(_m1$2);
  3811. scale.x = sx;
  3812. scale.y = sy;
  3813. scale.z = sz;
  3814. return this;
  3815. }
  3816. makePerspective(left, right, top, bottom, near, far) {
  3817. if (far === undefined) {
  3818. console.warn('THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.');
  3819. }
  3820. const te = this.elements;
  3821. const x = 2 * near / (right - left);
  3822. const y = 2 * near / (top - bottom);
  3823. const a = (right + left) / (right - left);
  3824. const b = (top + bottom) / (top - bottom);
  3825. const c = -(far + near) / (far - near);
  3826. const d = -2 * far * near / (far - near);
  3827. te[0] = x;
  3828. te[4] = 0;
  3829. te[8] = a;
  3830. te[12] = 0;
  3831. te[1] = 0;
  3832. te[5] = y;
  3833. te[9] = b;
  3834. te[13] = 0;
  3835. te[2] = 0;
  3836. te[6] = 0;
  3837. te[10] = c;
  3838. te[14] = d;
  3839. te[3] = 0;
  3840. te[7] = 0;
  3841. te[11] = -1;
  3842. te[15] = 0;
  3843. return this;
  3844. }
  3845. makeOrthographic(left, right, top, bottom, near, far) {
  3846. const te = this.elements;
  3847. const w = 1.0 / (right - left);
  3848. const h = 1.0 / (top - bottom);
  3849. const p = 1.0 / (far - near);
  3850. const x = (right + left) * w;
  3851. const y = (top + bottom) * h;
  3852. const z = (far + near) * p;
  3853. te[0] = 2 * w;
  3854. te[4] = 0;
  3855. te[8] = 0;
  3856. te[12] = -x;
  3857. te[1] = 0;
  3858. te[5] = 2 * h;
  3859. te[9] = 0;
  3860. te[13] = -y;
  3861. te[2] = 0;
  3862. te[6] = 0;
  3863. te[10] = -2 * p;
  3864. te[14] = -z;
  3865. te[3] = 0;
  3866. te[7] = 0;
  3867. te[11] = 0;
  3868. te[15] = 1;
  3869. return this;
  3870. }
  3871. equals(matrix) {
  3872. const te = this.elements;
  3873. const me = matrix.elements;
  3874. for (let i = 0; i < 16; i++) {
  3875. if (te[i] !== me[i]) return false;
  3876. }
  3877. return true;
  3878. }
  3879. fromArray(array, offset = 0) {
  3880. for (let i = 0; i < 16; i++) {
  3881. this.elements[i] = array[i + offset];
  3882. }
  3883. return this;
  3884. }
  3885. toArray(array = [], offset = 0) {
  3886. const te = this.elements;
  3887. array[offset] = te[0];
  3888. array[offset + 1] = te[1];
  3889. array[offset + 2] = te[2];
  3890. array[offset + 3] = te[3];
  3891. array[offset + 4] = te[4];
  3892. array[offset + 5] = te[5];
  3893. array[offset + 6] = te[6];
  3894. array[offset + 7] = te[7];
  3895. array[offset + 8] = te[8];
  3896. array[offset + 9] = te[9];
  3897. array[offset + 10] = te[10];
  3898. array[offset + 11] = te[11];
  3899. array[offset + 12] = te[12];
  3900. array[offset + 13] = te[13];
  3901. array[offset + 14] = te[14];
  3902. array[offset + 15] = te[15];
  3903. return array;
  3904. }
  3905. }
  3906. Matrix4.prototype.isMatrix4 = true;
  3907. const _v1$5 = /*@__PURE__*/new Vector3();
  3908. const _m1$2 = /*@__PURE__*/new Matrix4();
  3909. const _zero = /*@__PURE__*/new Vector3(0, 0, 0);
  3910. const _one = /*@__PURE__*/new Vector3(1, 1, 1);
  3911. const _x = /*@__PURE__*/new Vector3();
  3912. const _y = /*@__PURE__*/new Vector3();
  3913. const _z = /*@__PURE__*/new Vector3();
  3914. const _matrix$1 = /*@__PURE__*/new Matrix4();
  3915. const _quaternion$3 = /*@__PURE__*/new Quaternion();
  3916. class Euler {
  3917. constructor(x = 0, y = 0, z = 0, order = Euler.DefaultOrder) {
  3918. this._x = x;
  3919. this._y = y;
  3920. this._z = z;
  3921. this._order = order;
  3922. }
  3923. get x() {
  3924. return this._x;
  3925. }
  3926. set x(value) {
  3927. this._x = value;
  3928. this._onChangeCallback();
  3929. }
  3930. get y() {
  3931. return this._y;
  3932. }
  3933. set y(value) {
  3934. this._y = value;
  3935. this._onChangeCallback();
  3936. }
  3937. get z() {
  3938. return this._z;
  3939. }
  3940. set z(value) {
  3941. this._z = value;
  3942. this._onChangeCallback();
  3943. }
  3944. get order() {
  3945. return this._order;
  3946. }
  3947. set order(value) {
  3948. this._order = value;
  3949. this._onChangeCallback();
  3950. }
  3951. set(x, y, z, order) {
  3952. this._x = x;
  3953. this._y = y;
  3954. this._z = z;
  3955. this._order = order || this._order;
  3956. this._onChangeCallback();
  3957. return this;
  3958. }
  3959. clone() {
  3960. return new this.constructor(this._x, this._y, this._z, this._order);
  3961. }
  3962. copy(euler) {
  3963. this._x = euler._x;
  3964. this._y = euler._y;
  3965. this._z = euler._z;
  3966. this._order = euler._order;
  3967. this._onChangeCallback();
  3968. return this;
  3969. }
  3970. setFromRotationMatrix(m, order, update) {
  3971. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3972. const te = m.elements;
  3973. const m11 = te[0],
  3974. m12 = te[4],
  3975. m13 = te[8];
  3976. const m21 = te[1],
  3977. m22 = te[5],
  3978. m23 = te[9];
  3979. const m31 = te[2],
  3980. m32 = te[6],
  3981. m33 = te[10];
  3982. order = order || this._order;
  3983. switch (order) {
  3984. case 'XYZ':
  3985. this._y = Math.asin(clamp(m13, -1, 1));
  3986. if (Math.abs(m13) < 0.9999999) {
  3987. this._x = Math.atan2(-m23, m33);
  3988. this._z = Math.atan2(-m12, m11);
  3989. } else {
  3990. this._x = Math.atan2(m32, m22);
  3991. this._z = 0;
  3992. }
  3993. break;
  3994. case 'YXZ':
  3995. this._x = Math.asin(-clamp(m23, -1, 1));
  3996. if (Math.abs(m23) < 0.9999999) {
  3997. this._y = Math.atan2(m13, m33);
  3998. this._z = Math.atan2(m21, m22);
  3999. } else {
  4000. this._y = Math.atan2(-m31, m11);
  4001. this._z = 0;
  4002. }
  4003. break;
  4004. case 'ZXY':
  4005. this._x = Math.asin(clamp(m32, -1, 1));
  4006. if (Math.abs(m32) < 0.9999999) {
  4007. this._y = Math.atan2(-m31, m33);
  4008. this._z = Math.atan2(-m12, m22);
  4009. } else {
  4010. this._y = 0;
  4011. this._z = Math.atan2(m21, m11);
  4012. }
  4013. break;
  4014. case 'ZYX':
  4015. this._y = Math.asin(-clamp(m31, -1, 1));
  4016. if (Math.abs(m31) < 0.9999999) {
  4017. this._x = Math.atan2(m32, m33);
  4018. this._z = Math.atan2(m21, m11);
  4019. } else {
  4020. this._x = 0;
  4021. this._z = Math.atan2(-m12, m22);
  4022. }
  4023. break;
  4024. case 'YZX':
  4025. this._z = Math.asin(clamp(m21, -1, 1));
  4026. if (Math.abs(m21) < 0.9999999) {
  4027. this._x = Math.atan2(-m23, m22);
  4028. this._y = Math.atan2(-m31, m11);
  4029. } else {
  4030. this._x = 0;
  4031. this._y = Math.atan2(m13, m33);
  4032. }
  4033. break;
  4034. case 'XZY':
  4035. this._z = Math.asin(-clamp(m12, -1, 1));
  4036. if (Math.abs(m12) < 0.9999999) {
  4037. this._x = Math.atan2(m32, m22);
  4038. this._y = Math.atan2(m13, m11);
  4039. } else {
  4040. this._x = Math.atan2(-m23, m33);
  4041. this._y = 0;
  4042. }
  4043. break;
  4044. default:
  4045. console.warn('THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order);
  4046. }
  4047. this._order = order;
  4048. if (update !== false) this._onChangeCallback();
  4049. return this;
  4050. }
  4051. setFromQuaternion(q, order, update) {
  4052. _matrix$1.makeRotationFromQuaternion(q);
  4053. return this.setFromRotationMatrix(_matrix$1, order, update);
  4054. }
  4055. setFromVector3(v, order) {
  4056. return this.set(v.x, v.y, v.z, order || this._order);
  4057. }
  4058. reorder(newOrder) {
  4059. // WARNING: this discards revolution information -bhouston
  4060. _quaternion$3.setFromEuler(this);
  4061. return this.setFromQuaternion(_quaternion$3, newOrder);
  4062. }
  4063. equals(euler) {
  4064. return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
  4065. }
  4066. fromArray(array) {
  4067. this._x = array[0];
  4068. this._y = array[1];
  4069. this._z = array[2];
  4070. if (array[3] !== undefined) this._order = array[3];
  4071. this._onChangeCallback();
  4072. return this;
  4073. }
  4074. toArray(array = [], offset = 0) {
  4075. array[offset] = this._x;
  4076. array[offset + 1] = this._y;
  4077. array[offset + 2] = this._z;
  4078. array[offset + 3] = this._order;
  4079. return array;
  4080. }
  4081. toVector3(optionalResult) {
  4082. if (optionalResult) {
  4083. return optionalResult.set(this._x, this._y, this._z);
  4084. } else {
  4085. return new Vector3(this._x, this._y, this._z);
  4086. }
  4087. }
  4088. _onChange(callback) {
  4089. this._onChangeCallback = callback;
  4090. return this;
  4091. }
  4092. _onChangeCallback() {}
  4093. }
  4094. Euler.prototype.isEuler = true;
  4095. Euler.DefaultOrder = 'XYZ';
  4096. Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  4097. class Layers {
  4098. constructor() {
  4099. this.mask = 1 | 0;
  4100. }
  4101. set(channel) {
  4102. this.mask = 1 << channel | 0;
  4103. }
  4104. enable(channel) {
  4105. this.mask |= 1 << channel | 0;
  4106. }
  4107. enableAll() {
  4108. this.mask = 0xffffffff | 0;
  4109. }
  4110. toggle(channel) {
  4111. this.mask ^= 1 << channel | 0;
  4112. }
  4113. disable(channel) {
  4114. this.mask &= ~(1 << channel | 0);
  4115. }
  4116. disableAll() {
  4117. this.mask = 0;
  4118. }
  4119. test(layers) {
  4120. return (this.mask & layers.mask) !== 0;
  4121. }
  4122. }
  4123. let _object3DId = 0;
  4124. const _v1$4 = /*@__PURE__*/new Vector3();
  4125. const _q1 = /*@__PURE__*/new Quaternion();
  4126. const _m1$1 = /*@__PURE__*/new Matrix4();
  4127. const _target = /*@__PURE__*/new Vector3();
  4128. const _position$3 = /*@__PURE__*/new Vector3();
  4129. const _scale$2 = /*@__PURE__*/new Vector3();
  4130. const _quaternion$2 = /*@__PURE__*/new Quaternion();
  4131. const _xAxis = /*@__PURE__*/new Vector3(1, 0, 0);
  4132. const _yAxis = /*@__PURE__*/new Vector3(0, 1, 0);
  4133. const _zAxis = /*@__PURE__*/new Vector3(0, 0, 1);
  4134. const _addedEvent = {
  4135. type: 'added'
  4136. };
  4137. const _removedEvent = {
  4138. type: 'removed'
  4139. };
  4140. class Object3D extends EventDispatcher {
  4141. constructor() {
  4142. super();
  4143. Object.defineProperty(this, 'id', {
  4144. value: _object3DId++
  4145. });
  4146. this.uuid = generateUUID();
  4147. this.name = '';
  4148. this.type = 'Object3D';
  4149. this.parent = null;
  4150. this.children = [];
  4151. this.up = Object3D.DefaultUp.clone();
  4152. const position = new Vector3();
  4153. const rotation = new Euler();
  4154. const quaternion = new Quaternion();
  4155. const scale = new Vector3(1, 1, 1);
  4156. function onRotationChange() {
  4157. quaternion.setFromEuler(rotation, false);
  4158. }
  4159. function onQuaternionChange() {
  4160. rotation.setFromQuaternion(quaternion, undefined, false);
  4161. }
  4162. rotation._onChange(onRotationChange);
  4163. quaternion._onChange(onQuaternionChange);
  4164. Object.defineProperties(this, {
  4165. position: {
  4166. configurable: true,
  4167. enumerable: true,
  4168. value: position
  4169. },
  4170. rotation: {
  4171. configurable: true,
  4172. enumerable: true,
  4173. value: rotation
  4174. },
  4175. quaternion: {
  4176. configurable: true,
  4177. enumerable: true,
  4178. value: quaternion
  4179. },
  4180. scale: {
  4181. configurable: true,
  4182. enumerable: true,
  4183. value: scale
  4184. },
  4185. modelViewMatrix: {
  4186. value: new Matrix4()
  4187. },
  4188. normalMatrix: {
  4189. value: new Matrix3()
  4190. }
  4191. });
  4192. this.matrix = new Matrix4();
  4193. this.matrixWorld = new Matrix4();
  4194. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  4195. this.matrixWorldNeedsUpdate = false;
  4196. this.layers = new Layers();
  4197. this.visible = true;
  4198. this.castShadow = false;
  4199. this.receiveShadow = false;
  4200. this.frustumCulled = true;
  4201. this.renderOrder = 0;
  4202. this.animations = [];
  4203. this.userData = {};
  4204. }
  4205. onBeforeRender() {}
  4206. onAfterRender() {}
  4207. applyMatrix4(matrix) {
  4208. if (this.matrixAutoUpdate) this.updateMatrix();
  4209. this.matrix.premultiply(matrix);
  4210. this.matrix.decompose(this.position, this.quaternion, this.scale);
  4211. }
  4212. applyQuaternion(q) {
  4213. this.quaternion.premultiply(q);
  4214. return this;
  4215. }
  4216. setRotationFromAxisAngle(axis, angle) {
  4217. // assumes axis is normalized
  4218. this.quaternion.setFromAxisAngle(axis, angle);
  4219. }
  4220. setRotationFromEuler(euler) {
  4221. this.quaternion.setFromEuler(euler, true);
  4222. }
  4223. setRotationFromMatrix(m) {
  4224. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4225. this.quaternion.setFromRotationMatrix(m);
  4226. }
  4227. setRotationFromQuaternion(q) {
  4228. // assumes q is normalized
  4229. this.quaternion.copy(q);
  4230. }
  4231. rotateOnAxis(axis, angle) {
  4232. // rotate object on axis in object space
  4233. // axis is assumed to be normalized
  4234. _q1.setFromAxisAngle(axis, angle);
  4235. this.quaternion.multiply(_q1);
  4236. return this;
  4237. }
  4238. rotateOnWorldAxis(axis, angle) {
  4239. // rotate object on axis in world space
  4240. // axis is assumed to be normalized
  4241. // method assumes no rotated parent
  4242. _q1.setFromAxisAngle(axis, angle);
  4243. this.quaternion.premultiply(_q1);
  4244. return this;
  4245. }
  4246. rotateX(angle) {
  4247. return this.rotateOnAxis(_xAxis, angle);
  4248. }
  4249. rotateY(angle) {
  4250. return this.rotateOnAxis(_yAxis, angle);
  4251. }
  4252. rotateZ(angle) {
  4253. return this.rotateOnAxis(_zAxis, angle);
  4254. }
  4255. translateOnAxis(axis, distance) {
  4256. // translate object by distance along axis in object space
  4257. // axis is assumed to be normalized
  4258. _v1$4.copy(axis).applyQuaternion(this.quaternion);
  4259. this.position.add(_v1$4.multiplyScalar(distance));
  4260. return this;
  4261. }
  4262. translateX(distance) {
  4263. return this.translateOnAxis(_xAxis, distance);
  4264. }
  4265. translateY(distance) {
  4266. return this.translateOnAxis(_yAxis, distance);
  4267. }
  4268. translateZ(distance) {
  4269. return this.translateOnAxis(_zAxis, distance);
  4270. }
  4271. localToWorld(vector) {
  4272. return vector.applyMatrix4(this.matrixWorld);
  4273. }
  4274. worldToLocal(vector) {
  4275. return vector.applyMatrix4(_m1$1.copy(this.matrixWorld).invert());
  4276. }
  4277. lookAt(x, y, z) {
  4278. // This method does not support objects having non-uniformly-scaled parent(s)
  4279. if (x.isVector3) {
  4280. _target.copy(x);
  4281. } else {
  4282. _target.set(x, y, z);
  4283. }
  4284. const parent = this.parent;
  4285. this.updateWorldMatrix(true, false);
  4286. _position$3.setFromMatrixPosition(this.matrixWorld);
  4287. if (this.isCamera || this.isLight) {
  4288. _m1$1.lookAt(_position$3, _target, this.up);
  4289. } else {
  4290. _m1$1.lookAt(_target, _position$3, this.up);
  4291. }
  4292. this.quaternion.setFromRotationMatrix(_m1$1);
  4293. if (parent) {
  4294. _m1$1.extractRotation(parent.matrixWorld);
  4295. _q1.setFromRotationMatrix(_m1$1);
  4296. this.quaternion.premultiply(_q1.invert());
  4297. }
  4298. }
  4299. add(object) {
  4300. if (arguments.length > 1) {
  4301. for (let i = 0; i < arguments.length; i++) {
  4302. this.add(arguments[i]);
  4303. }
  4304. return this;
  4305. }
  4306. if (object === this) {
  4307. console.error('THREE.Object3D.add: object can\'t be added as a child of itself.', object);
  4308. return this;
  4309. }
  4310. if (object && object.isObject3D) {
  4311. if (object.parent !== null) {
  4312. object.parent.remove(object);
  4313. }
  4314. object.parent = this;
  4315. this.children.push(object);
  4316. object.dispatchEvent(_addedEvent);
  4317. } else {
  4318. console.error('THREE.Object3D.add: object not an instance of THREE.Object3D.', object);
  4319. }
  4320. return this;
  4321. }
  4322. remove(object) {
  4323. if (arguments.length > 1) {
  4324. for (let i = 0; i < arguments.length; i++) {
  4325. this.remove(arguments[i]);
  4326. }
  4327. return this;
  4328. }
  4329. const index = this.children.indexOf(object);
  4330. if (index !== -1) {
  4331. object.parent = null;
  4332. this.children.splice(index, 1);
  4333. object.dispatchEvent(_removedEvent);
  4334. }
  4335. return this;
  4336. }
  4337. clear() {
  4338. for (let i = 0; i < this.children.length; i++) {
  4339. const object = this.children[i];
  4340. object.parent = null;
  4341. object.dispatchEvent(_removedEvent);
  4342. }
  4343. this.children.length = 0;
  4344. return this;
  4345. }
  4346. attach(object) {
  4347. // adds object as a child of this, while maintaining the object's world transform
  4348. this.updateWorldMatrix(true, false);
  4349. _m1$1.copy(this.matrixWorld).invert();
  4350. if (object.parent !== null) {
  4351. object.parent.updateWorldMatrix(true, false);
  4352. _m1$1.multiply(object.parent.matrixWorld);
  4353. }
  4354. object.applyMatrix4(_m1$1);
  4355. this.add(object);
  4356. object.updateWorldMatrix(false, true);
  4357. return this;
  4358. }
  4359. getObjectById(id) {
  4360. return this.getObjectByProperty('id', id);
  4361. }
  4362. getObjectByName(name) {
  4363. return this.getObjectByProperty('name', name);
  4364. }
  4365. getObjectByProperty(name, value) {
  4366. if (this[name] === value) return this;
  4367. for (let i = 0, l = this.children.length; i < l; i++) {
  4368. const child = this.children[i];
  4369. const object = child.getObjectByProperty(name, value);
  4370. if (object !== undefined) {
  4371. return object;
  4372. }
  4373. }
  4374. return undefined;
  4375. }
  4376. getWorldPosition(target) {
  4377. if (target === undefined) {
  4378. console.warn('THREE.Object3D: .getWorldPosition() target is now required');
  4379. target = new Vector3();
  4380. }
  4381. this.updateWorldMatrix(true, false);
  4382. return target.setFromMatrixPosition(this.matrixWorld);
  4383. }
  4384. getWorldQuaternion(target) {
  4385. if (target === undefined) {
  4386. console.warn('THREE.Object3D: .getWorldQuaternion() target is now required');
  4387. target = new Quaternion();
  4388. }
  4389. this.updateWorldMatrix(true, false);
  4390. this.matrixWorld.decompose(_position$3, target, _scale$2);
  4391. return target;
  4392. }
  4393. getWorldScale(target) {
  4394. if (target === undefined) {
  4395. console.warn('THREE.Object3D: .getWorldScale() target is now required');
  4396. target = new Vector3();
  4397. }
  4398. this.updateWorldMatrix(true, false);
  4399. this.matrixWorld.decompose(_position$3, _quaternion$2, target);
  4400. return target;
  4401. }
  4402. getWorldDirection(target) {
  4403. if (target === undefined) {
  4404. console.warn('THREE.Object3D: .getWorldDirection() target is now required');
  4405. target = new Vector3();
  4406. }
  4407. this.updateWorldMatrix(true, false);
  4408. const e = this.matrixWorld.elements;
  4409. return target.set(e[8], e[9], e[10]).normalize();
  4410. }
  4411. raycast() {}
  4412. traverse(callback) {
  4413. callback(this);
  4414. const children = this.children;
  4415. for (let i = 0, l = children.length; i < l; i++) {
  4416. children[i].traverse(callback);
  4417. }
  4418. }
  4419. traverseVisible(callback) {
  4420. if (this.visible === false) return;
  4421. callback(this);
  4422. const children = this.children;
  4423. for (let i = 0, l = children.length; i < l; i++) {
  4424. children[i].traverseVisible(callback);
  4425. }
  4426. }
  4427. traverseAncestors(callback) {
  4428. const parent = this.parent;
  4429. if (parent !== null) {
  4430. callback(parent);
  4431. parent.traverseAncestors(callback);
  4432. }
  4433. }
  4434. updateMatrix() {
  4435. this.matrix.compose(this.position, this.quaternion, this.scale);
  4436. this.matrixWorldNeedsUpdate = true;
  4437. }
  4438. updateMatrixWorld(force) {
  4439. if (this.matrixAutoUpdate) this.updateMatrix();
  4440. if (this.matrixWorldNeedsUpdate || force) {
  4441. if (this.parent === null) {
  4442. this.matrixWorld.copy(this.matrix);
  4443. } else {
  4444. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4445. }
  4446. this.matrixWorldNeedsUpdate = false;
  4447. force = true;
  4448. } // update children
  4449. const children = this.children;
  4450. for (let i = 0, l = children.length; i < l; i++) {
  4451. children[i].updateMatrixWorld(force);
  4452. }
  4453. }
  4454. updateWorldMatrix(updateParents, updateChildren) {
  4455. const parent = this.parent;
  4456. if (updateParents === true && parent !== null) {
  4457. parent.updateWorldMatrix(true, false);
  4458. }
  4459. if (this.matrixAutoUpdate) this.updateMatrix();
  4460. if (this.parent === null) {
  4461. this.matrixWorld.copy(this.matrix);
  4462. } else {
  4463. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4464. } // update children
  4465. if (updateChildren === true) {
  4466. const children = this.children;
  4467. for (let i = 0, l = children.length; i < l; i++) {
  4468. children[i].updateWorldMatrix(false, true);
  4469. }
  4470. }
  4471. }
  4472. toJSON(meta) {
  4473. // meta is a string when called from JSON.stringify
  4474. const isRootObject = meta === undefined || typeof meta === 'string';
  4475. const output = {}; // meta is a hash used to collect geometries, materials.
  4476. // not providing it implies that this is the root object
  4477. // being serialized.
  4478. if (isRootObject) {
  4479. // initialize meta obj
  4480. meta = {
  4481. geometries: {},
  4482. materials: {},
  4483. textures: {},
  4484. images: {},
  4485. shapes: {},
  4486. skeletons: {},
  4487. animations: {}
  4488. };
  4489. output.metadata = {
  4490. version: 4.5,
  4491. type: 'Object',
  4492. generator: 'Object3D.toJSON'
  4493. };
  4494. } // standard Object3D serialization
  4495. const object = {};
  4496. object.uuid = this.uuid;
  4497. object.type = this.type;
  4498. if (this.name !== '') object.name = this.name;
  4499. if (this.castShadow === true) object.castShadow = true;
  4500. if (this.receiveShadow === true) object.receiveShadow = true;
  4501. if (this.visible === false) object.visible = false;
  4502. if (this.frustumCulled === false) object.frustumCulled = false;
  4503. if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
  4504. if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;
  4505. object.layers = this.layers.mask;
  4506. object.matrix = this.matrix.toArray();
  4507. if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; // object specific properties
  4508. if (this.isInstancedMesh) {
  4509. object.type = 'InstancedMesh';
  4510. object.count = this.count;
  4511. object.instanceMatrix = this.instanceMatrix.toJSON();
  4512. if (this.instanceColor !== null) object.instanceColor = this.instanceColor.toJSON();
  4513. } //
  4514. function serialize(library, element) {
  4515. if (library[element.uuid] === undefined) {
  4516. library[element.uuid] = element.toJSON(meta);
  4517. }
  4518. return element.uuid;
  4519. }
  4520. if (this.isMesh || this.isLine || this.isPoints) {
  4521. object.geometry = serialize(meta.geometries, this.geometry);
  4522. const parameters = this.geometry.parameters;
  4523. if (parameters !== undefined && parameters.shapes !== undefined) {
  4524. const shapes = parameters.shapes;
  4525. if (Array.isArray(shapes)) {
  4526. for (let i = 0, l = shapes.length; i < l; i++) {
  4527. const shape = shapes[i];
  4528. serialize(meta.shapes, shape);
  4529. }
  4530. } else {
  4531. serialize(meta.shapes, shapes);
  4532. }
  4533. }
  4534. }
  4535. if (this.isSkinnedMesh) {
  4536. object.bindMode = this.bindMode;
  4537. object.bindMatrix = this.bindMatrix.toArray();
  4538. if (this.skeleton !== undefined) {
  4539. serialize(meta.skeletons, this.skeleton);
  4540. object.skeleton = this.skeleton.uuid;
  4541. }
  4542. }
  4543. if (this.material !== undefined) {
  4544. if (Array.isArray(this.material)) {
  4545. const uuids = [];
  4546. for (let i = 0, l = this.material.length; i < l; i++) {
  4547. uuids.push(serialize(meta.materials, this.material[i]));
  4548. }
  4549. object.material = uuids;
  4550. } else {
  4551. object.material = serialize(meta.materials, this.material);
  4552. }
  4553. } //
  4554. if (this.children.length > 0) {
  4555. object.children = [];
  4556. for (let i = 0; i < this.children.length; i++) {
  4557. object.children.push(this.children[i].toJSON(meta).object);
  4558. }
  4559. } //
  4560. if (this.animations.length > 0) {
  4561. object.animations = [];
  4562. for (let i = 0; i < this.animations.length; i++) {
  4563. const animation = this.animations[i];
  4564. object.animations.push(serialize(meta.animations, animation));
  4565. }
  4566. }
  4567. if (isRootObject) {
  4568. const geometries = extractFromCache(meta.geometries);
  4569. const materials = extractFromCache(meta.materials);
  4570. const textures = extractFromCache(meta.textures);
  4571. const images = extractFromCache(meta.images);
  4572. const shapes = extractFromCache(meta.shapes);
  4573. const skeletons = extractFromCache(meta.skeletons);
  4574. const animations = extractFromCache(meta.animations);
  4575. if (geometries.length > 0) output.geometries = geometries;
  4576. if (materials.length > 0) output.materials = materials;
  4577. if (textures.length > 0) output.textures = textures;
  4578. if (images.length > 0) output.images = images;
  4579. if (shapes.length > 0) output.shapes = shapes;
  4580. if (skeletons.length > 0) output.skeletons = skeletons;
  4581. if (animations.length > 0) output.animations = animations;
  4582. }
  4583. output.object = object;
  4584. return output; // extract data from the cache hash
  4585. // remove metadata on each item
  4586. // and return as array
  4587. function extractFromCache(cache) {
  4588. const values = [];
  4589. for (const key in cache) {
  4590. const data = cache[key];
  4591. delete data.metadata;
  4592. values.push(data);
  4593. }
  4594. return values;
  4595. }
  4596. }
  4597. clone(recursive) {
  4598. return new this.constructor().copy(this, recursive);
  4599. }
  4600. copy(source, recursive = true) {
  4601. this.name = source.name;
  4602. this.up.copy(source.up);
  4603. this.position.copy(source.position);
  4604. this.rotation.order = source.rotation.order;
  4605. this.quaternion.copy(source.quaternion);
  4606. this.scale.copy(source.scale);
  4607. this.matrix.copy(source.matrix);
  4608. this.matrixWorld.copy(source.matrixWorld);
  4609. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4610. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4611. this.layers.mask = source.layers.mask;
  4612. this.visible = source.visible;
  4613. this.castShadow = source.castShadow;
  4614. this.receiveShadow = source.receiveShadow;
  4615. this.frustumCulled = source.frustumCulled;
  4616. this.renderOrder = source.renderOrder;
  4617. this.userData = JSON.parse(JSON.stringify(source.userData));
  4618. if (recursive === true) {
  4619. for (let i = 0; i < source.children.length; i++) {
  4620. const child = source.children[i];
  4621. this.add(child.clone());
  4622. }
  4623. }
  4624. return this;
  4625. }
  4626. }
  4627. Object3D.DefaultUp = new Vector3(0, 1, 0);
  4628. Object3D.DefaultMatrixAutoUpdate = true;
  4629. Object3D.prototype.isObject3D = true;
  4630. const _vector1 = /*@__PURE__*/new Vector3();
  4631. const _vector2$1 = /*@__PURE__*/new Vector3();
  4632. const _normalMatrix = /*@__PURE__*/new Matrix3();
  4633. class Plane {
  4634. constructor(normal = new Vector3(1, 0, 0), constant = 0) {
  4635. // normal is assumed to be normalized
  4636. this.normal = normal;
  4637. this.constant = constant;
  4638. }
  4639. set(normal, constant) {
  4640. this.normal.copy(normal);
  4641. this.constant = constant;
  4642. return this;
  4643. }
  4644. setComponents(x, y, z, w) {
  4645. this.normal.set(x, y, z);
  4646. this.constant = w;
  4647. return this;
  4648. }
  4649. setFromNormalAndCoplanarPoint(normal, point) {
  4650. this.normal.copy(normal);
  4651. this.constant = -point.dot(this.normal);
  4652. return this;
  4653. }
  4654. setFromCoplanarPoints(a, b, c) {
  4655. const normal = _vector1.subVectors(c, b).cross(_vector2$1.subVectors(a, b)).normalize(); // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  4656. this.setFromNormalAndCoplanarPoint(normal, a);
  4657. return this;
  4658. }
  4659. copy(plane) {
  4660. this.normal.copy(plane.normal);
  4661. this.constant = plane.constant;
  4662. return this;
  4663. }
  4664. normalize() {
  4665. // Note: will lead to a divide by zero if the plane is invalid.
  4666. const inverseNormalLength = 1.0 / this.normal.length();
  4667. this.normal.multiplyScalar(inverseNormalLength);
  4668. this.constant *= inverseNormalLength;
  4669. return this;
  4670. }
  4671. negate() {
  4672. this.constant *= -1;
  4673. this.normal.negate();
  4674. return this;
  4675. }
  4676. distanceToPoint(point) {
  4677. return this.normal.dot(point) + this.constant;
  4678. }
  4679. distanceToSphere(sphere) {
  4680. return this.distanceToPoint(sphere.center) - sphere.radius;
  4681. }
  4682. projectPoint(point, target) {
  4683. if (target === undefined) {
  4684. console.warn('THREE.Plane: .projectPoint() target is now required');
  4685. target = new Vector3();
  4686. }
  4687. return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
  4688. }
  4689. intersectLine(line, target) {
  4690. if (target === undefined) {
  4691. console.warn('THREE.Plane: .intersectLine() target is now required');
  4692. target = new Vector3();
  4693. }
  4694. const direction = line.delta(_vector1);
  4695. const denominator = this.normal.dot(direction);
  4696. if (denominator === 0) {
  4697. // line is coplanar, return origin
  4698. if (this.distanceToPoint(line.start) === 0) {
  4699. return target.copy(line.start);
  4700. } // Unsure if this is the correct method to handle this case.
  4701. return null;
  4702. }
  4703. const t = -(line.start.dot(this.normal) + this.constant) / denominator;
  4704. if (t < 0 || t > 1) {
  4705. return null;
  4706. }
  4707. return target.copy(direction).multiplyScalar(t).add(line.start);
  4708. }
  4709. intersectsLine(line) {
  4710. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  4711. const startSign = this.distanceToPoint(line.start);
  4712. const endSign = this.distanceToPoint(line.end);
  4713. return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
  4714. }
  4715. intersectsBox(box) {
  4716. return box.intersectsPlane(this);
  4717. }
  4718. intersectsSphere(sphere) {
  4719. return sphere.intersectsPlane(this);
  4720. }
  4721. coplanarPoint(target) {
  4722. if (target === undefined) {
  4723. console.warn('THREE.Plane: .coplanarPoint() target is now required');
  4724. target = new Vector3();
  4725. }
  4726. return target.copy(this.normal).multiplyScalar(-this.constant);
  4727. }
  4728. applyMatrix4(matrix, optionalNormalMatrix) {
  4729. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
  4730. const referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
  4731. const normal = this.normal.applyMatrix3(normalMatrix).normalize();
  4732. this.constant = -referencePoint.dot(normal);
  4733. return this;
  4734. }
  4735. translate(offset) {
  4736. this.constant -= offset.dot(this.normal);
  4737. return this;
  4738. }
  4739. equals(plane) {
  4740. return plane.normal.equals(this.normal) && plane.constant === this.constant;
  4741. }
  4742. clone() {
  4743. return new this.constructor().copy(this);
  4744. }
  4745. }
  4746. Plane.prototype.isPlane = true;
  4747. const _v0$1 = /*@__PURE__*/new Vector3();
  4748. const _v1$3 = /*@__PURE__*/new Vector3();
  4749. const _v2$2 = /*@__PURE__*/new Vector3();
  4750. const _v3$1 = /*@__PURE__*/new Vector3();
  4751. const _vab = /*@__PURE__*/new Vector3();
  4752. const _vac = /*@__PURE__*/new Vector3();
  4753. const _vbc = /*@__PURE__*/new Vector3();
  4754. const _vap = /*@__PURE__*/new Vector3();
  4755. const _vbp = /*@__PURE__*/new Vector3();
  4756. const _vcp = /*@__PURE__*/new Vector3();
  4757. class Triangle {
  4758. constructor(a = new Vector3(), b = new Vector3(), c = new Vector3()) {
  4759. this.a = a;
  4760. this.b = b;
  4761. this.c = c;
  4762. }
  4763. static getNormal(a, b, c, target) {
  4764. if (target === undefined) {
  4765. console.warn('THREE.Triangle: .getNormal() target is now required');
  4766. target = new Vector3();
  4767. }
  4768. target.subVectors(c, b);
  4769. _v0$1.subVectors(a, b);
  4770. target.cross(_v0$1);
  4771. const targetLengthSq = target.lengthSq();
  4772. if (targetLengthSq > 0) {
  4773. return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
  4774. }
  4775. return target.set(0, 0, 0);
  4776. } // static/instance method to calculate barycentric coordinates
  4777. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4778. static getBarycoord(point, a, b, c, target) {
  4779. _v0$1.subVectors(c, a);
  4780. _v1$3.subVectors(b, a);
  4781. _v2$2.subVectors(point, a);
  4782. const dot00 = _v0$1.dot(_v0$1);
  4783. const dot01 = _v0$1.dot(_v1$3);
  4784. const dot02 = _v0$1.dot(_v2$2);
  4785. const dot11 = _v1$3.dot(_v1$3);
  4786. const dot12 = _v1$3.dot(_v2$2);
  4787. const denom = dot00 * dot11 - dot01 * dot01;
  4788. if (target === undefined) {
  4789. console.warn('THREE.Triangle: .getBarycoord() target is now required');
  4790. target = new Vector3();
  4791. } // collinear or singular triangle
  4792. if (denom === 0) {
  4793. // arbitrary location outside of triangle?
  4794. // not sure if this is the best idea, maybe should be returning undefined
  4795. return target.set(-2, -1, -1);
  4796. }
  4797. const invDenom = 1 / denom;
  4798. const u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  4799. const v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1
  4800. return target.set(1 - u - v, v, u);
  4801. }
  4802. static containsPoint(point, a, b, c) {
  4803. this.getBarycoord(point, a, b, c, _v3$1);
  4804. return _v3$1.x >= 0 && _v3$1.y >= 0 && _v3$1.x + _v3$1.y <= 1;
  4805. }
  4806. static getUV(point, p1, p2, p3, uv1, uv2, uv3, target) {
  4807. this.getBarycoord(point, p1, p2, p3, _v3$1);
  4808. target.set(0, 0);
  4809. target.addScaledVector(uv1, _v3$1.x);
  4810. target.addScaledVector(uv2, _v3$1.y);
  4811. target.addScaledVector(uv3, _v3$1.z);
  4812. return target;
  4813. }
  4814. static isFrontFacing(a, b, c, direction) {
  4815. _v0$1.subVectors(c, b);
  4816. _v1$3.subVectors(a, b); // strictly front facing
  4817. return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
  4818. }
  4819. set(a, b, c) {
  4820. this.a.copy(a);
  4821. this.b.copy(b);
  4822. this.c.copy(c);
  4823. return this;
  4824. }
  4825. setFromPointsAndIndices(points, i0, i1, i2) {
  4826. this.a.copy(points[i0]);
  4827. this.b.copy(points[i1]);
  4828. this.c.copy(points[i2]);
  4829. return this;
  4830. }
  4831. clone() {
  4832. return new this.constructor().copy(this);
  4833. }
  4834. copy(triangle) {
  4835. this.a.copy(triangle.a);
  4836. this.b.copy(triangle.b);
  4837. this.c.copy(triangle.c);
  4838. return this;
  4839. }
  4840. getArea() {
  4841. _v0$1.subVectors(this.c, this.b);
  4842. _v1$3.subVectors(this.a, this.b);
  4843. return _v0$1.cross(_v1$3).length() * 0.5;
  4844. }
  4845. getMidpoint(target) {
  4846. if (target === undefined) {
  4847. console.warn('THREE.Triangle: .getMidpoint() target is now required');
  4848. target = new Vector3();
  4849. }
  4850. return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  4851. }
  4852. getNormal(target) {
  4853. return Triangle.getNormal(this.a, this.b, this.c, target);
  4854. }
  4855. getPlane(target) {
  4856. if (target === undefined) {
  4857. console.warn('THREE.Triangle: .getPlane() target is now required');
  4858. target = new Plane();
  4859. }
  4860. return target.setFromCoplanarPoints(this.a, this.b, this.c);
  4861. }
  4862. getBarycoord(point, target) {
  4863. return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
  4864. }
  4865. getUV(point, uv1, uv2, uv3, target) {
  4866. return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
  4867. }
  4868. containsPoint(point) {
  4869. return Triangle.containsPoint(point, this.a, this.b, this.c);
  4870. }
  4871. isFrontFacing(direction) {
  4872. return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
  4873. }
  4874. intersectsBox(box) {
  4875. return box.intersectsTriangle(this);
  4876. }
  4877. closestPointToPoint(p, target) {
  4878. if (target === undefined) {
  4879. console.warn('THREE.Triangle: .closestPointToPoint() target is now required');
  4880. target = new Vector3();
  4881. }
  4882. const a = this.a,
  4883. b = this.b,
  4884. c = this.c;
  4885. let v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  4886. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  4887. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  4888. // basically, we're distinguishing which of the voronoi regions of the triangle
  4889. // the point lies in with the minimum amount of redundant computation.
  4890. _vab.subVectors(b, a);
  4891. _vac.subVectors(c, a);
  4892. _vap.subVectors(p, a);
  4893. const d1 = _vab.dot(_vap);
  4894. const d2 = _vac.dot(_vap);
  4895. if (d1 <= 0 && d2 <= 0) {
  4896. // vertex region of A; barycentric coords (1, 0, 0)
  4897. return target.copy(a);
  4898. }
  4899. _vbp.subVectors(p, b);
  4900. const d3 = _vab.dot(_vbp);
  4901. const d4 = _vac.dot(_vbp);
  4902. if (d3 >= 0 && d4 <= d3) {
  4903. // vertex region of B; barycentric coords (0, 1, 0)
  4904. return target.copy(b);
  4905. }
  4906. const vc = d1 * d4 - d3 * d2;
  4907. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  4908. v = d1 / (d1 - d3); // edge region of AB; barycentric coords (1-v, v, 0)
  4909. return target.copy(a).addScaledVector(_vab, v);
  4910. }
  4911. _vcp.subVectors(p, c);
  4912. const d5 = _vab.dot(_vcp);
  4913. const d6 = _vac.dot(_vcp);
  4914. if (d6 >= 0 && d5 <= d6) {
  4915. // vertex region of C; barycentric coords (0, 0, 1)
  4916. return target.copy(c);
  4917. }
  4918. const vb = d5 * d2 - d1 * d6;
  4919. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  4920. w = d2 / (d2 - d6); // edge region of AC; barycentric coords (1-w, 0, w)
  4921. return target.copy(a).addScaledVector(_vac, w);
  4922. }
  4923. const va = d3 * d6 - d5 * d4;
  4924. if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
  4925. _vbc.subVectors(c, b);
  4926. w = (d4 - d3) / (d4 - d3 + (d5 - d6)); // edge region of BC; barycentric coords (0, 1-w, w)
  4927. return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
  4928. } // face region
  4929. const denom = 1 / (va + vb + vc); // u = va * denom
  4930. v = vb * denom;
  4931. w = vc * denom;
  4932. return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
  4933. }
  4934. equals(triangle) {
  4935. return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
  4936. }
  4937. }
  4938. let materialId = 0;
  4939. function Material() {
  4940. Object.defineProperty(this, 'id', {
  4941. value: materialId++
  4942. });
  4943. this.uuid = generateUUID();
  4944. this.name = '';
  4945. this.type = 'Material';
  4946. this.fog = true;
  4947. this.blending = NormalBlending;
  4948. this.side = FrontSide;
  4949. this.vertexColors = false;
  4950. this.opacity = 1;
  4951. this.transparent = false;
  4952. this.blendSrc = SrcAlphaFactor;
  4953. this.blendDst = OneMinusSrcAlphaFactor;
  4954. this.blendEquation = AddEquation;
  4955. this.blendSrcAlpha = null;
  4956. this.blendDstAlpha = null;
  4957. this.blendEquationAlpha = null;
  4958. this.depthFunc = LessEqualDepth;
  4959. this.depthTest = true;
  4960. this.depthWrite = true;
  4961. this.stencilWriteMask = 0xff;
  4962. this.stencilFunc = AlwaysStencilFunc;
  4963. this.stencilRef = 0;
  4964. this.stencilFuncMask = 0xff;
  4965. this.stencilFail = KeepStencilOp;
  4966. this.stencilZFail = KeepStencilOp;
  4967. this.stencilZPass = KeepStencilOp;
  4968. this.stencilWrite = false;
  4969. this.clippingPlanes = null;
  4970. this.clipIntersection = false;
  4971. this.clipShadows = false;
  4972. this.shadowSide = null;
  4973. this.colorWrite = true;
  4974. this.precision = null; // override the renderer's default precision for this material
  4975. this.polygonOffset = false;
  4976. this.polygonOffsetFactor = 0;
  4977. this.polygonOffsetUnits = 0;
  4978. this.dithering = false;
  4979. this.alphaTest = 0;
  4980. this.alphaToCoverage = false;
  4981. this.premultipliedAlpha = false;
  4982. this.visible = true;
  4983. this.toneMapped = true;
  4984. this.userData = {};
  4985. this.version = 0;
  4986. }
  4987. Material.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  4988. constructor: Material,
  4989. isMaterial: true,
  4990. onBuild: function ()
  4991. /* shaderobject, renderer */
  4992. {},
  4993. onBeforeCompile: function ()
  4994. /* shaderobject, renderer */
  4995. {},
  4996. customProgramCacheKey: function () {
  4997. return this.onBeforeCompile.toString();
  4998. },
  4999. setValues: function (values) {
  5000. if (values === undefined) return;
  5001. for (const key in values) {
  5002. const newValue = values[key];
  5003. if (newValue === undefined) {
  5004. console.warn('THREE.Material: \'' + key + '\' parameter is undefined.');
  5005. continue;
  5006. } // for backward compatability if shading is set in the constructor
  5007. if (key === 'shading') {
  5008. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  5009. this.flatShading = newValue === FlatShading ? true : false;
  5010. continue;
  5011. }
  5012. const currentValue = this[key];
  5013. if (currentValue === undefined) {
  5014. console.warn('THREE.' + this.type + ': \'' + key + '\' is not a property of this material.');
  5015. continue;
  5016. }
  5017. if (currentValue && currentValue.isColor) {
  5018. currentValue.set(newValue);
  5019. } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
  5020. currentValue.copy(newValue);
  5021. } else {
  5022. this[key] = newValue;
  5023. }
  5024. }
  5025. },
  5026. toJSON: function (meta) {
  5027. const isRoot = meta === undefined || typeof meta === 'string';
  5028. if (isRoot) {
  5029. meta = {
  5030. textures: {},
  5031. images: {}
  5032. };
  5033. }
  5034. const data = {
  5035. metadata: {
  5036. version: 4.5,
  5037. type: 'Material',
  5038. generator: 'Material.toJSON'
  5039. }
  5040. }; // standard Material serialization
  5041. data.uuid = this.uuid;
  5042. data.type = this.type;
  5043. if (this.name !== '') data.name = this.name;
  5044. if (this.color && this.color.isColor) data.color = this.color.getHex();
  5045. if (this.roughness !== undefined) data.roughness = this.roughness;
  5046. if (this.metalness !== undefined) data.metalness = this.metalness;
  5047. if (this.sheen && this.sheen.isColor) data.sheen = this.sheen.getHex();
  5048. if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
  5049. if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
  5050. if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
  5051. if (this.shininess !== undefined) data.shininess = this.shininess;
  5052. if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;
  5053. if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness;
  5054. if (this.clearcoatMap && this.clearcoatMap.isTexture) {
  5055. data.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid;
  5056. }
  5057. if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) {
  5058. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid;
  5059. }
  5060. if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
  5061. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;
  5062. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5063. }
  5064. if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid;
  5065. if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid;
  5066. if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid;
  5067. if (this.lightMap && this.lightMap.isTexture) {
  5068. data.lightMap = this.lightMap.toJSON(meta).uuid;
  5069. data.lightMapIntensity = this.lightMapIntensity;
  5070. }
  5071. if (this.aoMap && this.aoMap.isTexture) {
  5072. data.aoMap = this.aoMap.toJSON(meta).uuid;
  5073. data.aoMapIntensity = this.aoMapIntensity;
  5074. }
  5075. if (this.bumpMap && this.bumpMap.isTexture) {
  5076. data.bumpMap = this.bumpMap.toJSON(meta).uuid;
  5077. data.bumpScale = this.bumpScale;
  5078. }
  5079. if (this.normalMap && this.normalMap.isTexture) {
  5080. data.normalMap = this.normalMap.toJSON(meta).uuid;
  5081. data.normalMapType = this.normalMapType;
  5082. data.normalScale = this.normalScale.toArray();
  5083. }
  5084. if (this.displacementMap && this.displacementMap.isTexture) {
  5085. data.displacementMap = this.displacementMap.toJSON(meta).uuid;
  5086. data.displacementScale = this.displacementScale;
  5087. data.displacementBias = this.displacementBias;
  5088. }
  5089. if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;
  5090. if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;
  5091. if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;
  5092. if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid;
  5093. if (this.envMap && this.envMap.isTexture) {
  5094. data.envMap = this.envMap.toJSON(meta).uuid;
  5095. if (this.combine !== undefined) data.combine = this.combine;
  5096. }
  5097. if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
  5098. if (this.reflectivity !== undefined) data.reflectivity = this.reflectivity;
  5099. if (this.refractionRatio !== undefined) data.refractionRatio = this.refractionRatio;
  5100. if (this.gradientMap && this.gradientMap.isTexture) {
  5101. data.gradientMap = this.gradientMap.toJSON(meta).uuid;
  5102. }
  5103. if (this.size !== undefined) data.size = this.size;
  5104. if (this.shadowSide !== null) data.shadowSide = this.shadowSide;
  5105. if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
  5106. if (this.blending !== NormalBlending) data.blending = this.blending;
  5107. if (this.side !== FrontSide) data.side = this.side;
  5108. if (this.vertexColors) data.vertexColors = true;
  5109. if (this.opacity < 1) data.opacity = this.opacity;
  5110. if (this.transparent === true) data.transparent = this.transparent;
  5111. data.depthFunc = this.depthFunc;
  5112. data.depthTest = this.depthTest;
  5113. data.depthWrite = this.depthWrite;
  5114. data.colorWrite = this.colorWrite;
  5115. data.stencilWrite = this.stencilWrite;
  5116. data.stencilWriteMask = this.stencilWriteMask;
  5117. data.stencilFunc = this.stencilFunc;
  5118. data.stencilRef = this.stencilRef;
  5119. data.stencilFuncMask = this.stencilFuncMask;
  5120. data.stencilFail = this.stencilFail;
  5121. data.stencilZFail = this.stencilZFail;
  5122. data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial)
  5123. if (this.rotation && this.rotation !== 0) data.rotation = this.rotation;
  5124. if (this.polygonOffset === true) data.polygonOffset = true;
  5125. if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5126. if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5127. if (this.linewidth && this.linewidth !== 1) data.linewidth = this.linewidth;
  5128. if (this.dashSize !== undefined) data.dashSize = this.dashSize;
  5129. if (this.gapSize !== undefined) data.gapSize = this.gapSize;
  5130. if (this.scale !== undefined) data.scale = this.scale;
  5131. if (this.dithering === true) data.dithering = true;
  5132. if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
  5133. if (this.alphaToCoverage === true) data.alphaToCoverage = this.alphaToCoverage;
  5134. if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
  5135. if (this.wireframe === true) data.wireframe = this.wireframe;
  5136. if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
  5137. if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;
  5138. if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;
  5139. if (this.morphTargets === true) data.morphTargets = true;
  5140. if (this.morphNormals === true) data.morphNormals = true;
  5141. if (this.flatShading === true) data.flatShading = this.flatShading;
  5142. if (this.visible === false) data.visible = false;
  5143. if (this.toneMapped === false) data.toneMapped = false;
  5144. if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData; // TODO: Copied from Object3D.toJSON
  5145. function extractFromCache(cache) {
  5146. const values = [];
  5147. for (const key in cache) {
  5148. const data = cache[key];
  5149. delete data.metadata;
  5150. values.push(data);
  5151. }
  5152. return values;
  5153. }
  5154. if (isRoot) {
  5155. const textures = extractFromCache(meta.textures);
  5156. const images = extractFromCache(meta.images);
  5157. if (textures.length > 0) data.textures = textures;
  5158. if (images.length > 0) data.images = images;
  5159. }
  5160. return data;
  5161. },
  5162. clone: function () {
  5163. return new this.constructor().copy(this);
  5164. },
  5165. copy: function (source) {
  5166. this.name = source.name;
  5167. this.fog = source.fog;
  5168. this.blending = source.blending;
  5169. this.side = source.side;
  5170. this.vertexColors = source.vertexColors;
  5171. this.opacity = source.opacity;
  5172. this.transparent = source.transparent;
  5173. this.blendSrc = source.blendSrc;
  5174. this.blendDst = source.blendDst;
  5175. this.blendEquation = source.blendEquation;
  5176. this.blendSrcAlpha = source.blendSrcAlpha;
  5177. this.blendDstAlpha = source.blendDstAlpha;
  5178. this.blendEquationAlpha = source.blendEquationAlpha;
  5179. this.depthFunc = source.depthFunc;
  5180. this.depthTest = source.depthTest;
  5181. this.depthWrite = source.depthWrite;
  5182. this.stencilWriteMask = source.stencilWriteMask;
  5183. this.stencilFunc = source.stencilFunc;
  5184. this.stencilRef = source.stencilRef;
  5185. this.stencilFuncMask = source.stencilFuncMask;
  5186. this.stencilFail = source.stencilFail;
  5187. this.stencilZFail = source.stencilZFail;
  5188. this.stencilZPass = source.stencilZPass;
  5189. this.stencilWrite = source.stencilWrite;
  5190. const srcPlanes = source.clippingPlanes;
  5191. let dstPlanes = null;
  5192. if (srcPlanes !== null) {
  5193. const n = srcPlanes.length;
  5194. dstPlanes = new Array(n);
  5195. for (let i = 0; i !== n; ++i) {
  5196. dstPlanes[i] = srcPlanes[i].clone();
  5197. }
  5198. }
  5199. this.clippingPlanes = dstPlanes;
  5200. this.clipIntersection = source.clipIntersection;
  5201. this.clipShadows = source.clipShadows;
  5202. this.shadowSide = source.shadowSide;
  5203. this.colorWrite = source.colorWrite;
  5204. this.precision = source.precision;
  5205. this.polygonOffset = source.polygonOffset;
  5206. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5207. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5208. this.dithering = source.dithering;
  5209. this.alphaTest = source.alphaTest;
  5210. this.alphaToCoverage = source.alphaToCoverage;
  5211. this.premultipliedAlpha = source.premultipliedAlpha;
  5212. this.visible = source.visible;
  5213. this.toneMapped = source.toneMapped;
  5214. this.userData = JSON.parse(JSON.stringify(source.userData));
  5215. return this;
  5216. },
  5217. dispose: function () {
  5218. this.dispatchEvent({
  5219. type: 'dispose'
  5220. });
  5221. }
  5222. });
  5223. Object.defineProperty(Material.prototype, 'needsUpdate', {
  5224. set: function (value) {
  5225. if (value === true) this.version++;
  5226. }
  5227. });
  5228. const _colorKeywords = {
  5229. 'aliceblue': 0xF0F8FF,
  5230. 'antiquewhite': 0xFAEBD7,
  5231. 'aqua': 0x00FFFF,
  5232. 'aquamarine': 0x7FFFD4,
  5233. 'azure': 0xF0FFFF,
  5234. 'beige': 0xF5F5DC,
  5235. 'bisque': 0xFFE4C4,
  5236. 'black': 0x000000,
  5237. 'blanchedalmond': 0xFFEBCD,
  5238. 'blue': 0x0000FF,
  5239. 'blueviolet': 0x8A2BE2,
  5240. 'brown': 0xA52A2A,
  5241. 'burlywood': 0xDEB887,
  5242. 'cadetblue': 0x5F9EA0,
  5243. 'chartreuse': 0x7FFF00,
  5244. 'chocolate': 0xD2691E,
  5245. 'coral': 0xFF7F50,
  5246. 'cornflowerblue': 0x6495ED,
  5247. 'cornsilk': 0xFFF8DC,
  5248. 'crimson': 0xDC143C,
  5249. 'cyan': 0x00FFFF,
  5250. 'darkblue': 0x00008B,
  5251. 'darkcyan': 0x008B8B,
  5252. 'darkgoldenrod': 0xB8860B,
  5253. 'darkgray': 0xA9A9A9,
  5254. 'darkgreen': 0x006400,
  5255. 'darkgrey': 0xA9A9A9,
  5256. 'darkkhaki': 0xBDB76B,
  5257. 'darkmagenta': 0x8B008B,
  5258. 'darkolivegreen': 0x556B2F,
  5259. 'darkorange': 0xFF8C00,
  5260. 'darkorchid': 0x9932CC,
  5261. 'darkred': 0x8B0000,
  5262. 'darksalmon': 0xE9967A,
  5263. 'darkseagreen': 0x8FBC8F,
  5264. 'darkslateblue': 0x483D8B,
  5265. 'darkslategray': 0x2F4F4F,
  5266. 'darkslategrey': 0x2F4F4F,
  5267. 'darkturquoise': 0x00CED1,
  5268. 'darkviolet': 0x9400D3,
  5269. 'deeppink': 0xFF1493,
  5270. 'deepskyblue': 0x00BFFF,
  5271. 'dimgray': 0x696969,
  5272. 'dimgrey': 0x696969,
  5273. 'dodgerblue': 0x1E90FF,
  5274. 'firebrick': 0xB22222,
  5275. 'floralwhite': 0xFFFAF0,
  5276. 'forestgreen': 0x228B22,
  5277. 'fuchsia': 0xFF00FF,
  5278. 'gainsboro': 0xDCDCDC,
  5279. 'ghostwhite': 0xF8F8FF,
  5280. 'gold': 0xFFD700,
  5281. 'goldenrod': 0xDAA520,
  5282. 'gray': 0x808080,
  5283. 'green': 0x008000,
  5284. 'greenyellow': 0xADFF2F,
  5285. 'grey': 0x808080,
  5286. 'honeydew': 0xF0FFF0,
  5287. 'hotpink': 0xFF69B4,
  5288. 'indianred': 0xCD5C5C,
  5289. 'indigo': 0x4B0082,
  5290. 'ivory': 0xFFFFF0,
  5291. 'khaki': 0xF0E68C,
  5292. 'lavender': 0xE6E6FA,
  5293. 'lavenderblush': 0xFFF0F5,
  5294. 'lawngreen': 0x7CFC00,
  5295. 'lemonchiffon': 0xFFFACD,
  5296. 'lightblue': 0xADD8E6,
  5297. 'lightcoral': 0xF08080,
  5298. 'lightcyan': 0xE0FFFF,
  5299. 'lightgoldenrodyellow': 0xFAFAD2,
  5300. 'lightgray': 0xD3D3D3,
  5301. 'lightgreen': 0x90EE90,
  5302. 'lightgrey': 0xD3D3D3,
  5303. 'lightpink': 0xFFB6C1,
  5304. 'lightsalmon': 0xFFA07A,
  5305. 'lightseagreen': 0x20B2AA,
  5306. 'lightskyblue': 0x87CEFA,
  5307. 'lightslategray': 0x778899,
  5308. 'lightslategrey': 0x778899,
  5309. 'lightsteelblue': 0xB0C4DE,
  5310. 'lightyellow': 0xFFFFE0,
  5311. 'lime': 0x00FF00,
  5312. 'limegreen': 0x32CD32,
  5313. 'linen': 0xFAF0E6,
  5314. 'magenta': 0xFF00FF,
  5315. 'maroon': 0x800000,
  5316. 'mediumaquamarine': 0x66CDAA,
  5317. 'mediumblue': 0x0000CD,
  5318. 'mediumorchid': 0xBA55D3,
  5319. 'mediumpurple': 0x9370DB,
  5320. 'mediumseagreen': 0x3CB371,
  5321. 'mediumslateblue': 0x7B68EE,
  5322. 'mediumspringgreen': 0x00FA9A,
  5323. 'mediumturquoise': 0x48D1CC,
  5324. 'mediumvioletred': 0xC71585,
  5325. 'midnightblue': 0x191970,
  5326. 'mintcream': 0xF5FFFA,
  5327. 'mistyrose': 0xFFE4E1,
  5328. 'moccasin': 0xFFE4B5,
  5329. 'navajowhite': 0xFFDEAD,
  5330. 'navy': 0x000080,
  5331. 'oldlace': 0xFDF5E6,
  5332. 'olive': 0x808000,
  5333. 'olivedrab': 0x6B8E23,
  5334. 'orange': 0xFFA500,
  5335. 'orangered': 0xFF4500,
  5336. 'orchid': 0xDA70D6,
  5337. 'palegoldenrod': 0xEEE8AA,
  5338. 'palegreen': 0x98FB98,
  5339. 'paleturquoise': 0xAFEEEE,
  5340. 'palevioletred': 0xDB7093,
  5341. 'papayawhip': 0xFFEFD5,
  5342. 'peachpuff': 0xFFDAB9,
  5343. 'peru': 0xCD853F,
  5344. 'pink': 0xFFC0CB,
  5345. 'plum': 0xDDA0DD,
  5346. 'powderblue': 0xB0E0E6,
  5347. 'purple': 0x800080,
  5348. 'rebeccapurple': 0x663399,
  5349. 'red': 0xFF0000,
  5350. 'rosybrown': 0xBC8F8F,
  5351. 'royalblue': 0x4169E1,
  5352. 'saddlebrown': 0x8B4513,
  5353. 'salmon': 0xFA8072,
  5354. 'sandybrown': 0xF4A460,
  5355. 'seagreen': 0x2E8B57,
  5356. 'seashell': 0xFFF5EE,
  5357. 'sienna': 0xA0522D,
  5358. 'silver': 0xC0C0C0,
  5359. 'skyblue': 0x87CEEB,
  5360. 'slateblue': 0x6A5ACD,
  5361. 'slategray': 0x708090,
  5362. 'slategrey': 0x708090,
  5363. 'snow': 0xFFFAFA,
  5364. 'springgreen': 0x00FF7F,
  5365. 'steelblue': 0x4682B4,
  5366. 'tan': 0xD2B48C,
  5367. 'teal': 0x008080,
  5368. 'thistle': 0xD8BFD8,
  5369. 'tomato': 0xFF6347,
  5370. 'turquoise': 0x40E0D0,
  5371. 'violet': 0xEE82EE,
  5372. 'wheat': 0xF5DEB3,
  5373. 'white': 0xFFFFFF,
  5374. 'whitesmoke': 0xF5F5F5,
  5375. 'yellow': 0xFFFF00,
  5376. 'yellowgreen': 0x9ACD32
  5377. };
  5378. const _hslA = {
  5379. h: 0,
  5380. s: 0,
  5381. l: 0
  5382. };
  5383. const _hslB = {
  5384. h: 0,
  5385. s: 0,
  5386. l: 0
  5387. };
  5388. function hue2rgb(p, q, t) {
  5389. if (t < 0) t += 1;
  5390. if (t > 1) t -= 1;
  5391. if (t < 1 / 6) return p + (q - p) * 6 * t;
  5392. if (t < 1 / 2) return q;
  5393. if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t);
  5394. return p;
  5395. }
  5396. function SRGBToLinear(c) {
  5397. return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
  5398. }
  5399. function LinearToSRGB(c) {
  5400. return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
  5401. }
  5402. class Color {
  5403. constructor(r, g, b) {
  5404. if (g === undefined && b === undefined) {
  5405. // r is THREE.Color, hex or string
  5406. return this.set(r);
  5407. }
  5408. return this.setRGB(r, g, b);
  5409. }
  5410. set(value) {
  5411. if (value && value.isColor) {
  5412. this.copy(value);
  5413. } else if (typeof value === 'number') {
  5414. this.setHex(value);
  5415. } else if (typeof value === 'string') {
  5416. this.setStyle(value);
  5417. }
  5418. return this;
  5419. }
  5420. setScalar(scalar) {
  5421. this.r = scalar;
  5422. this.g = scalar;
  5423. this.b = scalar;
  5424. return this;
  5425. }
  5426. setHex(hex) {
  5427. hex = Math.floor(hex);
  5428. this.r = (hex >> 16 & 255) / 255;
  5429. this.g = (hex >> 8 & 255) / 255;
  5430. this.b = (hex & 255) / 255;
  5431. return this;
  5432. }
  5433. setRGB(r, g, b) {
  5434. this.r = r;
  5435. this.g = g;
  5436. this.b = b;
  5437. return this;
  5438. }
  5439. setHSL(h, s, l) {
  5440. // h,s,l ranges are in 0.0 - 1.0
  5441. h = euclideanModulo(h, 1);
  5442. s = clamp(s, 0, 1);
  5443. l = clamp(l, 0, 1);
  5444. if (s === 0) {
  5445. this.r = this.g = this.b = l;
  5446. } else {
  5447. const p = l <= 0.5 ? l * (1 + s) : l + s - l * s;
  5448. const q = 2 * l - p;
  5449. this.r = hue2rgb(q, p, h + 1 / 3);
  5450. this.g = hue2rgb(q, p, h);
  5451. this.b = hue2rgb(q, p, h - 1 / 3);
  5452. }
  5453. return this;
  5454. }
  5455. setStyle(style) {
  5456. function handleAlpha(string) {
  5457. if (string === undefined) return;
  5458. if (parseFloat(string) < 1) {
  5459. console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
  5460. }
  5461. }
  5462. let m;
  5463. if (m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec(style)) {
  5464. // rgb / hsl
  5465. let color;
  5466. const name = m[1];
  5467. const components = m[2];
  5468. switch (name) {
  5469. case 'rgb':
  5470. case 'rgba':
  5471. if (color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  5472. // rgb(255,0,0) rgba(255,0,0,0.5)
  5473. this.r = Math.min(255, parseInt(color[1], 10)) / 255;
  5474. this.g = Math.min(255, parseInt(color[2], 10)) / 255;
  5475. this.b = Math.min(255, parseInt(color[3], 10)) / 255;
  5476. handleAlpha(color[4]);
  5477. return this;
  5478. }
  5479. if (color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  5480. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5481. this.r = Math.min(100, parseInt(color[1], 10)) / 100;
  5482. this.g = Math.min(100, parseInt(color[2], 10)) / 100;
  5483. this.b = Math.min(100, parseInt(color[3], 10)) / 100;
  5484. handleAlpha(color[4]);
  5485. return this;
  5486. }
  5487. break;
  5488. case 'hsl':
  5489. case 'hsla':
  5490. if (color = /^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  5491. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5492. const h = parseFloat(color[1]) / 360;
  5493. const s = parseInt(color[2], 10) / 100;
  5494. const l = parseInt(color[3], 10) / 100;
  5495. handleAlpha(color[4]);
  5496. return this.setHSL(h, s, l);
  5497. }
  5498. break;
  5499. }
  5500. } else if (m = /^\#([A-Fa-f\d]+)$/.exec(style)) {
  5501. // hex color
  5502. const hex = m[1];
  5503. const size = hex.length;
  5504. if (size === 3) {
  5505. // #ff0
  5506. this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
  5507. this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
  5508. this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
  5509. return this;
  5510. } else if (size === 6) {
  5511. // #ff0000
  5512. this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
  5513. this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
  5514. this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
  5515. return this;
  5516. }
  5517. }
  5518. if (style && style.length > 0) {
  5519. return this.setColorName(style);
  5520. }
  5521. return this;
  5522. }
  5523. setColorName(style) {
  5524. // color keywords
  5525. const hex = _colorKeywords[style.toLowerCase()];
  5526. if (hex !== undefined) {
  5527. // red
  5528. this.setHex(hex);
  5529. } else {
  5530. // unknown color
  5531. console.warn('THREE.Color: Unknown color ' + style);
  5532. }
  5533. return this;
  5534. }
  5535. clone() {
  5536. return new this.constructor(this.r, this.g, this.b);
  5537. }
  5538. copy(color) {
  5539. this.r = color.r;
  5540. this.g = color.g;
  5541. this.b = color.b;
  5542. return this;
  5543. }
  5544. copyGammaToLinear(color, gammaFactor = 2.0) {
  5545. this.r = Math.pow(color.r, gammaFactor);
  5546. this.g = Math.pow(color.g, gammaFactor);
  5547. this.b = Math.pow(color.b, gammaFactor);
  5548. return this;
  5549. }
  5550. copyLinearToGamma(color, gammaFactor = 2.0) {
  5551. const safeInverse = gammaFactor > 0 ? 1.0 / gammaFactor : 1.0;
  5552. this.r = Math.pow(color.r, safeInverse);
  5553. this.g = Math.pow(color.g, safeInverse);
  5554. this.b = Math.pow(color.b, safeInverse);
  5555. return this;
  5556. }
  5557. convertGammaToLinear(gammaFactor) {
  5558. this.copyGammaToLinear(this, gammaFactor);
  5559. return this;
  5560. }
  5561. convertLinearToGamma(gammaFactor) {
  5562. this.copyLinearToGamma(this, gammaFactor);
  5563. return this;
  5564. }
  5565. copySRGBToLinear(color) {
  5566. this.r = SRGBToLinear(color.r);
  5567. this.g = SRGBToLinear(color.g);
  5568. this.b = SRGBToLinear(color.b);
  5569. return this;
  5570. }
  5571. copyLinearToSRGB(color) {
  5572. this.r = LinearToSRGB(color.r);
  5573. this.g = LinearToSRGB(color.g);
  5574. this.b = LinearToSRGB(color.b);
  5575. return this;
  5576. }
  5577. convertSRGBToLinear() {
  5578. this.copySRGBToLinear(this);
  5579. return this;
  5580. }
  5581. convertLinearToSRGB() {
  5582. this.copyLinearToSRGB(this);
  5583. return this;
  5584. }
  5585. getHex() {
  5586. return this.r * 255 << 16 ^ this.g * 255 << 8 ^ this.b * 255 << 0;
  5587. }
  5588. getHexString() {
  5589. return ('000000' + this.getHex().toString(16)).slice(-6);
  5590. }
  5591. getHSL(target) {
  5592. // h,s,l ranges are in 0.0 - 1.0
  5593. if (target === undefined) {
  5594. console.warn('THREE.Color: .getHSL() target is now required');
  5595. target = {
  5596. h: 0,
  5597. s: 0,
  5598. l: 0
  5599. };
  5600. }
  5601. const r = this.r,
  5602. g = this.g,
  5603. b = this.b;
  5604. const max = Math.max(r, g, b);
  5605. const min = Math.min(r, g, b);
  5606. let hue, saturation;
  5607. const lightness = (min + max) / 2.0;
  5608. if (min === max) {
  5609. hue = 0;
  5610. saturation = 0;
  5611. } else {
  5612. const delta = max - min;
  5613. saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
  5614. switch (max) {
  5615. case r:
  5616. hue = (g - b) / delta + (g < b ? 6 : 0);
  5617. break;
  5618. case g:
  5619. hue = (b - r) / delta + 2;
  5620. break;
  5621. case b:
  5622. hue = (r - g) / delta + 4;
  5623. break;
  5624. }
  5625. hue /= 6;
  5626. }
  5627. target.h = hue;
  5628. target.s = saturation;
  5629. target.l = lightness;
  5630. return target;
  5631. }
  5632. getStyle() {
  5633. return 'rgb(' + (this.r * 255 | 0) + ',' + (this.g * 255 | 0) + ',' + (this.b * 255 | 0) + ')';
  5634. }
  5635. offsetHSL(h, s, l) {
  5636. this.getHSL(_hslA);
  5637. _hslA.h += h;
  5638. _hslA.s += s;
  5639. _hslA.l += l;
  5640. this.setHSL(_hslA.h, _hslA.s, _hslA.l);
  5641. return this;
  5642. }
  5643. add(color) {
  5644. this.r += color.r;
  5645. this.g += color.g;
  5646. this.b += color.b;
  5647. return this;
  5648. }
  5649. addColors(color1, color2) {
  5650. this.r = color1.r + color2.r;
  5651. this.g = color1.g + color2.g;
  5652. this.b = color1.b + color2.b;
  5653. return this;
  5654. }
  5655. addScalar(s) {
  5656. this.r += s;
  5657. this.g += s;
  5658. this.b += s;
  5659. return this;
  5660. }
  5661. sub(color) {
  5662. this.r = Math.max(0, this.r - color.r);
  5663. this.g = Math.max(0, this.g - color.g);
  5664. this.b = Math.max(0, this.b - color.b);
  5665. return this;
  5666. }
  5667. multiply(color) {
  5668. this.r *= color.r;
  5669. this.g *= color.g;
  5670. this.b *= color.b;
  5671. return this;
  5672. }
  5673. multiplyScalar(s) {
  5674. this.r *= s;
  5675. this.g *= s;
  5676. this.b *= s;
  5677. return this;
  5678. }
  5679. lerp(color, alpha) {
  5680. this.r += (color.r - this.r) * alpha;
  5681. this.g += (color.g - this.g) * alpha;
  5682. this.b += (color.b - this.b) * alpha;
  5683. return this;
  5684. }
  5685. lerpColors(color1, color2, alpha) {
  5686. this.r = color1.r + (color2.r - color1.r) * alpha;
  5687. this.g = color1.g + (color2.g - color1.g) * alpha;
  5688. this.b = color1.b + (color2.b - color1.b) * alpha;
  5689. return this;
  5690. }
  5691. lerpHSL(color, alpha) {
  5692. this.getHSL(_hslA);
  5693. color.getHSL(_hslB);
  5694. const h = lerp(_hslA.h, _hslB.h, alpha);
  5695. const s = lerp(_hslA.s, _hslB.s, alpha);
  5696. const l = lerp(_hslA.l, _hslB.l, alpha);
  5697. this.setHSL(h, s, l);
  5698. return this;
  5699. }
  5700. equals(c) {
  5701. return c.r === this.r && c.g === this.g && c.b === this.b;
  5702. }
  5703. fromArray(array, offset = 0) {
  5704. this.r = array[offset];
  5705. this.g = array[offset + 1];
  5706. this.b = array[offset + 2];
  5707. return this;
  5708. }
  5709. toArray(array = [], offset = 0) {
  5710. array[offset] = this.r;
  5711. array[offset + 1] = this.g;
  5712. array[offset + 2] = this.b;
  5713. return array;
  5714. }
  5715. fromBufferAttribute(attribute, index) {
  5716. this.r = attribute.getX(index);
  5717. this.g = attribute.getY(index);
  5718. this.b = attribute.getZ(index);
  5719. if (attribute.normalized === true) {
  5720. // assuming Uint8Array
  5721. this.r /= 255;
  5722. this.g /= 255;
  5723. this.b /= 255;
  5724. }
  5725. return this;
  5726. }
  5727. toJSON() {
  5728. return this.getHex();
  5729. }
  5730. }
  5731. Color.NAMES = _colorKeywords;
  5732. Color.prototype.isColor = true;
  5733. Color.prototype.r = 1;
  5734. Color.prototype.g = 1;
  5735. Color.prototype.b = 1;
  5736. /**
  5737. * parameters = {
  5738. * color: <hex>,
  5739. * opacity: <float>,
  5740. * map: new THREE.Texture( <Image> ),
  5741. *
  5742. * lightMap: new THREE.Texture( <Image> ),
  5743. * lightMapIntensity: <float>
  5744. *
  5745. * aoMap: new THREE.Texture( <Image> ),
  5746. * aoMapIntensity: <float>
  5747. *
  5748. * specularMap: new THREE.Texture( <Image> ),
  5749. *
  5750. * alphaMap: new THREE.Texture( <Image> ),
  5751. *
  5752. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  5753. * combine: THREE.Multiply,
  5754. * reflectivity: <float>,
  5755. * refractionRatio: <float>,
  5756. *
  5757. * depthTest: <bool>,
  5758. * depthWrite: <bool>,
  5759. *
  5760. * wireframe: <boolean>,
  5761. * wireframeLinewidth: <float>,
  5762. *
  5763. * morphTargets: <bool>
  5764. * }
  5765. */
  5766. class MeshBasicMaterial extends Material {
  5767. constructor(parameters) {
  5768. super();
  5769. this.type = 'MeshBasicMaterial';
  5770. this.color = new Color(0xffffff); // emissive
  5771. this.map = null;
  5772. this.lightMap = null;
  5773. this.lightMapIntensity = 1.0;
  5774. this.aoMap = null;
  5775. this.aoMapIntensity = 1.0;
  5776. this.specularMap = null;
  5777. this.alphaMap = null;
  5778. this.envMap = null;
  5779. this.combine = MultiplyOperation;
  5780. this.reflectivity = 1;
  5781. this.refractionRatio = 0.98;
  5782. this.wireframe = false;
  5783. this.wireframeLinewidth = 1;
  5784. this.wireframeLinecap = 'round';
  5785. this.wireframeLinejoin = 'round';
  5786. this.morphTargets = false;
  5787. this.setValues(parameters);
  5788. }
  5789. copy(source) {
  5790. super.copy(source);
  5791. this.color.copy(source.color);
  5792. this.map = source.map;
  5793. this.lightMap = source.lightMap;
  5794. this.lightMapIntensity = source.lightMapIntensity;
  5795. this.aoMap = source.aoMap;
  5796. this.aoMapIntensity = source.aoMapIntensity;
  5797. this.specularMap = source.specularMap;
  5798. this.alphaMap = source.alphaMap;
  5799. this.envMap = source.envMap;
  5800. this.combine = source.combine;
  5801. this.reflectivity = source.reflectivity;
  5802. this.refractionRatio = source.refractionRatio;
  5803. this.wireframe = source.wireframe;
  5804. this.wireframeLinewidth = source.wireframeLinewidth;
  5805. this.wireframeLinecap = source.wireframeLinecap;
  5806. this.wireframeLinejoin = source.wireframeLinejoin;
  5807. this.morphTargets = source.morphTargets;
  5808. return this;
  5809. }
  5810. }
  5811. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  5812. const _vector$9 = /*@__PURE__*/new Vector3();
  5813. const _vector2 = /*@__PURE__*/new Vector2();
  5814. class BufferAttribute {
  5815. constructor(array, itemSize, normalized) {
  5816. if (Array.isArray(array)) {
  5817. throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
  5818. }
  5819. this.name = '';
  5820. this.array = array;
  5821. this.itemSize = itemSize;
  5822. this.count = array !== undefined ? array.length / itemSize : 0;
  5823. this.normalized = normalized === true;
  5824. this.usage = StaticDrawUsage;
  5825. this.updateRange = {
  5826. offset: 0,
  5827. count: -1
  5828. };
  5829. this.version = 0;
  5830. }
  5831. onUploadCallback() {}
  5832. set needsUpdate(value) {
  5833. if (value === true) this.version++;
  5834. }
  5835. setUsage(value) {
  5836. this.usage = value;
  5837. return this;
  5838. }
  5839. copy(source) {
  5840. this.name = source.name;
  5841. this.array = new source.array.constructor(source.array);
  5842. this.itemSize = source.itemSize;
  5843. this.count = source.count;
  5844. this.normalized = source.normalized;
  5845. this.usage = source.usage;
  5846. return this;
  5847. }
  5848. copyAt(index1, attribute, index2) {
  5849. index1 *= this.itemSize;
  5850. index2 *= attribute.itemSize;
  5851. for (let i = 0, l = this.itemSize; i < l; i++) {
  5852. this.array[index1 + i] = attribute.array[index2 + i];
  5853. }
  5854. return this;
  5855. }
  5856. copyArray(array) {
  5857. this.array.set(array);
  5858. return this;
  5859. }
  5860. copyColorsArray(colors) {
  5861. const array = this.array;
  5862. let offset = 0;
  5863. for (let i = 0, l = colors.length; i < l; i++) {
  5864. let color = colors[i];
  5865. if (color === undefined) {
  5866. console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined', i);
  5867. color = new Color();
  5868. }
  5869. array[offset++] = color.r;
  5870. array[offset++] = color.g;
  5871. array[offset++] = color.b;
  5872. }
  5873. return this;
  5874. }
  5875. copyVector2sArray(vectors) {
  5876. const array = this.array;
  5877. let offset = 0;
  5878. for (let i = 0, l = vectors.length; i < l; i++) {
  5879. let vector = vectors[i];
  5880. if (vector === undefined) {
  5881. console.warn('THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i);
  5882. vector = new Vector2();
  5883. }
  5884. array[offset++] = vector.x;
  5885. array[offset++] = vector.y;
  5886. }
  5887. return this;
  5888. }
  5889. copyVector3sArray(vectors) {
  5890. const array = this.array;
  5891. let offset = 0;
  5892. for (let i = 0, l = vectors.length; i < l; i++) {
  5893. let vector = vectors[i];
  5894. if (vector === undefined) {
  5895. console.warn('THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i);
  5896. vector = new Vector3();
  5897. }
  5898. array[offset++] = vector.x;
  5899. array[offset++] = vector.y;
  5900. array[offset++] = vector.z;
  5901. }
  5902. return this;
  5903. }
  5904. copyVector4sArray(vectors) {
  5905. const array = this.array;
  5906. let offset = 0;
  5907. for (let i = 0, l = vectors.length; i < l; i++) {
  5908. let vector = vectors[i];
  5909. if (vector === undefined) {
  5910. console.warn('THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i);
  5911. vector = new Vector4();
  5912. }
  5913. array[offset++] = vector.x;
  5914. array[offset++] = vector.y;
  5915. array[offset++] = vector.z;
  5916. array[offset++] = vector.w;
  5917. }
  5918. return this;
  5919. }
  5920. applyMatrix3(m) {
  5921. if (this.itemSize === 2) {
  5922. for (let i = 0, l = this.count; i < l; i++) {
  5923. _vector2.fromBufferAttribute(this, i);
  5924. _vector2.applyMatrix3(m);
  5925. this.setXY(i, _vector2.x, _vector2.y);
  5926. }
  5927. } else if (this.itemSize === 3) {
  5928. for (let i = 0, l = this.count; i < l; i++) {
  5929. _vector$9.fromBufferAttribute(this, i);
  5930. _vector$9.applyMatrix3(m);
  5931. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5932. }
  5933. }
  5934. return this;
  5935. }
  5936. applyMatrix4(m) {
  5937. for (let i = 0, l = this.count; i < l; i++) {
  5938. _vector$9.x = this.getX(i);
  5939. _vector$9.y = this.getY(i);
  5940. _vector$9.z = this.getZ(i);
  5941. _vector$9.applyMatrix4(m);
  5942. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5943. }
  5944. return this;
  5945. }
  5946. applyNormalMatrix(m) {
  5947. for (let i = 0, l = this.count; i < l; i++) {
  5948. _vector$9.x = this.getX(i);
  5949. _vector$9.y = this.getY(i);
  5950. _vector$9.z = this.getZ(i);
  5951. _vector$9.applyNormalMatrix(m);
  5952. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5953. }
  5954. return this;
  5955. }
  5956. transformDirection(m) {
  5957. for (let i = 0, l = this.count; i < l; i++) {
  5958. _vector$9.x = this.getX(i);
  5959. _vector$9.y = this.getY(i);
  5960. _vector$9.z = this.getZ(i);
  5961. _vector$9.transformDirection(m);
  5962. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5963. }
  5964. return this;
  5965. }
  5966. set(value, offset = 0) {
  5967. this.array.set(value, offset);
  5968. return this;
  5969. }
  5970. getX(index) {
  5971. return this.array[index * this.itemSize];
  5972. }
  5973. setX(index, x) {
  5974. this.array[index * this.itemSize] = x;
  5975. return this;
  5976. }
  5977. getY(index) {
  5978. return this.array[index * this.itemSize + 1];
  5979. }
  5980. setY(index, y) {
  5981. this.array[index * this.itemSize + 1] = y;
  5982. return this;
  5983. }
  5984. getZ(index) {
  5985. return this.array[index * this.itemSize + 2];
  5986. }
  5987. setZ(index, z) {
  5988. this.array[index * this.itemSize + 2] = z;
  5989. return this;
  5990. }
  5991. getW(index) {
  5992. return this.array[index * this.itemSize + 3];
  5993. }
  5994. setW(index, w) {
  5995. this.array[index * this.itemSize + 3] = w;
  5996. return this;
  5997. }
  5998. setXY(index, x, y) {
  5999. index *= this.itemSize;
  6000. this.array[index + 0] = x;
  6001. this.array[index + 1] = y;
  6002. return this;
  6003. }
  6004. setXYZ(index, x, y, z) {
  6005. index *= this.itemSize;
  6006. this.array[index + 0] = x;
  6007. this.array[index + 1] = y;
  6008. this.array[index + 2] = z;
  6009. return this;
  6010. }
  6011. setXYZW(index, x, y, z, w) {
  6012. index *= this.itemSize;
  6013. this.array[index + 0] = x;
  6014. this.array[index + 1] = y;
  6015. this.array[index + 2] = z;
  6016. this.array[index + 3] = w;
  6017. return this;
  6018. }
  6019. onUpload(callback) {
  6020. this.onUploadCallback = callback;
  6021. return this;
  6022. }
  6023. clone() {
  6024. return new this.constructor(this.array, this.itemSize).copy(this);
  6025. }
  6026. toJSON() {
  6027. const data = {
  6028. itemSize: this.itemSize,
  6029. type: this.array.constructor.name,
  6030. array: Array.prototype.slice.call(this.array),
  6031. normalized: this.normalized
  6032. };
  6033. if (this.name !== '') data.name = this.name;
  6034. if (this.usage !== StaticDrawUsage) data.usage = this.usage;
  6035. if (this.updateRange.offset !== 0 || this.updateRange.count !== -1) data.updateRange = this.updateRange;
  6036. return data;
  6037. }
  6038. }
  6039. BufferAttribute.prototype.isBufferAttribute = true; //
  6040. class Int8BufferAttribute extends BufferAttribute {
  6041. constructor(array, itemSize, normalized) {
  6042. super(new Int8Array(array), itemSize, normalized);
  6043. }
  6044. }
  6045. class Uint8BufferAttribute extends BufferAttribute {
  6046. constructor(array, itemSize, normalized) {
  6047. super(new Uint8Array(array), itemSize, normalized);
  6048. }
  6049. }
  6050. class Uint8ClampedBufferAttribute extends BufferAttribute {
  6051. constructor(array, itemSize, normalized) {
  6052. super(new Uint8ClampedArray(array), itemSize, normalized);
  6053. }
  6054. }
  6055. class Int16BufferAttribute extends BufferAttribute {
  6056. constructor(array, itemSize, normalized) {
  6057. super(new Int16Array(array), itemSize, normalized);
  6058. }
  6059. }
  6060. class Uint16BufferAttribute extends BufferAttribute {
  6061. constructor(array, itemSize, normalized) {
  6062. super(new Uint16Array(array), itemSize, normalized);
  6063. }
  6064. }
  6065. class Int32BufferAttribute extends BufferAttribute {
  6066. constructor(array, itemSize, normalized) {
  6067. super(new Int32Array(array), itemSize, normalized);
  6068. }
  6069. }
  6070. class Uint32BufferAttribute extends BufferAttribute {
  6071. constructor(array, itemSize, normalized) {
  6072. super(new Uint32Array(array), itemSize, normalized);
  6073. }
  6074. }
  6075. class Float16BufferAttribute extends BufferAttribute {
  6076. constructor(array, itemSize, normalized) {
  6077. super(new Uint16Array(array), itemSize, normalized);
  6078. }
  6079. }
  6080. Float16BufferAttribute.prototype.isFloat16BufferAttribute = true;
  6081. class Float32BufferAttribute extends BufferAttribute {
  6082. constructor(array, itemSize, normalized) {
  6083. super(new Float32Array(array), itemSize, normalized);
  6084. }
  6085. }
  6086. class Float64BufferAttribute extends BufferAttribute {
  6087. constructor(array, itemSize, normalized) {
  6088. super(new Float64Array(array), itemSize, normalized);
  6089. }
  6090. } //
  6091. function arrayMax(array) {
  6092. if (array.length === 0) return -Infinity;
  6093. let max = array[0];
  6094. for (let i = 1, l = array.length; i < l; ++i) {
  6095. if (array[i] > max) max = array[i];
  6096. }
  6097. return max;
  6098. }
  6099. const TYPED_ARRAYS = {
  6100. Int8Array: Int8Array,
  6101. Uint8Array: Uint8Array,
  6102. Uint8ClampedArray: Uint8ClampedArray,
  6103. Int16Array: Int16Array,
  6104. Uint16Array: Uint16Array,
  6105. Int32Array: Int32Array,
  6106. Uint32Array: Uint32Array,
  6107. Float32Array: Float32Array,
  6108. Float64Array: Float64Array
  6109. };
  6110. function getTypedArray(type, buffer) {
  6111. return new TYPED_ARRAYS[type](buffer);
  6112. }
  6113. let _id = 0;
  6114. const _m1 = /*@__PURE__*/new Matrix4();
  6115. const _obj = /*@__PURE__*/new Object3D();
  6116. const _offset = /*@__PURE__*/new Vector3();
  6117. const _box$1 = /*@__PURE__*/new Box3();
  6118. const _boxMorphTargets = /*@__PURE__*/new Box3();
  6119. const _vector$8 = /*@__PURE__*/new Vector3();
  6120. class BufferGeometry extends EventDispatcher {
  6121. constructor() {
  6122. super();
  6123. Object.defineProperty(this, 'id', {
  6124. value: _id++
  6125. });
  6126. this.uuid = generateUUID();
  6127. this.name = '';
  6128. this.type = 'BufferGeometry';
  6129. this.index = null;
  6130. this.attributes = {};
  6131. this.morphAttributes = {};
  6132. this.morphTargetsRelative = false;
  6133. this.groups = [];
  6134. this.boundingBox = null;
  6135. this.boundingSphere = null;
  6136. this.drawRange = {
  6137. start: 0,
  6138. count: Infinity
  6139. };
  6140. this.userData = {};
  6141. }
  6142. getIndex() {
  6143. return this.index;
  6144. }
  6145. setIndex(index) {
  6146. if (Array.isArray(index)) {
  6147. this.index = new (arrayMax(index) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
  6148. } else {
  6149. this.index = index;
  6150. }
  6151. return this;
  6152. }
  6153. getAttribute(name) {
  6154. return this.attributes[name];
  6155. }
  6156. setAttribute(name, attribute) {
  6157. this.attributes[name] = attribute;
  6158. return this;
  6159. }
  6160. deleteAttribute(name) {
  6161. delete this.attributes[name];
  6162. return this;
  6163. }
  6164. hasAttribute(name) {
  6165. return this.attributes[name] !== undefined;
  6166. }
  6167. addGroup(start, count, materialIndex = 0) {
  6168. this.groups.push({
  6169. start: start,
  6170. count: count,
  6171. materialIndex: materialIndex
  6172. });
  6173. }
  6174. clearGroups() {
  6175. this.groups = [];
  6176. }
  6177. setDrawRange(start, count) {
  6178. this.drawRange.start = start;
  6179. this.drawRange.count = count;
  6180. }
  6181. applyMatrix4(matrix) {
  6182. const position = this.attributes.position;
  6183. if (position !== undefined) {
  6184. position.applyMatrix4(matrix);
  6185. position.needsUpdate = true;
  6186. }
  6187. const normal = this.attributes.normal;
  6188. if (normal !== undefined) {
  6189. const normalMatrix = new Matrix3().getNormalMatrix(matrix);
  6190. normal.applyNormalMatrix(normalMatrix);
  6191. normal.needsUpdate = true;
  6192. }
  6193. const tangent = this.attributes.tangent;
  6194. if (tangent !== undefined) {
  6195. tangent.transformDirection(matrix);
  6196. tangent.needsUpdate = true;
  6197. }
  6198. if (this.boundingBox !== null) {
  6199. this.computeBoundingBox();
  6200. }
  6201. if (this.boundingSphere !== null) {
  6202. this.computeBoundingSphere();
  6203. }
  6204. return this;
  6205. }
  6206. rotateX(angle) {
  6207. // rotate geometry around world x-axis
  6208. _m1.makeRotationX(angle);
  6209. this.applyMatrix4(_m1);
  6210. return this;
  6211. }
  6212. rotateY(angle) {
  6213. // rotate geometry around world y-axis
  6214. _m1.makeRotationY(angle);
  6215. this.applyMatrix4(_m1);
  6216. return this;
  6217. }
  6218. rotateZ(angle) {
  6219. // rotate geometry around world z-axis
  6220. _m1.makeRotationZ(angle);
  6221. this.applyMatrix4(_m1);
  6222. return this;
  6223. }
  6224. translate(x, y, z) {
  6225. // translate geometry
  6226. _m1.makeTranslation(x, y, z);
  6227. this.applyMatrix4(_m1);
  6228. return this;
  6229. }
  6230. scale(x, y, z) {
  6231. // scale geometry
  6232. _m1.makeScale(x, y, z);
  6233. this.applyMatrix4(_m1);
  6234. return this;
  6235. }
  6236. lookAt(vector) {
  6237. _obj.lookAt(vector);
  6238. _obj.updateMatrix();
  6239. this.applyMatrix4(_obj.matrix);
  6240. return this;
  6241. }
  6242. center() {
  6243. this.computeBoundingBox();
  6244. this.boundingBox.getCenter(_offset).negate();
  6245. this.translate(_offset.x, _offset.y, _offset.z);
  6246. return this;
  6247. }
  6248. setFromPoints(points) {
  6249. const position = [];
  6250. for (let i = 0, l = points.length; i < l; i++) {
  6251. const point = points[i];
  6252. position.push(point.x, point.y, point.z || 0);
  6253. }
  6254. this.setAttribute('position', new Float32BufferAttribute(position, 3));
  6255. return this;
  6256. }
  6257. computeBoundingBox() {
  6258. if (this.boundingBox === null) {
  6259. this.boundingBox = new Box3();
  6260. }
  6261. const position = this.attributes.position;
  6262. const morphAttributesPosition = this.morphAttributes.position;
  6263. if (position && position.isGLBufferAttribute) {
  6264. console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this);
  6265. this.boundingBox.set(new Vector3(-Infinity, -Infinity, -Infinity), new Vector3(+Infinity, +Infinity, +Infinity));
  6266. return;
  6267. }
  6268. if (position !== undefined) {
  6269. this.boundingBox.setFromBufferAttribute(position); // process morph attributes if present
  6270. if (morphAttributesPosition) {
  6271. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6272. const morphAttribute = morphAttributesPosition[i];
  6273. _box$1.setFromBufferAttribute(morphAttribute);
  6274. if (this.morphTargetsRelative) {
  6275. _vector$8.addVectors(this.boundingBox.min, _box$1.min);
  6276. this.boundingBox.expandByPoint(_vector$8);
  6277. _vector$8.addVectors(this.boundingBox.max, _box$1.max);
  6278. this.boundingBox.expandByPoint(_vector$8);
  6279. } else {
  6280. this.boundingBox.expandByPoint(_box$1.min);
  6281. this.boundingBox.expandByPoint(_box$1.max);
  6282. }
  6283. }
  6284. }
  6285. } else {
  6286. this.boundingBox.makeEmpty();
  6287. }
  6288. if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
  6289. console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  6290. }
  6291. }
  6292. computeBoundingSphere() {
  6293. if (this.boundingSphere === null) {
  6294. this.boundingSphere = new Sphere();
  6295. }
  6296. const position = this.attributes.position;
  6297. const morphAttributesPosition = this.morphAttributes.position;
  6298. if (position && position.isGLBufferAttribute) {
  6299. console.error('THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this);
  6300. this.boundingSphere.set(new Vector3(), Infinity);
  6301. return;
  6302. }
  6303. if (position) {
  6304. // first, find the center of the bounding sphere
  6305. const center = this.boundingSphere.center;
  6306. _box$1.setFromBufferAttribute(position); // process morph attributes if present
  6307. if (morphAttributesPosition) {
  6308. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6309. const morphAttribute = morphAttributesPosition[i];
  6310. _boxMorphTargets.setFromBufferAttribute(morphAttribute);
  6311. if (this.morphTargetsRelative) {
  6312. _vector$8.addVectors(_box$1.min, _boxMorphTargets.min);
  6313. _box$1.expandByPoint(_vector$8);
  6314. _vector$8.addVectors(_box$1.max, _boxMorphTargets.max);
  6315. _box$1.expandByPoint(_vector$8);
  6316. } else {
  6317. _box$1.expandByPoint(_boxMorphTargets.min);
  6318. _box$1.expandByPoint(_boxMorphTargets.max);
  6319. }
  6320. }
  6321. }
  6322. _box$1.getCenter(center); // second, try to find a boundingSphere with a radius smaller than the
  6323. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6324. let maxRadiusSq = 0;
  6325. for (let i = 0, il = position.count; i < il; i++) {
  6326. _vector$8.fromBufferAttribute(position, i);
  6327. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6328. } // process morph attributes if present
  6329. if (morphAttributesPosition) {
  6330. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6331. const morphAttribute = morphAttributesPosition[i];
  6332. const morphTargetsRelative = this.morphTargetsRelative;
  6333. for (let j = 0, jl = morphAttribute.count; j < jl; j++) {
  6334. _vector$8.fromBufferAttribute(morphAttribute, j);
  6335. if (morphTargetsRelative) {
  6336. _offset.fromBufferAttribute(position, j);
  6337. _vector$8.add(_offset);
  6338. }
  6339. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6340. }
  6341. }
  6342. }
  6343. this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
  6344. if (isNaN(this.boundingSphere.radius)) {
  6345. console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
  6346. }
  6347. }
  6348. }
  6349. computeFaceNormals() {// backwards compatibility
  6350. }
  6351. computeTangents() {
  6352. const index = this.index;
  6353. const attributes = this.attributes; // based on http://www.terathon.com/code/tangent.html
  6354. // (per vertex tangents)
  6355. if (index === null || attributes.position === undefined || attributes.normal === undefined || attributes.uv === undefined) {
  6356. console.error('THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)');
  6357. return;
  6358. }
  6359. const indices = index.array;
  6360. const positions = attributes.position.array;
  6361. const normals = attributes.normal.array;
  6362. const uvs = attributes.uv.array;
  6363. const nVertices = positions.length / 3;
  6364. if (attributes.tangent === undefined) {
  6365. this.setAttribute('tangent', new BufferAttribute(new Float32Array(4 * nVertices), 4));
  6366. }
  6367. const tangents = attributes.tangent.array;
  6368. const tan1 = [],
  6369. tan2 = [];
  6370. for (let i = 0; i < nVertices; i++) {
  6371. tan1[i] = new Vector3();
  6372. tan2[i] = new Vector3();
  6373. }
  6374. const vA = new Vector3(),
  6375. vB = new Vector3(),
  6376. vC = new Vector3(),
  6377. uvA = new Vector2(),
  6378. uvB = new Vector2(),
  6379. uvC = new Vector2(),
  6380. sdir = new Vector3(),
  6381. tdir = new Vector3();
  6382. function handleTriangle(a, b, c) {
  6383. vA.fromArray(positions, a * 3);
  6384. vB.fromArray(positions, b * 3);
  6385. vC.fromArray(positions, c * 3);
  6386. uvA.fromArray(uvs, a * 2);
  6387. uvB.fromArray(uvs, b * 2);
  6388. uvC.fromArray(uvs, c * 2);
  6389. vB.sub(vA);
  6390. vC.sub(vA);
  6391. uvB.sub(uvA);
  6392. uvC.sub(uvA);
  6393. const r = 1.0 / (uvB.x * uvC.y - uvC.x * uvB.y); // silently ignore degenerate uv triangles having coincident or colinear vertices
  6394. if (!isFinite(r)) return;
  6395. sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r);
  6396. tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r);
  6397. tan1[a].add(sdir);
  6398. tan1[b].add(sdir);
  6399. tan1[c].add(sdir);
  6400. tan2[a].add(tdir);
  6401. tan2[b].add(tdir);
  6402. tan2[c].add(tdir);
  6403. }
  6404. let groups = this.groups;
  6405. if (groups.length === 0) {
  6406. groups = [{
  6407. start: 0,
  6408. count: indices.length
  6409. }];
  6410. }
  6411. for (let i = 0, il = groups.length; i < il; ++i) {
  6412. const group = groups[i];
  6413. const start = group.start;
  6414. const count = group.count;
  6415. for (let j = start, jl = start + count; j < jl; j += 3) {
  6416. handleTriangle(indices[j + 0], indices[j + 1], indices[j + 2]);
  6417. }
  6418. }
  6419. const tmp = new Vector3(),
  6420. tmp2 = new Vector3();
  6421. const n = new Vector3(),
  6422. n2 = new Vector3();
  6423. function handleVertex(v) {
  6424. n.fromArray(normals, v * 3);
  6425. n2.copy(n);
  6426. const t = tan1[v]; // Gram-Schmidt orthogonalize
  6427. tmp.copy(t);
  6428. tmp.sub(n.multiplyScalar(n.dot(t))).normalize(); // Calculate handedness
  6429. tmp2.crossVectors(n2, t);
  6430. const test = tmp2.dot(tan2[v]);
  6431. const w = test < 0.0 ? -1.0 : 1.0;
  6432. tangents[v * 4] = tmp.x;
  6433. tangents[v * 4 + 1] = tmp.y;
  6434. tangents[v * 4 + 2] = tmp.z;
  6435. tangents[v * 4 + 3] = w;
  6436. }
  6437. for (let i = 0, il = groups.length; i < il; ++i) {
  6438. const group = groups[i];
  6439. const start = group.start;
  6440. const count = group.count;
  6441. for (let j = start, jl = start + count; j < jl; j += 3) {
  6442. handleVertex(indices[j + 0]);
  6443. handleVertex(indices[j + 1]);
  6444. handleVertex(indices[j + 2]);
  6445. }
  6446. }
  6447. }
  6448. computeVertexNormals() {
  6449. const index = this.index;
  6450. const positionAttribute = this.getAttribute('position');
  6451. if (positionAttribute !== undefined) {
  6452. let normalAttribute = this.getAttribute('normal');
  6453. if (normalAttribute === undefined) {
  6454. normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3);
  6455. this.setAttribute('normal', normalAttribute);
  6456. } else {
  6457. // reset existing normals to zero
  6458. for (let i = 0, il = normalAttribute.count; i < il; i++) {
  6459. normalAttribute.setXYZ(i, 0, 0, 0);
  6460. }
  6461. }
  6462. const pA = new Vector3(),
  6463. pB = new Vector3(),
  6464. pC = new Vector3();
  6465. const nA = new Vector3(),
  6466. nB = new Vector3(),
  6467. nC = new Vector3();
  6468. const cb = new Vector3(),
  6469. ab = new Vector3(); // indexed elements
  6470. if (index) {
  6471. for (let i = 0, il = index.count; i < il; i += 3) {
  6472. const vA = index.getX(i + 0);
  6473. const vB = index.getX(i + 1);
  6474. const vC = index.getX(i + 2);
  6475. pA.fromBufferAttribute(positionAttribute, vA);
  6476. pB.fromBufferAttribute(positionAttribute, vB);
  6477. pC.fromBufferAttribute(positionAttribute, vC);
  6478. cb.subVectors(pC, pB);
  6479. ab.subVectors(pA, pB);
  6480. cb.cross(ab);
  6481. nA.fromBufferAttribute(normalAttribute, vA);
  6482. nB.fromBufferAttribute(normalAttribute, vB);
  6483. nC.fromBufferAttribute(normalAttribute, vC);
  6484. nA.add(cb);
  6485. nB.add(cb);
  6486. nC.add(cb);
  6487. normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z);
  6488. normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z);
  6489. normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z);
  6490. }
  6491. } else {
  6492. // non-indexed elements (unconnected triangle soup)
  6493. for (let i = 0, il = positionAttribute.count; i < il; i += 3) {
  6494. pA.fromBufferAttribute(positionAttribute, i + 0);
  6495. pB.fromBufferAttribute(positionAttribute, i + 1);
  6496. pC.fromBufferAttribute(positionAttribute, i + 2);
  6497. cb.subVectors(pC, pB);
  6498. ab.subVectors(pA, pB);
  6499. cb.cross(ab);
  6500. normalAttribute.setXYZ(i + 0, cb.x, cb.y, cb.z);
  6501. normalAttribute.setXYZ(i + 1, cb.x, cb.y, cb.z);
  6502. normalAttribute.setXYZ(i + 2, cb.x, cb.y, cb.z);
  6503. }
  6504. }
  6505. this.normalizeNormals();
  6506. normalAttribute.needsUpdate = true;
  6507. }
  6508. }
  6509. merge(geometry, offset) {
  6510. if (!(geometry && geometry.isBufferGeometry)) {
  6511. console.error('THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry);
  6512. return;
  6513. }
  6514. if (offset === undefined) {
  6515. offset = 0;
  6516. console.warn('THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.');
  6517. }
  6518. const attributes = this.attributes;
  6519. for (const key in attributes) {
  6520. if (geometry.attributes[key] === undefined) continue;
  6521. const attribute1 = attributes[key];
  6522. const attributeArray1 = attribute1.array;
  6523. const attribute2 = geometry.attributes[key];
  6524. const attributeArray2 = attribute2.array;
  6525. const attributeOffset = attribute2.itemSize * offset;
  6526. const length = Math.min(attributeArray2.length, attributeArray1.length - attributeOffset);
  6527. for (let i = 0, j = attributeOffset; i < length; i++, j++) {
  6528. attributeArray1[j] = attributeArray2[i];
  6529. }
  6530. }
  6531. return this;
  6532. }
  6533. normalizeNormals() {
  6534. const normals = this.attributes.normal;
  6535. for (let i = 0, il = normals.count; i < il; i++) {
  6536. _vector$8.fromBufferAttribute(normals, i);
  6537. _vector$8.normalize();
  6538. normals.setXYZ(i, _vector$8.x, _vector$8.y, _vector$8.z);
  6539. }
  6540. }
  6541. toNonIndexed() {
  6542. function convertBufferAttribute(attribute, indices) {
  6543. const array = attribute.array;
  6544. const itemSize = attribute.itemSize;
  6545. const normalized = attribute.normalized;
  6546. const array2 = new array.constructor(indices.length * itemSize);
  6547. let index = 0,
  6548. index2 = 0;
  6549. for (let i = 0, l = indices.length; i < l; i++) {
  6550. index = indices[i] * itemSize;
  6551. for (let j = 0; j < itemSize; j++) {
  6552. array2[index2++] = array[index++];
  6553. }
  6554. }
  6555. return new BufferAttribute(array2, itemSize, normalized);
  6556. } //
  6557. if (this.index === null) {
  6558. console.warn('THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.');
  6559. return this;
  6560. }
  6561. const geometry2 = new BufferGeometry();
  6562. const indices = this.index.array;
  6563. const attributes = this.attributes; // attributes
  6564. for (const name in attributes) {
  6565. const attribute = attributes[name];
  6566. const newAttribute = convertBufferAttribute(attribute, indices);
  6567. geometry2.setAttribute(name, newAttribute);
  6568. } // morph attributes
  6569. const morphAttributes = this.morphAttributes;
  6570. for (const name in morphAttributes) {
  6571. const morphArray = [];
  6572. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6573. for (let i = 0, il = morphAttribute.length; i < il; i++) {
  6574. const attribute = morphAttribute[i];
  6575. const newAttribute = convertBufferAttribute(attribute, indices);
  6576. morphArray.push(newAttribute);
  6577. }
  6578. geometry2.morphAttributes[name] = morphArray;
  6579. }
  6580. geometry2.morphTargetsRelative = this.morphTargetsRelative; // groups
  6581. const groups = this.groups;
  6582. for (let i = 0, l = groups.length; i < l; i++) {
  6583. const group = groups[i];
  6584. geometry2.addGroup(group.start, group.count, group.materialIndex);
  6585. }
  6586. return geometry2;
  6587. }
  6588. toJSON() {
  6589. const data = {
  6590. metadata: {
  6591. version: 4.5,
  6592. type: 'BufferGeometry',
  6593. generator: 'BufferGeometry.toJSON'
  6594. }
  6595. }; // standard BufferGeometry serialization
  6596. data.uuid = this.uuid;
  6597. data.type = this.type;
  6598. if (this.name !== '') data.name = this.name;
  6599. if (Object.keys(this.userData).length > 0) data.userData = this.userData;
  6600. if (this.parameters !== undefined) {
  6601. const parameters = this.parameters;
  6602. for (const key in parameters) {
  6603. if (parameters[key] !== undefined) data[key] = parameters[key];
  6604. }
  6605. return data;
  6606. } // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6607. data.data = {
  6608. attributes: {}
  6609. };
  6610. const index = this.index;
  6611. if (index !== null) {
  6612. data.data.index = {
  6613. type: index.array.constructor.name,
  6614. array: Array.prototype.slice.call(index.array)
  6615. };
  6616. }
  6617. const attributes = this.attributes;
  6618. for (const key in attributes) {
  6619. const attribute = attributes[key];
  6620. data.data.attributes[key] = attribute.toJSON(data.data);
  6621. }
  6622. const morphAttributes = {};
  6623. let hasMorphAttributes = false;
  6624. for (const key in this.morphAttributes) {
  6625. const attributeArray = this.morphAttributes[key];
  6626. const array = [];
  6627. for (let i = 0, il = attributeArray.length; i < il; i++) {
  6628. const attribute = attributeArray[i];
  6629. array.push(attribute.toJSON(data.data));
  6630. }
  6631. if (array.length > 0) {
  6632. morphAttributes[key] = array;
  6633. hasMorphAttributes = true;
  6634. }
  6635. }
  6636. if (hasMorphAttributes) {
  6637. data.data.morphAttributes = morphAttributes;
  6638. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6639. }
  6640. const groups = this.groups;
  6641. if (groups.length > 0) {
  6642. data.data.groups = JSON.parse(JSON.stringify(groups));
  6643. }
  6644. const boundingSphere = this.boundingSphere;
  6645. if (boundingSphere !== null) {
  6646. data.data.boundingSphere = {
  6647. center: boundingSphere.center.toArray(),
  6648. radius: boundingSphere.radius
  6649. };
  6650. }
  6651. return data;
  6652. }
  6653. clone() {
  6654. /*
  6655. // Handle primitives
  6656. const parameters = this.parameters;
  6657. if ( parameters !== undefined ) {
  6658. const values = [];
  6659. for ( const key in parameters ) {
  6660. values.push( parameters[ key ] );
  6661. }
  6662. const geometry = Object.create( this.constructor.prototype );
  6663. this.constructor.apply( geometry, values );
  6664. return geometry;
  6665. }
  6666. return new this.constructor().copy( this );
  6667. */
  6668. return new BufferGeometry().copy(this);
  6669. }
  6670. copy(source) {
  6671. // reset
  6672. this.index = null;
  6673. this.attributes = {};
  6674. this.morphAttributes = {};
  6675. this.groups = [];
  6676. this.boundingBox = null;
  6677. this.boundingSphere = null; // used for storing cloned, shared data
  6678. const data = {}; // name
  6679. this.name = source.name; // index
  6680. const index = source.index;
  6681. if (index !== null) {
  6682. this.setIndex(index.clone(data));
  6683. } // attributes
  6684. const attributes = source.attributes;
  6685. for (const name in attributes) {
  6686. const attribute = attributes[name];
  6687. this.setAttribute(name, attribute.clone(data));
  6688. } // morph attributes
  6689. const morphAttributes = source.morphAttributes;
  6690. for (const name in morphAttributes) {
  6691. const array = [];
  6692. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6693. for (let i = 0, l = morphAttribute.length; i < l; i++) {
  6694. array.push(morphAttribute[i].clone(data));
  6695. }
  6696. this.morphAttributes[name] = array;
  6697. }
  6698. this.morphTargetsRelative = source.morphTargetsRelative; // groups
  6699. const groups = source.groups;
  6700. for (let i = 0, l = groups.length; i < l; i++) {
  6701. const group = groups[i];
  6702. this.addGroup(group.start, group.count, group.materialIndex);
  6703. } // bounding box
  6704. const boundingBox = source.boundingBox;
  6705. if (boundingBox !== null) {
  6706. this.boundingBox = boundingBox.clone();
  6707. } // bounding sphere
  6708. const boundingSphere = source.boundingSphere;
  6709. if (boundingSphere !== null) {
  6710. this.boundingSphere = boundingSphere.clone();
  6711. } // draw range
  6712. this.drawRange.start = source.drawRange.start;
  6713. this.drawRange.count = source.drawRange.count; // user data
  6714. this.userData = source.userData;
  6715. return this;
  6716. }
  6717. dispose() {
  6718. this.dispatchEvent({
  6719. type: 'dispose'
  6720. });
  6721. }
  6722. }
  6723. BufferGeometry.prototype.isBufferGeometry = true;
  6724. const _inverseMatrix$2 = /*@__PURE__*/new Matrix4();
  6725. const _ray$2 = /*@__PURE__*/new Ray();
  6726. const _sphere$3 = /*@__PURE__*/new Sphere();
  6727. const _vA$1 = /*@__PURE__*/new Vector3();
  6728. const _vB$1 = /*@__PURE__*/new Vector3();
  6729. const _vC$1 = /*@__PURE__*/new Vector3();
  6730. const _tempA = /*@__PURE__*/new Vector3();
  6731. const _tempB = /*@__PURE__*/new Vector3();
  6732. const _tempC = /*@__PURE__*/new Vector3();
  6733. const _morphA = /*@__PURE__*/new Vector3();
  6734. const _morphB = /*@__PURE__*/new Vector3();
  6735. const _morphC = /*@__PURE__*/new Vector3();
  6736. const _uvA$1 = /*@__PURE__*/new Vector2();
  6737. const _uvB$1 = /*@__PURE__*/new Vector2();
  6738. const _uvC$1 = /*@__PURE__*/new Vector2();
  6739. const _intersectionPoint = /*@__PURE__*/new Vector3();
  6740. const _intersectionPointWorld = /*@__PURE__*/new Vector3();
  6741. class Mesh extends Object3D {
  6742. constructor(geometry = new BufferGeometry(), material = new MeshBasicMaterial()) {
  6743. super();
  6744. this.type = 'Mesh';
  6745. this.geometry = geometry;
  6746. this.material = material;
  6747. this.updateMorphTargets();
  6748. }
  6749. copy(source) {
  6750. super.copy(source);
  6751. if (source.morphTargetInfluences !== undefined) {
  6752. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6753. }
  6754. if (source.morphTargetDictionary !== undefined) {
  6755. this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
  6756. }
  6757. this.material = source.material;
  6758. this.geometry = source.geometry;
  6759. return this;
  6760. }
  6761. updateMorphTargets() {
  6762. const geometry = this.geometry;
  6763. if (geometry.isBufferGeometry) {
  6764. const morphAttributes = geometry.morphAttributes;
  6765. const keys = Object.keys(morphAttributes);
  6766. if (keys.length > 0) {
  6767. const morphAttribute = morphAttributes[keys[0]];
  6768. if (morphAttribute !== undefined) {
  6769. this.morphTargetInfluences = [];
  6770. this.morphTargetDictionary = {};
  6771. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  6772. const name = morphAttribute[m].name || String(m);
  6773. this.morphTargetInfluences.push(0);
  6774. this.morphTargetDictionary[name] = m;
  6775. }
  6776. }
  6777. }
  6778. } else {
  6779. const morphTargets = geometry.morphTargets;
  6780. if (morphTargets !== undefined && morphTargets.length > 0) {
  6781. console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  6782. }
  6783. }
  6784. }
  6785. raycast(raycaster, intersects) {
  6786. const geometry = this.geometry;
  6787. const material = this.material;
  6788. const matrixWorld = this.matrixWorld;
  6789. if (material === undefined) return; // Checking boundingSphere distance to ray
  6790. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  6791. _sphere$3.copy(geometry.boundingSphere);
  6792. _sphere$3.applyMatrix4(matrixWorld);
  6793. if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; //
  6794. _inverseMatrix$2.copy(matrixWorld).invert();
  6795. _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2); // Check boundingBox before continuing
  6796. if (geometry.boundingBox !== null) {
  6797. if (_ray$2.intersectsBox(geometry.boundingBox) === false) return;
  6798. }
  6799. let intersection;
  6800. if (geometry.isBufferGeometry) {
  6801. const index = geometry.index;
  6802. const position = geometry.attributes.position;
  6803. const morphPosition = geometry.morphAttributes.position;
  6804. const morphTargetsRelative = geometry.morphTargetsRelative;
  6805. const uv = geometry.attributes.uv;
  6806. const uv2 = geometry.attributes.uv2;
  6807. const groups = geometry.groups;
  6808. const drawRange = geometry.drawRange;
  6809. if (index !== null) {
  6810. // indexed buffer geometry
  6811. if (Array.isArray(material)) {
  6812. for (let i = 0, il = groups.length; i < il; i++) {
  6813. const group = groups[i];
  6814. const groupMaterial = material[group.materialIndex];
  6815. const start = Math.max(group.start, drawRange.start);
  6816. const end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  6817. for (let j = start, jl = end; j < jl; j += 3) {
  6818. const a = index.getX(j);
  6819. const b = index.getX(j + 1);
  6820. const c = index.getX(j + 2);
  6821. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6822. if (intersection) {
  6823. intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
  6824. intersection.face.materialIndex = group.materialIndex;
  6825. intersects.push(intersection);
  6826. }
  6827. }
  6828. }
  6829. } else {
  6830. const start = Math.max(0, drawRange.start);
  6831. const end = Math.min(index.count, drawRange.start + drawRange.count);
  6832. for (let i = start, il = end; i < il; i += 3) {
  6833. const a = index.getX(i);
  6834. const b = index.getX(i + 1);
  6835. const c = index.getX(i + 2);
  6836. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6837. if (intersection) {
  6838. intersection.faceIndex = Math.floor(i / 3); // triangle number in indexed buffer semantics
  6839. intersects.push(intersection);
  6840. }
  6841. }
  6842. }
  6843. } else if (position !== undefined) {
  6844. // non-indexed buffer geometry
  6845. if (Array.isArray(material)) {
  6846. for (let i = 0, il = groups.length; i < il; i++) {
  6847. const group = groups[i];
  6848. const groupMaterial = material[group.materialIndex];
  6849. const start = Math.max(group.start, drawRange.start);
  6850. const end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  6851. for (let j = start, jl = end; j < jl; j += 3) {
  6852. const a = j;
  6853. const b = j + 1;
  6854. const c = j + 2;
  6855. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6856. if (intersection) {
  6857. intersection.faceIndex = Math.floor(j / 3); // triangle number in non-indexed buffer semantics
  6858. intersection.face.materialIndex = group.materialIndex;
  6859. intersects.push(intersection);
  6860. }
  6861. }
  6862. }
  6863. } else {
  6864. const start = Math.max(0, drawRange.start);
  6865. const end = Math.min(position.count, drawRange.start + drawRange.count);
  6866. for (let i = start, il = end; i < il; i += 3) {
  6867. const a = i;
  6868. const b = i + 1;
  6869. const c = i + 2;
  6870. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6871. if (intersection) {
  6872. intersection.faceIndex = Math.floor(i / 3); // triangle number in non-indexed buffer semantics
  6873. intersects.push(intersection);
  6874. }
  6875. }
  6876. }
  6877. }
  6878. } else if (geometry.isGeometry) {
  6879. console.error('THREE.Mesh.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  6880. }
  6881. }
  6882. }
  6883. Mesh.prototype.isMesh = true;
  6884. function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
  6885. let intersect;
  6886. if (material.side === BackSide) {
  6887. intersect = ray.intersectTriangle(pC, pB, pA, true, point);
  6888. } else {
  6889. intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
  6890. }
  6891. if (intersect === null) return null;
  6892. _intersectionPointWorld.copy(point);
  6893. _intersectionPointWorld.applyMatrix4(object.matrixWorld);
  6894. const distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
  6895. if (distance < raycaster.near || distance > raycaster.far) return null;
  6896. return {
  6897. distance: distance,
  6898. point: _intersectionPointWorld.clone(),
  6899. object: object
  6900. };
  6901. }
  6902. function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c) {
  6903. _vA$1.fromBufferAttribute(position, a);
  6904. _vB$1.fromBufferAttribute(position, b);
  6905. _vC$1.fromBufferAttribute(position, c);
  6906. const morphInfluences = object.morphTargetInfluences;
  6907. if (material.morphTargets && morphPosition && morphInfluences) {
  6908. _morphA.set(0, 0, 0);
  6909. _morphB.set(0, 0, 0);
  6910. _morphC.set(0, 0, 0);
  6911. for (let i = 0, il = morphPosition.length; i < il; i++) {
  6912. const influence = morphInfluences[i];
  6913. const morphAttribute = morphPosition[i];
  6914. if (influence === 0) continue;
  6915. _tempA.fromBufferAttribute(morphAttribute, a);
  6916. _tempB.fromBufferAttribute(morphAttribute, b);
  6917. _tempC.fromBufferAttribute(morphAttribute, c);
  6918. if (morphTargetsRelative) {
  6919. _morphA.addScaledVector(_tempA, influence);
  6920. _morphB.addScaledVector(_tempB, influence);
  6921. _morphC.addScaledVector(_tempC, influence);
  6922. } else {
  6923. _morphA.addScaledVector(_tempA.sub(_vA$1), influence);
  6924. _morphB.addScaledVector(_tempB.sub(_vB$1), influence);
  6925. _morphC.addScaledVector(_tempC.sub(_vC$1), influence);
  6926. }
  6927. }
  6928. _vA$1.add(_morphA);
  6929. _vB$1.add(_morphB);
  6930. _vC$1.add(_morphC);
  6931. }
  6932. if (object.isSkinnedMesh) {
  6933. object.boneTransform(a, _vA$1);
  6934. object.boneTransform(b, _vB$1);
  6935. object.boneTransform(c, _vC$1);
  6936. }
  6937. const intersection = checkIntersection(object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint);
  6938. if (intersection) {
  6939. if (uv) {
  6940. _uvA$1.fromBufferAttribute(uv, a);
  6941. _uvB$1.fromBufferAttribute(uv, b);
  6942. _uvC$1.fromBufferAttribute(uv, c);
  6943. intersection.uv = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  6944. }
  6945. if (uv2) {
  6946. _uvA$1.fromBufferAttribute(uv2, a);
  6947. _uvB$1.fromBufferAttribute(uv2, b);
  6948. _uvC$1.fromBufferAttribute(uv2, c);
  6949. intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  6950. }
  6951. const face = {
  6952. a: a,
  6953. b: b,
  6954. c: c,
  6955. normal: new Vector3(),
  6956. materialIndex: 0
  6957. };
  6958. Triangle.getNormal(_vA$1, _vB$1, _vC$1, face.normal);
  6959. intersection.face = face;
  6960. }
  6961. return intersection;
  6962. }
  6963. class BoxGeometry extends BufferGeometry {
  6964. constructor(width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) {
  6965. super();
  6966. this.type = 'BoxGeometry';
  6967. this.parameters = {
  6968. width: width,
  6969. height: height,
  6970. depth: depth,
  6971. widthSegments: widthSegments,
  6972. heightSegments: heightSegments,
  6973. depthSegments: depthSegments
  6974. };
  6975. const scope = this; // segments
  6976. widthSegments = Math.floor(widthSegments);
  6977. heightSegments = Math.floor(heightSegments);
  6978. depthSegments = Math.floor(depthSegments); // buffers
  6979. const indices = [];
  6980. const vertices = [];
  6981. const normals = [];
  6982. const uvs = []; // helper variables
  6983. let numberOfVertices = 0;
  6984. let groupStart = 0; // build each side of the box geometry
  6985. buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
  6986. buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
  6987. buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
  6988. buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
  6989. buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
  6990. buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
  6991. // build geometry
  6992. this.setIndex(indices);
  6993. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  6994. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  6995. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  6996. function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {
  6997. const segmentWidth = width / gridX;
  6998. const segmentHeight = height / gridY;
  6999. const widthHalf = width / 2;
  7000. const heightHalf = height / 2;
  7001. const depthHalf = depth / 2;
  7002. const gridX1 = gridX + 1;
  7003. const gridY1 = gridY + 1;
  7004. let vertexCounter = 0;
  7005. let groupCount = 0;
  7006. const vector = new Vector3(); // generate vertices, normals and uvs
  7007. for (let iy = 0; iy < gridY1; iy++) {
  7008. const y = iy * segmentHeight - heightHalf;
  7009. for (let ix = 0; ix < gridX1; ix++) {
  7010. const x = ix * segmentWidth - widthHalf; // set values to correct vector component
  7011. vector[u] = x * udir;
  7012. vector[v] = y * vdir;
  7013. vector[w] = depthHalf; // now apply vector to vertex buffer
  7014. vertices.push(vector.x, vector.y, vector.z); // set values to correct vector component
  7015. vector[u] = 0;
  7016. vector[v] = 0;
  7017. vector[w] = depth > 0 ? 1 : -1; // now apply vector to normal buffer
  7018. normals.push(vector.x, vector.y, vector.z); // uvs
  7019. uvs.push(ix / gridX);
  7020. uvs.push(1 - iy / gridY); // counters
  7021. vertexCounter += 1;
  7022. }
  7023. } // indices
  7024. // 1. you need three indices to draw a single face
  7025. // 2. a single segment consists of two faces
  7026. // 3. so we need to generate six (2*3) indices per segment
  7027. for (let iy = 0; iy < gridY; iy++) {
  7028. for (let ix = 0; ix < gridX; ix++) {
  7029. const a = numberOfVertices + ix + gridX1 * iy;
  7030. const b = numberOfVertices + ix + gridX1 * (iy + 1);
  7031. const c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);
  7032. const d = numberOfVertices + (ix + 1) + gridX1 * iy; // faces
  7033. indices.push(a, b, d);
  7034. indices.push(b, c, d); // increase counter
  7035. groupCount += 6;
  7036. }
  7037. } // add a group to the geometry. this will ensure multi material support
  7038. scope.addGroup(groupStart, groupCount, materialIndex); // calculate new start value for groups
  7039. groupStart += groupCount; // update total number of vertices
  7040. numberOfVertices += vertexCounter;
  7041. }
  7042. }
  7043. }
  7044. /**
  7045. * Uniform Utilities
  7046. */
  7047. function cloneUniforms(src) {
  7048. const dst = {};
  7049. for (const u in src) {
  7050. dst[u] = {};
  7051. for (const p in src[u]) {
  7052. const property = src[u][p];
  7053. if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture || property.isQuaternion)) {
  7054. dst[u][p] = property.clone();
  7055. } else if (Array.isArray(property)) {
  7056. dst[u][p] = property.slice();
  7057. } else {
  7058. dst[u][p] = property;
  7059. }
  7060. }
  7061. }
  7062. return dst;
  7063. }
  7064. function mergeUniforms(uniforms) {
  7065. const merged = {};
  7066. for (let u = 0; u < uniforms.length; u++) {
  7067. const tmp = cloneUniforms(uniforms[u]);
  7068. for (const p in tmp) {
  7069. merged[p] = tmp[p];
  7070. }
  7071. }
  7072. return merged;
  7073. } // Legacy
  7074. const UniformsUtils = {
  7075. clone: cloneUniforms,
  7076. merge: mergeUniforms
  7077. };
  7078. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  7079. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  7080. /**
  7081. * parameters = {
  7082. * defines: { "label" : "value" },
  7083. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  7084. *
  7085. * fragmentShader: <string>,
  7086. * vertexShader: <string>,
  7087. *
  7088. * wireframe: <boolean>,
  7089. * wireframeLinewidth: <float>,
  7090. *
  7091. * lights: <bool>,
  7092. *
  7093. * morphTargets: <bool>,
  7094. * morphNormals: <bool>
  7095. * }
  7096. */
  7097. class ShaderMaterial extends Material {
  7098. constructor(parameters) {
  7099. super();
  7100. this.type = 'ShaderMaterial';
  7101. this.defines = {};
  7102. this.uniforms = {};
  7103. this.vertexShader = default_vertex;
  7104. this.fragmentShader = default_fragment;
  7105. this.linewidth = 1;
  7106. this.wireframe = false;
  7107. this.wireframeLinewidth = 1;
  7108. this.fog = false; // set to use scene fog
  7109. this.lights = false; // set to use scene lights
  7110. this.clipping = false; // set to use user-defined clipping planes
  7111. this.morphTargets = false; // set to use morph targets
  7112. this.morphNormals = false; // set to use morph normals
  7113. this.extensions = {
  7114. derivatives: false,
  7115. // set to use derivatives
  7116. fragDepth: false,
  7117. // set to use fragment depth values
  7118. drawBuffers: false,
  7119. // set to use draw buffers
  7120. shaderTextureLOD: false // set to use shader texture LOD
  7121. }; // When rendered geometry doesn't include these attributes but the material does,
  7122. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7123. this.defaultAttributeValues = {
  7124. 'color': [1, 1, 1],
  7125. 'uv': [0, 0],
  7126. 'uv2': [0, 0]
  7127. };
  7128. this.index0AttributeName = undefined;
  7129. this.uniformsNeedUpdate = false;
  7130. this.glslVersion = null;
  7131. if (parameters !== undefined) {
  7132. if (parameters.attributes !== undefined) {
  7133. console.error('THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.');
  7134. }
  7135. this.setValues(parameters);
  7136. }
  7137. }
  7138. copy(source) {
  7139. super.copy(source);
  7140. this.fragmentShader = source.fragmentShader;
  7141. this.vertexShader = source.vertexShader;
  7142. this.uniforms = cloneUniforms(source.uniforms);
  7143. this.defines = Object.assign({}, source.defines);
  7144. this.wireframe = source.wireframe;
  7145. this.wireframeLinewidth = source.wireframeLinewidth;
  7146. this.lights = source.lights;
  7147. this.clipping = source.clipping;
  7148. this.morphTargets = source.morphTargets;
  7149. this.morphNormals = source.morphNormals;
  7150. this.extensions = Object.assign({}, source.extensions);
  7151. this.glslVersion = source.glslVersion;
  7152. return this;
  7153. }
  7154. toJSON(meta) {
  7155. const data = super.toJSON(meta);
  7156. data.glslVersion = this.glslVersion;
  7157. data.uniforms = {};
  7158. for (const name in this.uniforms) {
  7159. const uniform = this.uniforms[name];
  7160. const value = uniform.value;
  7161. if (value && value.isTexture) {
  7162. data.uniforms[name] = {
  7163. type: 't',
  7164. value: value.toJSON(meta).uuid
  7165. };
  7166. } else if (value && value.isColor) {
  7167. data.uniforms[name] = {
  7168. type: 'c',
  7169. value: value.getHex()
  7170. };
  7171. } else if (value && value.isVector2) {
  7172. data.uniforms[name] = {
  7173. type: 'v2',
  7174. value: value.toArray()
  7175. };
  7176. } else if (value && value.isVector3) {
  7177. data.uniforms[name] = {
  7178. type: 'v3',
  7179. value: value.toArray()
  7180. };
  7181. } else if (value && value.isVector4) {
  7182. data.uniforms[name] = {
  7183. type: 'v4',
  7184. value: value.toArray()
  7185. };
  7186. } else if (value && value.isMatrix3) {
  7187. data.uniforms[name] = {
  7188. type: 'm3',
  7189. value: value.toArray()
  7190. };
  7191. } else if (value && value.isMatrix4) {
  7192. data.uniforms[name] = {
  7193. type: 'm4',
  7194. value: value.toArray()
  7195. };
  7196. } else {
  7197. data.uniforms[name] = {
  7198. value: value
  7199. }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7200. }
  7201. }
  7202. if (Object.keys(this.defines).length > 0) data.defines = this.defines;
  7203. data.vertexShader = this.vertexShader;
  7204. data.fragmentShader = this.fragmentShader;
  7205. const extensions = {};
  7206. for (const key in this.extensions) {
  7207. if (this.extensions[key] === true) extensions[key] = true;
  7208. }
  7209. if (Object.keys(extensions).length > 0) data.extensions = extensions;
  7210. return data;
  7211. }
  7212. }
  7213. ShaderMaterial.prototype.isShaderMaterial = true;
  7214. class Camera extends Object3D {
  7215. constructor() {
  7216. super();
  7217. this.type = 'Camera';
  7218. this.matrixWorldInverse = new Matrix4();
  7219. this.projectionMatrix = new Matrix4();
  7220. this.projectionMatrixInverse = new Matrix4();
  7221. }
  7222. copy(source, recursive) {
  7223. super.copy(source, recursive);
  7224. this.matrixWorldInverse.copy(source.matrixWorldInverse);
  7225. this.projectionMatrix.copy(source.projectionMatrix);
  7226. this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
  7227. return this;
  7228. }
  7229. getWorldDirection(target) {
  7230. if (target === undefined) {
  7231. console.warn('THREE.Camera: .getWorldDirection() target is now required');
  7232. target = new Vector3();
  7233. }
  7234. this.updateWorldMatrix(true, false);
  7235. const e = this.matrixWorld.elements;
  7236. return target.set(-e[8], -e[9], -e[10]).normalize();
  7237. }
  7238. updateMatrixWorld(force) {
  7239. super.updateMatrixWorld(force);
  7240. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7241. }
  7242. updateWorldMatrix(updateParents, updateChildren) {
  7243. super.updateWorldMatrix(updateParents, updateChildren);
  7244. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7245. }
  7246. clone() {
  7247. return new this.constructor().copy(this);
  7248. }
  7249. }
  7250. Camera.prototype.isCamera = true;
  7251. class PerspectiveCamera extends Camera {
  7252. constructor(fov = 50, aspect = 1, near = 0.1, far = 2000) {
  7253. super();
  7254. this.type = 'PerspectiveCamera';
  7255. this.fov = fov;
  7256. this.zoom = 1;
  7257. this.near = near;
  7258. this.far = far;
  7259. this.focus = 10;
  7260. this.aspect = aspect;
  7261. this.view = null;
  7262. this.filmGauge = 35; // width of the film (default in millimeters)
  7263. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7264. this.updateProjectionMatrix();
  7265. }
  7266. copy(source, recursive) {
  7267. super.copy(source, recursive);
  7268. this.fov = source.fov;
  7269. this.zoom = source.zoom;
  7270. this.near = source.near;
  7271. this.far = source.far;
  7272. this.focus = source.focus;
  7273. this.aspect = source.aspect;
  7274. this.view = source.view === null ? null : Object.assign({}, source.view);
  7275. this.filmGauge = source.filmGauge;
  7276. this.filmOffset = source.filmOffset;
  7277. return this;
  7278. }
  7279. /**
  7280. * Sets the FOV by focal length in respect to the current .filmGauge.
  7281. *
  7282. * The default film gauge is 35, so that the focal length can be specified for
  7283. * a 35mm (full frame) camera.
  7284. *
  7285. * Values for focal length and film gauge must have the same unit.
  7286. */
  7287. setFocalLength(focalLength) {
  7288. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7289. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7290. this.fov = RAD2DEG * 2 * Math.atan(vExtentSlope);
  7291. this.updateProjectionMatrix();
  7292. }
  7293. /**
  7294. * Calculates the focal length from the current .fov and .filmGauge.
  7295. */
  7296. getFocalLength() {
  7297. const vExtentSlope = Math.tan(DEG2RAD * 0.5 * this.fov);
  7298. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7299. }
  7300. getEffectiveFOV() {
  7301. return RAD2DEG * 2 * Math.atan(Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom);
  7302. }
  7303. getFilmWidth() {
  7304. // film not completely covered in portrait format (aspect < 1)
  7305. return this.filmGauge * Math.min(this.aspect, 1);
  7306. }
  7307. getFilmHeight() {
  7308. // film not completely covered in landscape format (aspect > 1)
  7309. return this.filmGauge / Math.max(this.aspect, 1);
  7310. }
  7311. /**
  7312. * Sets an offset in a larger frustum. This is useful for multi-window or
  7313. * multi-monitor/multi-machine setups.
  7314. *
  7315. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7316. * the monitors are in grid like this
  7317. *
  7318. * +---+---+---+
  7319. * | A | B | C |
  7320. * +---+---+---+
  7321. * | D | E | F |
  7322. * +---+---+---+
  7323. *
  7324. * then for each monitor you would call it like this
  7325. *
  7326. * const w = 1920;
  7327. * const h = 1080;
  7328. * const fullWidth = w * 3;
  7329. * const fullHeight = h * 2;
  7330. *
  7331. * --A--
  7332. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7333. * --B--
  7334. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7335. * --C--
  7336. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7337. * --D--
  7338. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7339. * --E--
  7340. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7341. * --F--
  7342. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7343. *
  7344. * Note there is no reason monitors have to be the same size or in a grid.
  7345. */
  7346. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  7347. this.aspect = fullWidth / fullHeight;
  7348. if (this.view === null) {
  7349. this.view = {
  7350. enabled: true,
  7351. fullWidth: 1,
  7352. fullHeight: 1,
  7353. offsetX: 0,
  7354. offsetY: 0,
  7355. width: 1,
  7356. height: 1
  7357. };
  7358. }
  7359. this.view.enabled = true;
  7360. this.view.fullWidth = fullWidth;
  7361. this.view.fullHeight = fullHeight;
  7362. this.view.offsetX = x;
  7363. this.view.offsetY = y;
  7364. this.view.width = width;
  7365. this.view.height = height;
  7366. this.updateProjectionMatrix();
  7367. }
  7368. clearViewOffset() {
  7369. if (this.view !== null) {
  7370. this.view.enabled = false;
  7371. }
  7372. this.updateProjectionMatrix();
  7373. }
  7374. updateProjectionMatrix() {
  7375. const near = this.near;
  7376. let top = near * Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom;
  7377. let height = 2 * top;
  7378. let width = this.aspect * height;
  7379. let left = -0.5 * width;
  7380. const view = this.view;
  7381. if (this.view !== null && this.view.enabled) {
  7382. const fullWidth = view.fullWidth,
  7383. fullHeight = view.fullHeight;
  7384. left += view.offsetX * width / fullWidth;
  7385. top -= view.offsetY * height / fullHeight;
  7386. width *= view.width / fullWidth;
  7387. height *= view.height / fullHeight;
  7388. }
  7389. const skew = this.filmOffset;
  7390. if (skew !== 0) left += near * skew / this.getFilmWidth();
  7391. this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);
  7392. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  7393. }
  7394. toJSON(meta) {
  7395. const data = super.toJSON(meta);
  7396. data.object.fov = this.fov;
  7397. data.object.zoom = this.zoom;
  7398. data.object.near = this.near;
  7399. data.object.far = this.far;
  7400. data.object.focus = this.focus;
  7401. data.object.aspect = this.aspect;
  7402. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  7403. data.object.filmGauge = this.filmGauge;
  7404. data.object.filmOffset = this.filmOffset;
  7405. return data;
  7406. }
  7407. }
  7408. PerspectiveCamera.prototype.isPerspectiveCamera = true;
  7409. const fov = 90,
  7410. aspect = 1;
  7411. class CubeCamera extends Object3D {
  7412. constructor(near, far, renderTarget) {
  7413. super();
  7414. this.type = 'CubeCamera';
  7415. if (renderTarget.isWebGLCubeRenderTarget !== true) {
  7416. console.error('THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.');
  7417. return;
  7418. }
  7419. this.renderTarget = renderTarget;
  7420. const cameraPX = new PerspectiveCamera(fov, aspect, near, far);
  7421. cameraPX.layers = this.layers;
  7422. cameraPX.up.set(0, -1, 0);
  7423. cameraPX.lookAt(new Vector3(1, 0, 0));
  7424. this.add(cameraPX);
  7425. const cameraNX = new PerspectiveCamera(fov, aspect, near, far);
  7426. cameraNX.layers = this.layers;
  7427. cameraNX.up.set(0, -1, 0);
  7428. cameraNX.lookAt(new Vector3(-1, 0, 0));
  7429. this.add(cameraNX);
  7430. const cameraPY = new PerspectiveCamera(fov, aspect, near, far);
  7431. cameraPY.layers = this.layers;
  7432. cameraPY.up.set(0, 0, 1);
  7433. cameraPY.lookAt(new Vector3(0, 1, 0));
  7434. this.add(cameraPY);
  7435. const cameraNY = new PerspectiveCamera(fov, aspect, near, far);
  7436. cameraNY.layers = this.layers;
  7437. cameraNY.up.set(0, 0, -1);
  7438. cameraNY.lookAt(new Vector3(0, -1, 0));
  7439. this.add(cameraNY);
  7440. const cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
  7441. cameraPZ.layers = this.layers;
  7442. cameraPZ.up.set(0, -1, 0);
  7443. cameraPZ.lookAt(new Vector3(0, 0, 1));
  7444. this.add(cameraPZ);
  7445. const cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
  7446. cameraNZ.layers = this.layers;
  7447. cameraNZ.up.set(0, -1, 0);
  7448. cameraNZ.lookAt(new Vector3(0, 0, -1));
  7449. this.add(cameraNZ);
  7450. }
  7451. update(renderer, scene) {
  7452. if (this.parent === null) this.updateMatrixWorld();
  7453. const renderTarget = this.renderTarget;
  7454. const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = this.children;
  7455. const currentXrEnabled = renderer.xr.enabled;
  7456. const currentRenderTarget = renderer.getRenderTarget();
  7457. renderer.xr.enabled = false;
  7458. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7459. renderTarget.texture.generateMipmaps = false;
  7460. renderer.setRenderTarget(renderTarget, 0);
  7461. renderer.render(scene, cameraPX);
  7462. renderer.setRenderTarget(renderTarget, 1);
  7463. renderer.render(scene, cameraNX);
  7464. renderer.setRenderTarget(renderTarget, 2);
  7465. renderer.render(scene, cameraPY);
  7466. renderer.setRenderTarget(renderTarget, 3);
  7467. renderer.render(scene, cameraNY);
  7468. renderer.setRenderTarget(renderTarget, 4);
  7469. renderer.render(scene, cameraPZ);
  7470. renderTarget.texture.generateMipmaps = generateMipmaps;
  7471. renderer.setRenderTarget(renderTarget, 5);
  7472. renderer.render(scene, cameraNZ);
  7473. renderer.setRenderTarget(currentRenderTarget);
  7474. renderer.xr.enabled = currentXrEnabled;
  7475. }
  7476. }
  7477. class CubeTexture extends Texture {
  7478. constructor(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  7479. images = images !== undefined ? images : [];
  7480. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7481. format = format !== undefined ? format : RGBFormat;
  7482. super(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding); // Why CubeTexture._needsFlipEnvMap is necessary:
  7483. //
  7484. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7485. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7486. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7487. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7488. // and the flag _needsFlipEnvMap controls this conversion. The flip is not required (and thus _needsFlipEnvMap is set to false)
  7489. // when using WebGLCubeRenderTarget.texture as a cube texture.
  7490. this._needsFlipEnvMap = true;
  7491. this.flipY = false;
  7492. }
  7493. get images() {
  7494. return this.image;
  7495. }
  7496. set images(value) {
  7497. this.image = value;
  7498. }
  7499. }
  7500. CubeTexture.prototype.isCubeTexture = true;
  7501. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7502. constructor(size, options, dummy) {
  7503. if (Number.isInteger(options)) {
  7504. console.warn('THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )');
  7505. options = dummy;
  7506. }
  7507. super(size, size, options);
  7508. options = options || {};
  7509. this.texture = new CubeTexture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  7510. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7511. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7512. this.texture._needsFlipEnvMap = false;
  7513. }
  7514. fromEquirectangularTexture(renderer, texture) {
  7515. this.texture.type = texture.type;
  7516. this.texture.format = RGBAFormat; // see #18859
  7517. this.texture.encoding = texture.encoding;
  7518. this.texture.generateMipmaps = texture.generateMipmaps;
  7519. this.texture.minFilter = texture.minFilter;
  7520. this.texture.magFilter = texture.magFilter;
  7521. const shader = {
  7522. uniforms: {
  7523. tEquirect: {
  7524. value: null
  7525. }
  7526. },
  7527. vertexShader:
  7528. /* glsl */
  7529. `
  7530. varying vec3 vWorldDirection;
  7531. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7532. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7533. }
  7534. void main() {
  7535. vWorldDirection = transformDirection( position, modelMatrix );
  7536. #include <begin_vertex>
  7537. #include <project_vertex>
  7538. }
  7539. `,
  7540. fragmentShader:
  7541. /* glsl */
  7542. `
  7543. uniform sampler2D tEquirect;
  7544. varying vec3 vWorldDirection;
  7545. #include <common>
  7546. void main() {
  7547. vec3 direction = normalize( vWorldDirection );
  7548. vec2 sampleUV = equirectUv( direction );
  7549. gl_FragColor = texture2D( tEquirect, sampleUV );
  7550. }
  7551. `
  7552. };
  7553. const geometry = new BoxGeometry(5, 5, 5);
  7554. const material = new ShaderMaterial({
  7555. name: 'CubemapFromEquirect',
  7556. uniforms: cloneUniforms(shader.uniforms),
  7557. vertexShader: shader.vertexShader,
  7558. fragmentShader: shader.fragmentShader,
  7559. side: BackSide,
  7560. blending: NoBlending
  7561. });
  7562. material.uniforms.tEquirect.value = texture;
  7563. const mesh = new Mesh(geometry, material);
  7564. const currentMinFilter = texture.minFilter; // Avoid blurred poles
  7565. if (texture.minFilter === LinearMipmapLinearFilter) texture.minFilter = LinearFilter;
  7566. const camera = new CubeCamera(1, 10, this);
  7567. camera.update(renderer, mesh);
  7568. texture.minFilter = currentMinFilter;
  7569. mesh.geometry.dispose();
  7570. mesh.material.dispose();
  7571. return this;
  7572. }
  7573. clear(renderer, color, depth, stencil) {
  7574. const currentRenderTarget = renderer.getRenderTarget();
  7575. for (let i = 0; i < 6; i++) {
  7576. renderer.setRenderTarget(this, i);
  7577. renderer.clear(color, depth, stencil);
  7578. }
  7579. renderer.setRenderTarget(currentRenderTarget);
  7580. }
  7581. }
  7582. WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
  7583. class DataTexture extends Texture {
  7584. constructor(data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  7585. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  7586. this.image = {
  7587. data: data || null,
  7588. width: width || 1,
  7589. height: height || 1
  7590. };
  7591. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  7592. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  7593. this.generateMipmaps = false;
  7594. this.flipY = false;
  7595. this.unpackAlignment = 1;
  7596. this.needsUpdate = true;
  7597. }
  7598. }
  7599. DataTexture.prototype.isDataTexture = true;
  7600. const _sphere$2 = /*@__PURE__*/new Sphere();
  7601. const _vector$7 = /*@__PURE__*/new Vector3();
  7602. class Frustum {
  7603. constructor(p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane()) {
  7604. this.planes = [p0, p1, p2, p3, p4, p5];
  7605. }
  7606. set(p0, p1, p2, p3, p4, p5) {
  7607. const planes = this.planes;
  7608. planes[0].copy(p0);
  7609. planes[1].copy(p1);
  7610. planes[2].copy(p2);
  7611. planes[3].copy(p3);
  7612. planes[4].copy(p4);
  7613. planes[5].copy(p5);
  7614. return this;
  7615. }
  7616. copy(frustum) {
  7617. const planes = this.planes;
  7618. for (let i = 0; i < 6; i++) {
  7619. planes[i].copy(frustum.planes[i]);
  7620. }
  7621. return this;
  7622. }
  7623. setFromProjectionMatrix(m) {
  7624. const planes = this.planes;
  7625. const me = m.elements;
  7626. const me0 = me[0],
  7627. me1 = me[1],
  7628. me2 = me[2],
  7629. me3 = me[3];
  7630. const me4 = me[4],
  7631. me5 = me[5],
  7632. me6 = me[6],
  7633. me7 = me[7];
  7634. const me8 = me[8],
  7635. me9 = me[9],
  7636. me10 = me[10],
  7637. me11 = me[11];
  7638. const me12 = me[12],
  7639. me13 = me[13],
  7640. me14 = me[14],
  7641. me15 = me[15];
  7642. planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
  7643. planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
  7644. planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
  7645. planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
  7646. planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
  7647. planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
  7648. return this;
  7649. }
  7650. intersectsObject(object) {
  7651. const geometry = object.geometry;
  7652. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  7653. _sphere$2.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
  7654. return this.intersectsSphere(_sphere$2);
  7655. }
  7656. intersectsSprite(sprite) {
  7657. _sphere$2.center.set(0, 0, 0);
  7658. _sphere$2.radius = 0.7071067811865476;
  7659. _sphere$2.applyMatrix4(sprite.matrixWorld);
  7660. return this.intersectsSphere(_sphere$2);
  7661. }
  7662. intersectsSphere(sphere) {
  7663. const planes = this.planes;
  7664. const center = sphere.center;
  7665. const negRadius = -sphere.radius;
  7666. for (let i = 0; i < 6; i++) {
  7667. const distance = planes[i].distanceToPoint(center);
  7668. if (distance < negRadius) {
  7669. return false;
  7670. }
  7671. }
  7672. return true;
  7673. }
  7674. intersectsBox(box) {
  7675. const planes = this.planes;
  7676. for (let i = 0; i < 6; i++) {
  7677. const plane = planes[i]; // corner at max distance
  7678. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7679. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7680. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7681. if (plane.distanceToPoint(_vector$7) < 0) {
  7682. return false;
  7683. }
  7684. }
  7685. return true;
  7686. }
  7687. containsPoint(point) {
  7688. const planes = this.planes;
  7689. for (let i = 0; i < 6; i++) {
  7690. if (planes[i].distanceToPoint(point) < 0) {
  7691. return false;
  7692. }
  7693. }
  7694. return true;
  7695. }
  7696. clone() {
  7697. return new this.constructor().copy(this);
  7698. }
  7699. }
  7700. function WebGLAnimation() {
  7701. let context = null;
  7702. let isAnimating = false;
  7703. let animationLoop = null;
  7704. let requestId = null;
  7705. function onAnimationFrame(time, frame) {
  7706. animationLoop(time, frame);
  7707. requestId = context.requestAnimationFrame(onAnimationFrame);
  7708. }
  7709. return {
  7710. start: function () {
  7711. if (isAnimating === true) return;
  7712. if (animationLoop === null) return;
  7713. requestId = context.requestAnimationFrame(onAnimationFrame);
  7714. isAnimating = true;
  7715. },
  7716. stop: function () {
  7717. context.cancelAnimationFrame(requestId);
  7718. isAnimating = false;
  7719. },
  7720. setAnimationLoop: function (callback) {
  7721. animationLoop = callback;
  7722. },
  7723. setContext: function (value) {
  7724. context = value;
  7725. }
  7726. };
  7727. }
  7728. function WebGLAttributes(gl, capabilities) {
  7729. const isWebGL2 = capabilities.isWebGL2;
  7730. const buffers = new WeakMap();
  7731. function createBuffer(attribute, bufferType) {
  7732. const array = attribute.array;
  7733. const usage = attribute.usage;
  7734. const buffer = gl.createBuffer();
  7735. gl.bindBuffer(bufferType, buffer);
  7736. gl.bufferData(bufferType, array, usage);
  7737. attribute.onUploadCallback();
  7738. let type = gl.FLOAT;
  7739. if (array instanceof Float32Array) {
  7740. type = gl.FLOAT;
  7741. } else if (array instanceof Float64Array) {
  7742. console.warn('THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.');
  7743. } else if (array instanceof Uint16Array) {
  7744. if (attribute.isFloat16BufferAttribute) {
  7745. if (isWebGL2) {
  7746. type = gl.HALF_FLOAT;
  7747. } else {
  7748. console.warn('THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.');
  7749. }
  7750. } else {
  7751. type = gl.UNSIGNED_SHORT;
  7752. }
  7753. } else if (array instanceof Int16Array) {
  7754. type = gl.SHORT;
  7755. } else if (array instanceof Uint32Array) {
  7756. type = gl.UNSIGNED_INT;
  7757. } else if (array instanceof Int32Array) {
  7758. type = gl.INT;
  7759. } else if (array instanceof Int8Array) {
  7760. type = gl.BYTE;
  7761. } else if (array instanceof Uint8Array) {
  7762. type = gl.UNSIGNED_BYTE;
  7763. }
  7764. return {
  7765. buffer: buffer,
  7766. type: type,
  7767. bytesPerElement: array.BYTES_PER_ELEMENT,
  7768. version: attribute.version
  7769. };
  7770. }
  7771. function updateBuffer(buffer, attribute, bufferType) {
  7772. const array = attribute.array;
  7773. const updateRange = attribute.updateRange;
  7774. gl.bindBuffer(bufferType, buffer);
  7775. if (updateRange.count === -1) {
  7776. // Not using update ranges
  7777. gl.bufferSubData(bufferType, 0, array);
  7778. } else {
  7779. if (isWebGL2) {
  7780. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array, updateRange.offset, updateRange.count);
  7781. } else {
  7782. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
  7783. }
  7784. updateRange.count = -1; // reset range
  7785. }
  7786. } //
  7787. function get(attribute) {
  7788. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7789. return buffers.get(attribute);
  7790. }
  7791. function remove(attribute) {
  7792. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7793. const data = buffers.get(attribute);
  7794. if (data) {
  7795. gl.deleteBuffer(data.buffer);
  7796. buffers.delete(attribute);
  7797. }
  7798. }
  7799. function update(attribute, bufferType) {
  7800. if (attribute.isGLBufferAttribute) {
  7801. const cached = buffers.get(attribute);
  7802. if (!cached || cached.version < attribute.version) {
  7803. buffers.set(attribute, {
  7804. buffer: attribute.buffer,
  7805. type: attribute.type,
  7806. bytesPerElement: attribute.elementSize,
  7807. version: attribute.version
  7808. });
  7809. }
  7810. return;
  7811. }
  7812. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7813. const data = buffers.get(attribute);
  7814. if (data === undefined) {
  7815. buffers.set(attribute, createBuffer(attribute, bufferType));
  7816. } else if (data.version < attribute.version) {
  7817. updateBuffer(data.buffer, attribute, bufferType);
  7818. data.version = attribute.version;
  7819. }
  7820. }
  7821. return {
  7822. get: get,
  7823. remove: remove,
  7824. update: update
  7825. };
  7826. }
  7827. class PlaneGeometry extends BufferGeometry {
  7828. constructor(width = 1, height = 1, widthSegments = 1, heightSegments = 1) {
  7829. super();
  7830. this.type = 'PlaneGeometry';
  7831. this.parameters = {
  7832. width: width,
  7833. height: height,
  7834. widthSegments: widthSegments,
  7835. heightSegments: heightSegments
  7836. };
  7837. const width_half = width / 2;
  7838. const height_half = height / 2;
  7839. const gridX = Math.floor(widthSegments);
  7840. const gridY = Math.floor(heightSegments);
  7841. const gridX1 = gridX + 1;
  7842. const gridY1 = gridY + 1;
  7843. const segment_width = width / gridX;
  7844. const segment_height = height / gridY; //
  7845. const indices = [];
  7846. const vertices = [];
  7847. const normals = [];
  7848. const uvs = [];
  7849. for (let iy = 0; iy < gridY1; iy++) {
  7850. const y = iy * segment_height - height_half;
  7851. for (let ix = 0; ix < gridX1; ix++) {
  7852. const x = ix * segment_width - width_half;
  7853. vertices.push(x, -y, 0);
  7854. normals.push(0, 0, 1);
  7855. uvs.push(ix / gridX);
  7856. uvs.push(1 - iy / gridY);
  7857. }
  7858. }
  7859. for (let iy = 0; iy < gridY; iy++) {
  7860. for (let ix = 0; ix < gridX; ix++) {
  7861. const a = ix + gridX1 * iy;
  7862. const b = ix + gridX1 * (iy + 1);
  7863. const c = ix + 1 + gridX1 * (iy + 1);
  7864. const d = ix + 1 + gridX1 * iy;
  7865. indices.push(a, b, d);
  7866. indices.push(b, c, d);
  7867. }
  7868. }
  7869. this.setIndex(indices);
  7870. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  7871. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  7872. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  7873. }
  7874. }
  7875. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  7876. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7877. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";
  7878. var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif";
  7879. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7880. var begin_vertex = "vec3 transformed = vec3( position );";
  7881. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  7882. var bsdfs = "vec2 integrateSpecularBRDF( const in float dotNV, const in float roughness ) {\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\treturn vec2( -1.04, 1.04 ) * a004 + r.zw;\n}\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n#else\n\tif( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t}\n\treturn 1.0;\n#endif\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nvec3 F_Schlick_RoughnessDependent( const in vec3 F0, const in float dotNV, const in float roughness ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotNV - 6.98316 ) * dotNV );\n\tvec3 Fr = max( vec3( 1.0 - roughness ), F0 ) - F0;\n\treturn Fr * fresnel + F0;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + viewDir );\n\tfloat dotNL = saturate( dot( normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nvec3 BRDF_Specular_GGX_Environment( const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\treturn specularColor * brdf.x + brdf.y;\n}\nvoid BRDF_Specular_Multiscattering_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tvec3 F = F_Schlick_RoughnessDependent( specularColor, dotNV, roughness );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\tvec3 FssEss = F * brdf.x + brdf.y;\n\tfloat Ess = brdf.x + brdf.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie(float roughness, float NoH) {\n\tfloat invAlpha = 1.0 / roughness;\n\tfloat cos2h = NoH * NoH;\n\tfloat sin2h = max(1.0 - cos2h, 0.0078125);\treturn (2.0 + invAlpha) * pow(sin2h, invAlpha * 0.5) / (2.0 * PI);\n}\nfloat V_Neubelt(float NoV, float NoL) {\n\treturn saturate(1.0 / (4.0 * (NoL + NoV - NoL * NoV)));\n}\nvec3 BRDF_Specular_Sheen( const in float roughness, const in vec3 L, const in GeometricContext geometry, vec3 specularColor ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 H = normalize( V + L );\n\tfloat dotNH = saturate( dot( N, H ) );\n\treturn specularColor * D_Charlie( roughness, dotNH ) * V_Neubelt( dot(N, V), dot(N, L) );\n}\n#endif";
  7883. 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";
  7884. 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";
  7885. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  7886. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  7887. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  7888. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7889. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7890. 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";
  7891. 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";
  7892. var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat max3( vec3 v ) { return max( max( v.x, v.y ), v.z ); }\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}";
  7893. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_maxMipLevel 8.0\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_maxTileSize 256.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\tfloat texelSize = 1.0 / ( 3.0 * cubeUV_maxTileSize );\n\t\tvec2 uv = getUV( direction, face ) * ( faceSize - 1.0 );\n\t\tvec2 f = fract( uv );\n\t\tuv += 0.5 - f;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tif ( mipInt < cubeUV_maxMipLevel ) {\n\t\t\tuv.y += 2.0 * cubeUV_maxTileSize;\n\t\t}\n\t\tuv.y += filterInt * 2.0 * cubeUV_minTileSize;\n\t\tuv.x += 3.0 * max( 0.0, cubeUV_maxTileSize - 2.0 * faceSize );\n\t\tuv *= texelSize;\n\t\tvec3 tl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.x += texelSize;\n\t\tvec3 tr = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.y += texelSize;\n\t\tvec3 br = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.x -= texelSize;\n\t\tvec3 bl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tvec3 tm = mix( tl, tr, f.x );\n\t\tvec3 bm = mix( bl, br, f.x );\n\t\treturn mix( tm, bm, f.y );\n\t}\n\t#define r0 1.0\n\t#define v0 0.339\n\t#define m0 - 2.0\n\t#define r1 0.8\n\t#define v1 0.276\n\t#define m1 - 1.0\n\t#define r4 0.4\n\t#define v4 0.046\n\t#define m4 2.0\n\t#define r5 0.305\n\t#define v5 0.016\n\t#define m5 3.0\n\t#define r6 0.21\n\t#define v6 0.0038\n\t#define m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= r1 ) {\n\t\t\tmip = ( r0 - roughness ) * ( m1 - m0 ) / ( r0 - r1 ) + m0;\n\t\t} else if ( roughness >= r4 ) {\n\t\t\tmip = ( r1 - roughness ) * ( m4 - m1 ) / ( r1 - r4 ) + m1;\n\t\t} else if ( roughness >= r5 ) {\n\t\t\tmip = ( r4 - roughness ) * ( m5 - m4 ) / ( r4 - r5 ) + m4;\n\t\t} else if ( roughness >= r6 ) {\n\t\t\tmip = ( r5 - roughness ) * ( m6 - m5 ) / ( r5 - r6 ) + m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), m0, cubeUV_maxMipLevel );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif";
  7894. 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";
  7895. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  7896. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  7897. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  7898. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  7899. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  7900. var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( gammaFactor ) ), value.a );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( 1.0 / gammaFactor ) ), value.a );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * value.a * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\tD = clamp( floor( D ) / 255.0, 0.0, 1.0 );\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n\tvec3 Xp_Y_XYZp = cLogLuvM * value.rgb;\n\tXp_Y_XYZp = max( Xp_Y_XYZp, vec3( 1e-6, 1e-6, 1e-6 ) );\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract( Le );\n\tvResult.z = ( Le - ( floor( vResult.w * 255.0 ) ) / 255.0 ) / 255.0;\n\treturn vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2( ( Le - 127.0 ) / 2.0 );\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = cLogLuvInverseM * Xp_Y_XYZp.rgb;\n\treturn vec4( max( vRGB, 0.0 ), 1.0 );\n}";
  7901. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifndef ENVMAP_TYPE_CUBE_UV\n\t\tenvColor = envMapTexelToLinear( envColor );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";
  7902. var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform int maxMipLevel;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif";
  7903. 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";
  7904. 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";
  7905. 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";
  7906. var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = - mvPosition.z;\n#endif";
  7907. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";
  7908. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * fogDepth * fogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif";
  7909. var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float fogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif";
  7910. var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn texture2D( gradientMap, coord ).rgb;\n\t#else\n\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t#endif\n}";
  7911. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\treflectedLight.indirectDiffuse += PI * lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n#endif";
  7912. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7913. var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\nvIndirectFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n\tvIndirectBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\nvIndirectFront += getAmbientLightIrradiance( ambientLightColor );\nvIndirectFront += getLightProbeIrradiance( lightProbe, geometry );\n#ifdef DOUBLE_SIDED\n\tvIndirectBack += getAmbientLightIrradiance( ambientLightColor );\n\tvIndirectBack += getLightProbeIrradiance( lightProbe, backGeometry );\n#endif\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif";
  7914. var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in GeometricContext geometry ) {\n\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif";
  7915. var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float roughness, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat sigma = PI * roughness * roughness / ( 1.0 + roughness );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar + log2( sigma );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -viewDir, normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( roughness, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif";
  7916. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  7917. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n#define Material_LightProbeLOD( material )\t(0)";
  7918. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  7919. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)";
  7920. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.specularRoughness = max( roughnessFactor, 0.0525 );material.specularRoughness += geometryRoughness;\nmaterial.specularRoughness = min( material.specularRoughness, 1.0 );\n#ifdef REFLECTIVITY\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#endif\n#ifdef CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheen;\n#endif";
  7921. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat specularRoughness;\n\tvec3 specularColor;\n#ifdef CLEARCOAT\n\tfloat clearcoat;\n\tfloat clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tvec3 sheenColor;\n#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearcoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNL = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = ccDotNL * directLight.color;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tccIrradiance *= PI;\n\t\t#endif\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t\treflectedLight.directSpecular += ccIrradiance * material.clearcoat * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_Sheen(\n\t\t\tmaterial.specularRoughness,\n\t\t\tdirectLight.direction,\n\t\t\tgeometry,\n\t\t\tmaterial.sheenColor\n\t\t);\n\t#else\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.normal, material.specularColor, material.specularRoughness);\n\t#endif\n\treflectedLight.directDiffuse += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNV = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular += clearcoatRadiance * material.clearcoat * BRDF_Specular_GGX_Environment( geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t\tfloat ccDotNL = ccDotNV;\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\tfloat clearcoatInv = 1.0 - clearcoatDHR;\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tBRDF_Specular_Multiscattering_Environment( geometry, material.specularColor, material.specularRoughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += clearcoatInv * radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}";
  7922. var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif";
  7923. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getLightProbeIndirectIrradiance( geometry, maxMipLevel );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.normal, material.specularRoughness, maxMipLevel );\n\t#ifdef CLEARCOAT\n\t\tclearcoatRadiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness, maxMipLevel );\n\t#endif\n#endif";
  7924. 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";
  7925. 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";
  7926. 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";
  7927. 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";
  7928. 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";
  7929. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  7930. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  7931. 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";
  7932. 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";
  7933. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  7934. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  7935. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n#endif";
  7936. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifndef USE_MORPHNORMALS\n\t\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\t\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif";
  7937. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t#endif\n#endif";
  7938. 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;";
  7939. 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";
  7940. 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";
  7941. var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  7942. 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";
  7943. 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";
  7944. 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}";
  7945. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  7946. 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;";
  7947. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  7948. 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";
  7949. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  7950. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  7951. 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";
  7952. 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";
  7953. 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";
  7954. 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}";
  7955. 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";
  7956. 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";
  7957. 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";
  7958. 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";
  7959. 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";
  7960. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  7961. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  7962. 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; }";
  7963. var transmissionmap_fragment = "#ifdef USE_TRANSMISSIONMAP\n\ttotalTransmission *= texture2D( transmissionMap, vUv ).r;\n#endif";
  7964. var transmissionmap_pars_fragment = "#ifdef USE_TRANSMISSIONMAP\n\tuniform sampler2D transmissionMap;\n#endif";
  7965. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  7966. 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";
  7967. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  7968. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  7969. 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";
  7970. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  7971. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\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";
  7972. var background_frag = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7973. var background_vert = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}";
  7974. var cube_frag = "#include <envmap_common_pars_fragment>\nuniform float opacity;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\tvec3 vReflect = vWorldDirection;\n\t#include <envmap_fragment>\n\tgl_FragColor = envColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7975. var cube_vert = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}";
  7976. var depth_frag = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}";
  7977. var depth_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvHighPrecisionZW = gl_Position.zw;\n}";
  7978. var distanceRGBA_frag = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}";
  7979. var distanceRGBA_vert = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}";
  7980. var equirect_frag = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tvec4 texColor = texture2D( tEquirect, sampleUV );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7981. var equirect_vert = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}";
  7982. var linedashed_frag = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  7983. var linedashed_vert = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  7984. var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7985. var meshbasic_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_ENVMAP\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";
  7986. var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack;\n\t#else\n\t\treflectedLight.indirectDiffuse += vIndirectFront;\n\t#endif\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7987. var meshlambert_vert = "#define LAMBERT\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7988. var meshmatcap_frag = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t\tmatcapColor = matcapTexelToLinear( matcapColor );\n\t#else\n\t\tvec4 matcapColor = vec4( 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7989. var meshmatcap_vert = "#define MATCAP\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#ifndef FLAT_SHADED\n\t\tvNormal = normalize( transformedNormal );\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";
  7990. var meshtoon_frag = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7991. var meshtoon_vert = "#define TOON\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7992. var meshphong_frag = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7993. var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7994. var meshphysical_frag = "#define STANDARD\n#ifdef PHYSICAL\n\t#define REFLECTIVITY\n\t#define CLEARCOAT\n\t#define TRANSMISSION\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef TRANSMISSION\n\tuniform float transmission;\n#endif\n#ifdef REFLECTIVITY\n\tuniform float reflectivity;\n#endif\n#ifdef CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheen;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <transmissionmap_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 <lights_physical_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#ifdef TRANSMISSION\n\t\tfloat totalTransmission = transmission;\n\t#endif\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <transmissionmap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#ifdef TRANSMISSION\n\t\tdiffuseColor.a *= mix( saturate( 1. - totalTransmission + linearToRelativeLuminance( reflectedLight.directSpecular + reflectedLight.indirectSpecular ) ), 1.0, metalness );\n\t#endif\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7995. var meshphysical_vert = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7996. var normal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}";
  7997. var normal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
  7998. var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  7999. var points_vert = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n}";
  8000. var shadow_frag = "uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  8001. var shadow_vert = "#include <common>\n#include <fog_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8002. var sprite_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  8003. var sprite_vert = "uniform float rotation;\nuniform vec2 center;\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  8004. const ShaderChunk = {
  8005. alphamap_fragment: alphamap_fragment,
  8006. alphamap_pars_fragment: alphamap_pars_fragment,
  8007. alphatest_fragment: alphatest_fragment,
  8008. aomap_fragment: aomap_fragment,
  8009. aomap_pars_fragment: aomap_pars_fragment,
  8010. begin_vertex: begin_vertex,
  8011. beginnormal_vertex: beginnormal_vertex,
  8012. bsdfs: bsdfs,
  8013. bumpmap_pars_fragment: bumpmap_pars_fragment,
  8014. clipping_planes_fragment: clipping_planes_fragment,
  8015. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  8016. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  8017. clipping_planes_vertex: clipping_planes_vertex,
  8018. color_fragment: color_fragment,
  8019. color_pars_fragment: color_pars_fragment,
  8020. color_pars_vertex: color_pars_vertex,
  8021. color_vertex: color_vertex,
  8022. common: common,
  8023. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  8024. defaultnormal_vertex: defaultnormal_vertex,
  8025. displacementmap_pars_vertex: displacementmap_pars_vertex,
  8026. displacementmap_vertex: displacementmap_vertex,
  8027. emissivemap_fragment: emissivemap_fragment,
  8028. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8029. encodings_fragment: encodings_fragment,
  8030. encodings_pars_fragment: encodings_pars_fragment,
  8031. envmap_fragment: envmap_fragment,
  8032. envmap_common_pars_fragment: envmap_common_pars_fragment,
  8033. envmap_pars_fragment: envmap_pars_fragment,
  8034. envmap_pars_vertex: envmap_pars_vertex,
  8035. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  8036. envmap_vertex: envmap_vertex,
  8037. fog_vertex: fog_vertex,
  8038. fog_pars_vertex: fog_pars_vertex,
  8039. fog_fragment: fog_fragment,
  8040. fog_pars_fragment: fog_pars_fragment,
  8041. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8042. lightmap_fragment: lightmap_fragment,
  8043. lightmap_pars_fragment: lightmap_pars_fragment,
  8044. lights_lambert_vertex: lights_lambert_vertex,
  8045. lights_pars_begin: lights_pars_begin,
  8046. lights_toon_fragment: lights_toon_fragment,
  8047. lights_toon_pars_fragment: lights_toon_pars_fragment,
  8048. lights_phong_fragment: lights_phong_fragment,
  8049. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8050. lights_physical_fragment: lights_physical_fragment,
  8051. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8052. lights_fragment_begin: lights_fragment_begin,
  8053. lights_fragment_maps: lights_fragment_maps,
  8054. lights_fragment_end: lights_fragment_end,
  8055. logdepthbuf_fragment: logdepthbuf_fragment,
  8056. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8057. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8058. logdepthbuf_vertex: logdepthbuf_vertex,
  8059. map_fragment: map_fragment,
  8060. map_pars_fragment: map_pars_fragment,
  8061. map_particle_fragment: map_particle_fragment,
  8062. map_particle_pars_fragment: map_particle_pars_fragment,
  8063. metalnessmap_fragment: metalnessmap_fragment,
  8064. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8065. morphnormal_vertex: morphnormal_vertex,
  8066. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8067. morphtarget_vertex: morphtarget_vertex,
  8068. normal_fragment_begin: normal_fragment_begin,
  8069. normal_fragment_maps: normal_fragment_maps,
  8070. normalmap_pars_fragment: normalmap_pars_fragment,
  8071. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8072. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8073. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8074. packing: packing,
  8075. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8076. project_vertex: project_vertex,
  8077. dithering_fragment: dithering_fragment,
  8078. dithering_pars_fragment: dithering_pars_fragment,
  8079. roughnessmap_fragment: roughnessmap_fragment,
  8080. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8081. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8082. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8083. shadowmap_vertex: shadowmap_vertex,
  8084. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8085. skinbase_vertex: skinbase_vertex,
  8086. skinning_pars_vertex: skinning_pars_vertex,
  8087. skinning_vertex: skinning_vertex,
  8088. skinnormal_vertex: skinnormal_vertex,
  8089. specularmap_fragment: specularmap_fragment,
  8090. specularmap_pars_fragment: specularmap_pars_fragment,
  8091. tonemapping_fragment: tonemapping_fragment,
  8092. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8093. transmissionmap_fragment: transmissionmap_fragment,
  8094. transmissionmap_pars_fragment: transmissionmap_pars_fragment,
  8095. uv_pars_fragment: uv_pars_fragment,
  8096. uv_pars_vertex: uv_pars_vertex,
  8097. uv_vertex: uv_vertex,
  8098. uv2_pars_fragment: uv2_pars_fragment,
  8099. uv2_pars_vertex: uv2_pars_vertex,
  8100. uv2_vertex: uv2_vertex,
  8101. worldpos_vertex: worldpos_vertex,
  8102. background_frag: background_frag,
  8103. background_vert: background_vert,
  8104. cube_frag: cube_frag,
  8105. cube_vert: cube_vert,
  8106. depth_frag: depth_frag,
  8107. depth_vert: depth_vert,
  8108. distanceRGBA_frag: distanceRGBA_frag,
  8109. distanceRGBA_vert: distanceRGBA_vert,
  8110. equirect_frag: equirect_frag,
  8111. equirect_vert: equirect_vert,
  8112. linedashed_frag: linedashed_frag,
  8113. linedashed_vert: linedashed_vert,
  8114. meshbasic_frag: meshbasic_frag,
  8115. meshbasic_vert: meshbasic_vert,
  8116. meshlambert_frag: meshlambert_frag,
  8117. meshlambert_vert: meshlambert_vert,
  8118. meshmatcap_frag: meshmatcap_frag,
  8119. meshmatcap_vert: meshmatcap_vert,
  8120. meshtoon_frag: meshtoon_frag,
  8121. meshtoon_vert: meshtoon_vert,
  8122. meshphong_frag: meshphong_frag,
  8123. meshphong_vert: meshphong_vert,
  8124. meshphysical_frag: meshphysical_frag,
  8125. meshphysical_vert: meshphysical_vert,
  8126. normal_frag: normal_frag,
  8127. normal_vert: normal_vert,
  8128. points_frag: points_frag,
  8129. points_vert: points_vert,
  8130. shadow_frag: shadow_frag,
  8131. shadow_vert: shadow_vert,
  8132. sprite_frag: sprite_frag,
  8133. sprite_vert: sprite_vert
  8134. };
  8135. /**
  8136. * Uniforms library for shared webgl shaders
  8137. */
  8138. const UniformsLib = {
  8139. common: {
  8140. diffuse: {
  8141. value: new Color(0xeeeeee)
  8142. },
  8143. opacity: {
  8144. value: 1.0
  8145. },
  8146. map: {
  8147. value: null
  8148. },
  8149. uvTransform: {
  8150. value: new Matrix3()
  8151. },
  8152. uv2Transform: {
  8153. value: new Matrix3()
  8154. },
  8155. alphaMap: {
  8156. value: null
  8157. }
  8158. },
  8159. specularmap: {
  8160. specularMap: {
  8161. value: null
  8162. }
  8163. },
  8164. envmap: {
  8165. envMap: {
  8166. value: null
  8167. },
  8168. flipEnvMap: {
  8169. value: -1
  8170. },
  8171. reflectivity: {
  8172. value: 1.0
  8173. },
  8174. refractionRatio: {
  8175. value: 0.98
  8176. },
  8177. maxMipLevel: {
  8178. value: 0
  8179. }
  8180. },
  8181. aomap: {
  8182. aoMap: {
  8183. value: null
  8184. },
  8185. aoMapIntensity: {
  8186. value: 1
  8187. }
  8188. },
  8189. lightmap: {
  8190. lightMap: {
  8191. value: null
  8192. },
  8193. lightMapIntensity: {
  8194. value: 1
  8195. }
  8196. },
  8197. emissivemap: {
  8198. emissiveMap: {
  8199. value: null
  8200. }
  8201. },
  8202. bumpmap: {
  8203. bumpMap: {
  8204. value: null
  8205. },
  8206. bumpScale: {
  8207. value: 1
  8208. }
  8209. },
  8210. normalmap: {
  8211. normalMap: {
  8212. value: null
  8213. },
  8214. normalScale: {
  8215. value: new Vector2(1, 1)
  8216. }
  8217. },
  8218. displacementmap: {
  8219. displacementMap: {
  8220. value: null
  8221. },
  8222. displacementScale: {
  8223. value: 1
  8224. },
  8225. displacementBias: {
  8226. value: 0
  8227. }
  8228. },
  8229. roughnessmap: {
  8230. roughnessMap: {
  8231. value: null
  8232. }
  8233. },
  8234. metalnessmap: {
  8235. metalnessMap: {
  8236. value: null
  8237. }
  8238. },
  8239. gradientmap: {
  8240. gradientMap: {
  8241. value: null
  8242. }
  8243. },
  8244. fog: {
  8245. fogDensity: {
  8246. value: 0.00025
  8247. },
  8248. fogNear: {
  8249. value: 1
  8250. },
  8251. fogFar: {
  8252. value: 2000
  8253. },
  8254. fogColor: {
  8255. value: new Color(0xffffff)
  8256. }
  8257. },
  8258. lights: {
  8259. ambientLightColor: {
  8260. value: []
  8261. },
  8262. lightProbe: {
  8263. value: []
  8264. },
  8265. directionalLights: {
  8266. value: [],
  8267. properties: {
  8268. direction: {},
  8269. color: {}
  8270. }
  8271. },
  8272. directionalLightShadows: {
  8273. value: [],
  8274. properties: {
  8275. shadowBias: {},
  8276. shadowNormalBias: {},
  8277. shadowRadius: {},
  8278. shadowMapSize: {}
  8279. }
  8280. },
  8281. directionalShadowMap: {
  8282. value: []
  8283. },
  8284. directionalShadowMatrix: {
  8285. value: []
  8286. },
  8287. spotLights: {
  8288. value: [],
  8289. properties: {
  8290. color: {},
  8291. position: {},
  8292. direction: {},
  8293. distance: {},
  8294. coneCos: {},
  8295. penumbraCos: {},
  8296. decay: {}
  8297. }
  8298. },
  8299. spotLightShadows: {
  8300. value: [],
  8301. properties: {
  8302. shadowBias: {},
  8303. shadowNormalBias: {},
  8304. shadowRadius: {},
  8305. shadowMapSize: {}
  8306. }
  8307. },
  8308. spotShadowMap: {
  8309. value: []
  8310. },
  8311. spotShadowMatrix: {
  8312. value: []
  8313. },
  8314. pointLights: {
  8315. value: [],
  8316. properties: {
  8317. color: {},
  8318. position: {},
  8319. decay: {},
  8320. distance: {}
  8321. }
  8322. },
  8323. pointLightShadows: {
  8324. value: [],
  8325. properties: {
  8326. shadowBias: {},
  8327. shadowNormalBias: {},
  8328. shadowRadius: {},
  8329. shadowMapSize: {},
  8330. shadowCameraNear: {},
  8331. shadowCameraFar: {}
  8332. }
  8333. },
  8334. pointShadowMap: {
  8335. value: []
  8336. },
  8337. pointShadowMatrix: {
  8338. value: []
  8339. },
  8340. hemisphereLights: {
  8341. value: [],
  8342. properties: {
  8343. direction: {},
  8344. skyColor: {},
  8345. groundColor: {}
  8346. }
  8347. },
  8348. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8349. rectAreaLights: {
  8350. value: [],
  8351. properties: {
  8352. color: {},
  8353. position: {},
  8354. width: {},
  8355. height: {}
  8356. }
  8357. },
  8358. ltc_1: {
  8359. value: null
  8360. },
  8361. ltc_2: {
  8362. value: null
  8363. }
  8364. },
  8365. points: {
  8366. diffuse: {
  8367. value: new Color(0xeeeeee)
  8368. },
  8369. opacity: {
  8370. value: 1.0
  8371. },
  8372. size: {
  8373. value: 1.0
  8374. },
  8375. scale: {
  8376. value: 1.0
  8377. },
  8378. map: {
  8379. value: null
  8380. },
  8381. alphaMap: {
  8382. value: null
  8383. },
  8384. uvTransform: {
  8385. value: new Matrix3()
  8386. }
  8387. },
  8388. sprite: {
  8389. diffuse: {
  8390. value: new Color(0xeeeeee)
  8391. },
  8392. opacity: {
  8393. value: 1.0
  8394. },
  8395. center: {
  8396. value: new Vector2(0.5, 0.5)
  8397. },
  8398. rotation: {
  8399. value: 0.0
  8400. },
  8401. map: {
  8402. value: null
  8403. },
  8404. alphaMap: {
  8405. value: null
  8406. },
  8407. uvTransform: {
  8408. value: new Matrix3()
  8409. }
  8410. }
  8411. };
  8412. const ShaderLib = {
  8413. basic: {
  8414. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
  8415. vertexShader: ShaderChunk.meshbasic_vert,
  8416. fragmentShader: ShaderChunk.meshbasic_frag
  8417. },
  8418. lambert: {
  8419. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.fog, UniformsLib.lights, {
  8420. emissive: {
  8421. value: new Color(0x000000)
  8422. }
  8423. }]),
  8424. vertexShader: ShaderChunk.meshlambert_vert,
  8425. fragmentShader: ShaderChunk.meshlambert_frag
  8426. },
  8427. phong: {
  8428. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, UniformsLib.lights, {
  8429. emissive: {
  8430. value: new Color(0x000000)
  8431. },
  8432. specular: {
  8433. value: new Color(0x111111)
  8434. },
  8435. shininess: {
  8436. value: 30
  8437. }
  8438. }]),
  8439. vertexShader: ShaderChunk.meshphong_vert,
  8440. fragmentShader: ShaderChunk.meshphong_frag
  8441. },
  8442. standard: {
  8443. 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, {
  8444. emissive: {
  8445. value: new Color(0x000000)
  8446. },
  8447. roughness: {
  8448. value: 1.0
  8449. },
  8450. metalness: {
  8451. value: 0.0
  8452. },
  8453. envMapIntensity: {
  8454. value: 1
  8455. } // temporary
  8456. }]),
  8457. vertexShader: ShaderChunk.meshphysical_vert,
  8458. fragmentShader: ShaderChunk.meshphysical_frag
  8459. },
  8460. toon: {
  8461. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.gradientmap, UniformsLib.fog, UniformsLib.lights, {
  8462. emissive: {
  8463. value: new Color(0x000000)
  8464. }
  8465. }]),
  8466. vertexShader: ShaderChunk.meshtoon_vert,
  8467. fragmentShader: ShaderChunk.meshtoon_frag
  8468. },
  8469. matcap: {
  8470. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
  8471. matcap: {
  8472. value: null
  8473. }
  8474. }]),
  8475. vertexShader: ShaderChunk.meshmatcap_vert,
  8476. fragmentShader: ShaderChunk.meshmatcap_frag
  8477. },
  8478. points: {
  8479. uniforms: mergeUniforms([UniformsLib.points, UniformsLib.fog]),
  8480. vertexShader: ShaderChunk.points_vert,
  8481. fragmentShader: ShaderChunk.points_frag
  8482. },
  8483. dashed: {
  8484. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.fog, {
  8485. scale: {
  8486. value: 1
  8487. },
  8488. dashSize: {
  8489. value: 1
  8490. },
  8491. totalSize: {
  8492. value: 2
  8493. }
  8494. }]),
  8495. vertexShader: ShaderChunk.linedashed_vert,
  8496. fragmentShader: ShaderChunk.linedashed_frag
  8497. },
  8498. depth: {
  8499. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
  8500. vertexShader: ShaderChunk.depth_vert,
  8501. fragmentShader: ShaderChunk.depth_frag
  8502. },
  8503. normal: {
  8504. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
  8505. opacity: {
  8506. value: 1.0
  8507. }
  8508. }]),
  8509. vertexShader: ShaderChunk.normal_vert,
  8510. fragmentShader: ShaderChunk.normal_frag
  8511. },
  8512. sprite: {
  8513. uniforms: mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
  8514. vertexShader: ShaderChunk.sprite_vert,
  8515. fragmentShader: ShaderChunk.sprite_frag
  8516. },
  8517. background: {
  8518. uniforms: {
  8519. uvTransform: {
  8520. value: new Matrix3()
  8521. },
  8522. t2D: {
  8523. value: null
  8524. }
  8525. },
  8526. vertexShader: ShaderChunk.background_vert,
  8527. fragmentShader: ShaderChunk.background_frag
  8528. },
  8529. /* -------------------------------------------------------------------------
  8530. // Cube map shader
  8531. ------------------------------------------------------------------------- */
  8532. cube: {
  8533. uniforms: mergeUniforms([UniformsLib.envmap, {
  8534. opacity: {
  8535. value: 1.0
  8536. }
  8537. }]),
  8538. vertexShader: ShaderChunk.cube_vert,
  8539. fragmentShader: ShaderChunk.cube_frag
  8540. },
  8541. equirect: {
  8542. uniforms: {
  8543. tEquirect: {
  8544. value: null
  8545. }
  8546. },
  8547. vertexShader: ShaderChunk.equirect_vert,
  8548. fragmentShader: ShaderChunk.equirect_frag
  8549. },
  8550. distanceRGBA: {
  8551. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
  8552. referencePosition: {
  8553. value: new Vector3()
  8554. },
  8555. nearDistance: {
  8556. value: 1
  8557. },
  8558. farDistance: {
  8559. value: 1000
  8560. }
  8561. }]),
  8562. vertexShader: ShaderChunk.distanceRGBA_vert,
  8563. fragmentShader: ShaderChunk.distanceRGBA_frag
  8564. },
  8565. shadow: {
  8566. uniforms: mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
  8567. color: {
  8568. value: new Color(0x00000)
  8569. },
  8570. opacity: {
  8571. value: 1.0
  8572. }
  8573. }]),
  8574. vertexShader: ShaderChunk.shadow_vert,
  8575. fragmentShader: ShaderChunk.shadow_frag
  8576. }
  8577. };
  8578. ShaderLib.physical = {
  8579. uniforms: mergeUniforms([ShaderLib.standard.uniforms, {
  8580. clearcoat: {
  8581. value: 0
  8582. },
  8583. clearcoatMap: {
  8584. value: null
  8585. },
  8586. clearcoatRoughness: {
  8587. value: 0
  8588. },
  8589. clearcoatRoughnessMap: {
  8590. value: null
  8591. },
  8592. clearcoatNormalScale: {
  8593. value: new Vector2(1, 1)
  8594. },
  8595. clearcoatNormalMap: {
  8596. value: null
  8597. },
  8598. sheen: {
  8599. value: new Color(0x000000)
  8600. },
  8601. transmission: {
  8602. value: 0
  8603. },
  8604. transmissionMap: {
  8605. value: null
  8606. }
  8607. }]),
  8608. vertexShader: ShaderChunk.meshphysical_vert,
  8609. fragmentShader: ShaderChunk.meshphysical_frag
  8610. };
  8611. function WebGLBackground(renderer, cubemaps, state, objects, premultipliedAlpha) {
  8612. const clearColor = new Color(0x000000);
  8613. let clearAlpha = 0;
  8614. let planeMesh;
  8615. let boxMesh;
  8616. let currentBackground = null;
  8617. let currentBackgroundVersion = 0;
  8618. let currentTonemapping = null;
  8619. function render(renderList, scene) {
  8620. let forceClear = false;
  8621. let background = scene.isScene === true ? scene.background : null;
  8622. if (background && background.isTexture) {
  8623. background = cubemaps.get(background);
  8624. } // Ignore background in AR
  8625. // TODO: Reconsider this.
  8626. const xr = renderer.xr;
  8627. const session = xr.getSession && xr.getSession();
  8628. if (session && session.environmentBlendMode === 'additive') {
  8629. background = null;
  8630. }
  8631. if (background === null) {
  8632. setClear(clearColor, clearAlpha);
  8633. } else if (background && background.isColor) {
  8634. setClear(background, 1);
  8635. forceClear = true;
  8636. }
  8637. if (renderer.autoClear || forceClear) {
  8638. renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
  8639. }
  8640. if (background && (background.isCubeTexture || background.mapping === CubeUVReflectionMapping)) {
  8641. if (boxMesh === undefined) {
  8642. boxMesh = new Mesh(new BoxGeometry(1, 1, 1), new ShaderMaterial({
  8643. name: 'BackgroundCubeMaterial',
  8644. uniforms: cloneUniforms(ShaderLib.cube.uniforms),
  8645. vertexShader: ShaderLib.cube.vertexShader,
  8646. fragmentShader: ShaderLib.cube.fragmentShader,
  8647. side: BackSide,
  8648. depthTest: false,
  8649. depthWrite: false,
  8650. fog: false
  8651. }));
  8652. boxMesh.geometry.deleteAttribute('normal');
  8653. boxMesh.geometry.deleteAttribute('uv');
  8654. boxMesh.onBeforeRender = function (renderer, scene, camera) {
  8655. this.matrixWorld.copyPosition(camera.matrixWorld);
  8656. }; // enable code injection for non-built-in material
  8657. Object.defineProperty(boxMesh.material, 'envMap', {
  8658. get: function () {
  8659. return this.uniforms.envMap.value;
  8660. }
  8661. });
  8662. objects.update(boxMesh);
  8663. }
  8664. boxMesh.material.uniforms.envMap.value = background;
  8665. boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background._needsFlipEnvMap ? -1 : 1;
  8666. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8667. boxMesh.material.needsUpdate = true;
  8668. currentBackground = background;
  8669. currentBackgroundVersion = background.version;
  8670. currentTonemapping = renderer.toneMapping;
  8671. } // push to the pre-sorted opaque render list
  8672. renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
  8673. } else if (background && background.isTexture) {
  8674. if (planeMesh === undefined) {
  8675. planeMesh = new Mesh(new PlaneGeometry(2, 2), new ShaderMaterial({
  8676. name: 'BackgroundMaterial',
  8677. uniforms: cloneUniforms(ShaderLib.background.uniforms),
  8678. vertexShader: ShaderLib.background.vertexShader,
  8679. fragmentShader: ShaderLib.background.fragmentShader,
  8680. side: FrontSide,
  8681. depthTest: false,
  8682. depthWrite: false,
  8683. fog: false
  8684. }));
  8685. planeMesh.geometry.deleteAttribute('normal'); // enable code injection for non-built-in material
  8686. Object.defineProperty(planeMesh.material, 'map', {
  8687. get: function () {
  8688. return this.uniforms.t2D.value;
  8689. }
  8690. });
  8691. objects.update(planeMesh);
  8692. }
  8693. planeMesh.material.uniforms.t2D.value = background;
  8694. if (background.matrixAutoUpdate === true) {
  8695. background.updateMatrix();
  8696. }
  8697. planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
  8698. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8699. planeMesh.material.needsUpdate = true;
  8700. currentBackground = background;
  8701. currentBackgroundVersion = background.version;
  8702. currentTonemapping = renderer.toneMapping;
  8703. } // push to the pre-sorted opaque render list
  8704. renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
  8705. }
  8706. }
  8707. function setClear(color, alpha) {
  8708. state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha);
  8709. }
  8710. return {
  8711. getClearColor: function () {
  8712. return clearColor;
  8713. },
  8714. setClearColor: function (color, alpha = 1) {
  8715. clearColor.set(color);
  8716. clearAlpha = alpha;
  8717. setClear(clearColor, clearAlpha);
  8718. },
  8719. getClearAlpha: function () {
  8720. return clearAlpha;
  8721. },
  8722. setClearAlpha: function (alpha) {
  8723. clearAlpha = alpha;
  8724. setClear(clearColor, clearAlpha);
  8725. },
  8726. render: render
  8727. };
  8728. }
  8729. function WebGLBindingStates(gl, extensions, attributes, capabilities) {
  8730. const maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  8731. const extension = capabilities.isWebGL2 ? null : extensions.get('OES_vertex_array_object');
  8732. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8733. const bindingStates = {};
  8734. const defaultState = createBindingState(null);
  8735. let currentState = defaultState;
  8736. function setup(object, material, program, geometry, index) {
  8737. let updateBuffers = false;
  8738. if (vaoAvailable) {
  8739. const state = getBindingState(geometry, program, material);
  8740. if (currentState !== state) {
  8741. currentState = state;
  8742. bindVertexArrayObject(currentState.object);
  8743. }
  8744. updateBuffers = needsUpdate(geometry, index);
  8745. if (updateBuffers) saveCache(geometry, index);
  8746. } else {
  8747. const wireframe = material.wireframe === true;
  8748. if (currentState.geometry !== geometry.id || currentState.program !== program.id || currentState.wireframe !== wireframe) {
  8749. currentState.geometry = geometry.id;
  8750. currentState.program = program.id;
  8751. currentState.wireframe = wireframe;
  8752. updateBuffers = true;
  8753. }
  8754. }
  8755. if (object.isInstancedMesh === true) {
  8756. updateBuffers = true;
  8757. }
  8758. if (index !== null) {
  8759. attributes.update(index, gl.ELEMENT_ARRAY_BUFFER);
  8760. }
  8761. if (updateBuffers) {
  8762. setupVertexAttributes(object, material, program, geometry);
  8763. if (index !== null) {
  8764. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, attributes.get(index).buffer);
  8765. }
  8766. }
  8767. }
  8768. function createVertexArrayObject() {
  8769. if (capabilities.isWebGL2) return gl.createVertexArray();
  8770. return extension.createVertexArrayOES();
  8771. }
  8772. function bindVertexArrayObject(vao) {
  8773. if (capabilities.isWebGL2) return gl.bindVertexArray(vao);
  8774. return extension.bindVertexArrayOES(vao);
  8775. }
  8776. function deleteVertexArrayObject(vao) {
  8777. if (capabilities.isWebGL2) return gl.deleteVertexArray(vao);
  8778. return extension.deleteVertexArrayOES(vao);
  8779. }
  8780. function getBindingState(geometry, program, material) {
  8781. const wireframe = material.wireframe === true;
  8782. let programMap = bindingStates[geometry.id];
  8783. if (programMap === undefined) {
  8784. programMap = {};
  8785. bindingStates[geometry.id] = programMap;
  8786. }
  8787. let stateMap = programMap[program.id];
  8788. if (stateMap === undefined) {
  8789. stateMap = {};
  8790. programMap[program.id] = stateMap;
  8791. }
  8792. let state = stateMap[wireframe];
  8793. if (state === undefined) {
  8794. state = createBindingState(createVertexArrayObject());
  8795. stateMap[wireframe] = state;
  8796. }
  8797. return state;
  8798. }
  8799. function createBindingState(vao) {
  8800. const newAttributes = [];
  8801. const enabledAttributes = [];
  8802. const attributeDivisors = [];
  8803. for (let i = 0; i < maxVertexAttributes; i++) {
  8804. newAttributes[i] = 0;
  8805. enabledAttributes[i] = 0;
  8806. attributeDivisors[i] = 0;
  8807. }
  8808. return {
  8809. // for backward compatibility on non-VAO support browser
  8810. geometry: null,
  8811. program: null,
  8812. wireframe: false,
  8813. newAttributes: newAttributes,
  8814. enabledAttributes: enabledAttributes,
  8815. attributeDivisors: attributeDivisors,
  8816. object: vao,
  8817. attributes: {},
  8818. index: null
  8819. };
  8820. }
  8821. function needsUpdate(geometry, index) {
  8822. const cachedAttributes = currentState.attributes;
  8823. const geometryAttributes = geometry.attributes;
  8824. let attributesNum = 0;
  8825. for (const key in geometryAttributes) {
  8826. const cachedAttribute = cachedAttributes[key];
  8827. const geometryAttribute = geometryAttributes[key];
  8828. if (cachedAttribute === undefined) return true;
  8829. if (cachedAttribute.attribute !== geometryAttribute) return true;
  8830. if (cachedAttribute.data !== geometryAttribute.data) return true;
  8831. attributesNum++;
  8832. }
  8833. if (currentState.attributesNum !== attributesNum) return true;
  8834. if (currentState.index !== index) return true;
  8835. return false;
  8836. }
  8837. function saveCache(geometry, index) {
  8838. const cache = {};
  8839. const attributes = geometry.attributes;
  8840. let attributesNum = 0;
  8841. for (const key in attributes) {
  8842. const attribute = attributes[key];
  8843. const data = {};
  8844. data.attribute = attribute;
  8845. if (attribute.data) {
  8846. data.data = attribute.data;
  8847. }
  8848. cache[key] = data;
  8849. attributesNum++;
  8850. }
  8851. currentState.attributes = cache;
  8852. currentState.attributesNum = attributesNum;
  8853. currentState.index = index;
  8854. }
  8855. function initAttributes() {
  8856. const newAttributes = currentState.newAttributes;
  8857. for (let i = 0, il = newAttributes.length; i < il; i++) {
  8858. newAttributes[i] = 0;
  8859. }
  8860. }
  8861. function enableAttribute(attribute) {
  8862. enableAttributeAndDivisor(attribute, 0);
  8863. }
  8864. function enableAttributeAndDivisor(attribute, meshPerAttribute) {
  8865. const newAttributes = currentState.newAttributes;
  8866. const enabledAttributes = currentState.enabledAttributes;
  8867. const attributeDivisors = currentState.attributeDivisors;
  8868. newAttributes[attribute] = 1;
  8869. if (enabledAttributes[attribute] === 0) {
  8870. gl.enableVertexAttribArray(attribute);
  8871. enabledAttributes[attribute] = 1;
  8872. }
  8873. if (attributeDivisors[attribute] !== meshPerAttribute) {
  8874. const extension = capabilities.isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
  8875. extension[capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);
  8876. attributeDivisors[attribute] = meshPerAttribute;
  8877. }
  8878. }
  8879. function disableUnusedAttributes() {
  8880. const newAttributes = currentState.newAttributes;
  8881. const enabledAttributes = currentState.enabledAttributes;
  8882. for (let i = 0, il = enabledAttributes.length; i < il; i++) {
  8883. if (enabledAttributes[i] !== newAttributes[i]) {
  8884. gl.disableVertexAttribArray(i);
  8885. enabledAttributes[i] = 0;
  8886. }
  8887. }
  8888. }
  8889. function vertexAttribPointer(index, size, type, normalized, stride, offset) {
  8890. if (capabilities.isWebGL2 === true && (type === gl.INT || type === gl.UNSIGNED_INT)) {
  8891. gl.vertexAttribIPointer(index, size, type, stride, offset);
  8892. } else {
  8893. gl.vertexAttribPointer(index, size, type, normalized, stride, offset);
  8894. }
  8895. }
  8896. function setupVertexAttributes(object, material, program, geometry) {
  8897. if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
  8898. if (extensions.get('ANGLE_instanced_arrays') === null) return;
  8899. }
  8900. initAttributes();
  8901. const geometryAttributes = geometry.attributes;
  8902. const programAttributes = program.getAttributes();
  8903. const materialDefaultAttributeValues = material.defaultAttributeValues;
  8904. for (const name in programAttributes) {
  8905. const programAttribute = programAttributes[name];
  8906. if (programAttribute >= 0) {
  8907. const geometryAttribute = geometryAttributes[name];
  8908. if (geometryAttribute !== undefined) {
  8909. const normalized = geometryAttribute.normalized;
  8910. const size = geometryAttribute.itemSize;
  8911. const attribute = attributes.get(geometryAttribute); // TODO Attribute may not be available on context restore
  8912. if (attribute === undefined) continue;
  8913. const buffer = attribute.buffer;
  8914. const type = attribute.type;
  8915. const bytesPerElement = attribute.bytesPerElement;
  8916. if (geometryAttribute.isInterleavedBufferAttribute) {
  8917. const data = geometryAttribute.data;
  8918. const stride = data.stride;
  8919. const offset = geometryAttribute.offset;
  8920. if (data && data.isInstancedInterleavedBuffer) {
  8921. enableAttributeAndDivisor(programAttribute, data.meshPerAttribute);
  8922. if (geometry._maxInstanceCount === undefined) {
  8923. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  8924. }
  8925. } else {
  8926. enableAttribute(programAttribute);
  8927. }
  8928. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8929. vertexAttribPointer(programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement);
  8930. } else {
  8931. if (geometryAttribute.isInstancedBufferAttribute) {
  8932. enableAttributeAndDivisor(programAttribute, geometryAttribute.meshPerAttribute);
  8933. if (geometry._maxInstanceCount === undefined) {
  8934. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  8935. }
  8936. } else {
  8937. enableAttribute(programAttribute);
  8938. }
  8939. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8940. vertexAttribPointer(programAttribute, size, type, normalized, 0, 0);
  8941. }
  8942. } else if (name === 'instanceMatrix') {
  8943. const attribute = attributes.get(object.instanceMatrix); // TODO Attribute may not be available on context restore
  8944. if (attribute === undefined) continue;
  8945. const buffer = attribute.buffer;
  8946. const type = attribute.type;
  8947. enableAttributeAndDivisor(programAttribute + 0, 1);
  8948. enableAttributeAndDivisor(programAttribute + 1, 1);
  8949. enableAttributeAndDivisor(programAttribute + 2, 1);
  8950. enableAttributeAndDivisor(programAttribute + 3, 1);
  8951. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8952. gl.vertexAttribPointer(programAttribute + 0, 4, type, false, 64, 0);
  8953. gl.vertexAttribPointer(programAttribute + 1, 4, type, false, 64, 16);
  8954. gl.vertexAttribPointer(programAttribute + 2, 4, type, false, 64, 32);
  8955. gl.vertexAttribPointer(programAttribute + 3, 4, type, false, 64, 48);
  8956. } else if (name === 'instanceColor') {
  8957. const attribute = attributes.get(object.instanceColor); // TODO Attribute may not be available on context restore
  8958. if (attribute === undefined) continue;
  8959. const buffer = attribute.buffer;
  8960. const type = attribute.type;
  8961. enableAttributeAndDivisor(programAttribute, 1);
  8962. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8963. gl.vertexAttribPointer(programAttribute, 3, type, false, 12, 0);
  8964. } else if (materialDefaultAttributeValues !== undefined) {
  8965. const value = materialDefaultAttributeValues[name];
  8966. if (value !== undefined) {
  8967. switch (value.length) {
  8968. case 2:
  8969. gl.vertexAttrib2fv(programAttribute, value);
  8970. break;
  8971. case 3:
  8972. gl.vertexAttrib3fv(programAttribute, value);
  8973. break;
  8974. case 4:
  8975. gl.vertexAttrib4fv(programAttribute, value);
  8976. break;
  8977. default:
  8978. gl.vertexAttrib1fv(programAttribute, value);
  8979. }
  8980. }
  8981. }
  8982. }
  8983. }
  8984. disableUnusedAttributes();
  8985. }
  8986. function dispose() {
  8987. reset();
  8988. for (const geometryId in bindingStates) {
  8989. const programMap = bindingStates[geometryId];
  8990. for (const programId in programMap) {
  8991. const stateMap = programMap[programId];
  8992. for (const wireframe in stateMap) {
  8993. deleteVertexArrayObject(stateMap[wireframe].object);
  8994. delete stateMap[wireframe];
  8995. }
  8996. delete programMap[programId];
  8997. }
  8998. delete bindingStates[geometryId];
  8999. }
  9000. }
  9001. function releaseStatesOfGeometry(geometry) {
  9002. if (bindingStates[geometry.id] === undefined) return;
  9003. const programMap = bindingStates[geometry.id];
  9004. for (const programId in programMap) {
  9005. const stateMap = programMap[programId];
  9006. for (const wireframe in stateMap) {
  9007. deleteVertexArrayObject(stateMap[wireframe].object);
  9008. delete stateMap[wireframe];
  9009. }
  9010. delete programMap[programId];
  9011. }
  9012. delete bindingStates[geometry.id];
  9013. }
  9014. function releaseStatesOfProgram(program) {
  9015. for (const geometryId in bindingStates) {
  9016. const programMap = bindingStates[geometryId];
  9017. if (programMap[program.id] === undefined) continue;
  9018. const stateMap = programMap[program.id];
  9019. for (const wireframe in stateMap) {
  9020. deleteVertexArrayObject(stateMap[wireframe].object);
  9021. delete stateMap[wireframe];
  9022. }
  9023. delete programMap[program.id];
  9024. }
  9025. }
  9026. function reset() {
  9027. resetDefaultState();
  9028. if (currentState === defaultState) return;
  9029. currentState = defaultState;
  9030. bindVertexArrayObject(currentState.object);
  9031. } // for backward-compatilibity
  9032. function resetDefaultState() {
  9033. defaultState.geometry = null;
  9034. defaultState.program = null;
  9035. defaultState.wireframe = false;
  9036. }
  9037. return {
  9038. setup: setup,
  9039. reset: reset,
  9040. resetDefaultState: resetDefaultState,
  9041. dispose: dispose,
  9042. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9043. releaseStatesOfProgram: releaseStatesOfProgram,
  9044. initAttributes: initAttributes,
  9045. enableAttribute: enableAttribute,
  9046. disableUnusedAttributes: disableUnusedAttributes
  9047. };
  9048. }
  9049. function WebGLBufferRenderer(gl, extensions, info, capabilities) {
  9050. const isWebGL2 = capabilities.isWebGL2;
  9051. let mode;
  9052. function setMode(value) {
  9053. mode = value;
  9054. }
  9055. function render(start, count) {
  9056. gl.drawArrays(mode, start, count);
  9057. info.update(count, mode, 1);
  9058. }
  9059. function renderInstances(start, count, primcount) {
  9060. if (primcount === 0) return;
  9061. let extension, methodName;
  9062. if (isWebGL2) {
  9063. extension = gl;
  9064. methodName = 'drawArraysInstanced';
  9065. } else {
  9066. extension = extensions.get('ANGLE_instanced_arrays');
  9067. methodName = 'drawArraysInstancedANGLE';
  9068. if (extension === null) {
  9069. console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  9070. return;
  9071. }
  9072. }
  9073. extension[methodName](mode, start, count, primcount);
  9074. info.update(count, mode, primcount);
  9075. } //
  9076. this.setMode = setMode;
  9077. this.render = render;
  9078. this.renderInstances = renderInstances;
  9079. }
  9080. function WebGLCapabilities(gl, extensions, parameters) {
  9081. let maxAnisotropy;
  9082. function getMaxAnisotropy() {
  9083. if (maxAnisotropy !== undefined) return maxAnisotropy;
  9084. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  9085. const extension = extensions.get('EXT_texture_filter_anisotropic');
  9086. maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  9087. } else {
  9088. maxAnisotropy = 0;
  9089. }
  9090. return maxAnisotropy;
  9091. }
  9092. function getMaxPrecision(precision) {
  9093. if (precision === 'highp') {
  9094. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT).precision > 0) {
  9095. return 'highp';
  9096. }
  9097. precision = 'mediump';
  9098. }
  9099. if (precision === 'mediump') {
  9100. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT).precision > 0) {
  9101. return 'mediump';
  9102. }
  9103. }
  9104. return 'lowp';
  9105. }
  9106. /* eslint-disable no-undef */
  9107. const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext || typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext;
  9108. /* eslint-enable no-undef */
  9109. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9110. const maxPrecision = getMaxPrecision(precision);
  9111. if (maxPrecision !== precision) {
  9112. console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
  9113. precision = maxPrecision;
  9114. }
  9115. const drawBuffers = isWebGL2 || extensions.has('WEBGL_draw_buffers');
  9116. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9117. const maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
  9118. const maxVertexTextures = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  9119. const maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
  9120. const maxCubemapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  9121. const maxAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  9122. const maxVertexUniforms = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS);
  9123. const maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS);
  9124. const maxFragmentUniforms = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  9125. const vertexTextures = maxVertexTextures > 0;
  9126. const floatFragmentTextures = isWebGL2 || extensions.has('OES_texture_float');
  9127. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  9128. const maxSamples = isWebGL2 ? gl.getParameter(gl.MAX_SAMPLES) : 0;
  9129. return {
  9130. isWebGL2: isWebGL2,
  9131. drawBuffers: drawBuffers,
  9132. getMaxAnisotropy: getMaxAnisotropy,
  9133. getMaxPrecision: getMaxPrecision,
  9134. precision: precision,
  9135. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9136. maxTextures: maxTextures,
  9137. maxVertexTextures: maxVertexTextures,
  9138. maxTextureSize: maxTextureSize,
  9139. maxCubemapSize: maxCubemapSize,
  9140. maxAttributes: maxAttributes,
  9141. maxVertexUniforms: maxVertexUniforms,
  9142. maxVaryings: maxVaryings,
  9143. maxFragmentUniforms: maxFragmentUniforms,
  9144. vertexTextures: vertexTextures,
  9145. floatFragmentTextures: floatFragmentTextures,
  9146. floatVertexTextures: floatVertexTextures,
  9147. maxSamples: maxSamples
  9148. };
  9149. }
  9150. function WebGLClipping(properties) {
  9151. const scope = this;
  9152. let globalState = null,
  9153. numGlobalPlanes = 0,
  9154. localClippingEnabled = false,
  9155. renderingShadows = false;
  9156. const plane = new Plane(),
  9157. viewNormalMatrix = new Matrix3(),
  9158. uniform = {
  9159. value: null,
  9160. needsUpdate: false
  9161. };
  9162. this.uniform = uniform;
  9163. this.numPlanes = 0;
  9164. this.numIntersection = 0;
  9165. this.init = function (planes, enableLocalClipping, camera) {
  9166. const enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to
  9167. // run another frame in order to reset the state:
  9168. numGlobalPlanes !== 0 || localClippingEnabled;
  9169. localClippingEnabled = enableLocalClipping;
  9170. globalState = projectPlanes(planes, camera, 0);
  9171. numGlobalPlanes = planes.length;
  9172. return enabled;
  9173. };
  9174. this.beginShadows = function () {
  9175. renderingShadows = true;
  9176. projectPlanes(null);
  9177. };
  9178. this.endShadows = function () {
  9179. renderingShadows = false;
  9180. resetGlobalState();
  9181. };
  9182. this.setState = function (material, camera, useCache) {
  9183. const planes = material.clippingPlanes,
  9184. clipIntersection = material.clipIntersection,
  9185. clipShadows = material.clipShadows;
  9186. const materialProperties = properties.get(material);
  9187. if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
  9188. // there's no local clipping
  9189. if (renderingShadows) {
  9190. // there's no global clipping
  9191. projectPlanes(null);
  9192. } else {
  9193. resetGlobalState();
  9194. }
  9195. } else {
  9196. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9197. lGlobal = nGlobal * 4;
  9198. let dstArray = materialProperties.clippingState || null;
  9199. uniform.value = dstArray; // ensure unique state
  9200. dstArray = projectPlanes(planes, camera, lGlobal, useCache);
  9201. for (let i = 0; i !== lGlobal; ++i) {
  9202. dstArray[i] = globalState[i];
  9203. }
  9204. materialProperties.clippingState = dstArray;
  9205. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9206. this.numPlanes += nGlobal;
  9207. }
  9208. };
  9209. function resetGlobalState() {
  9210. if (uniform.value !== globalState) {
  9211. uniform.value = globalState;
  9212. uniform.needsUpdate = numGlobalPlanes > 0;
  9213. }
  9214. scope.numPlanes = numGlobalPlanes;
  9215. scope.numIntersection = 0;
  9216. }
  9217. function projectPlanes(planes, camera, dstOffset, skipTransform) {
  9218. const nPlanes = planes !== null ? planes.length : 0;
  9219. let dstArray = null;
  9220. if (nPlanes !== 0) {
  9221. dstArray = uniform.value;
  9222. if (skipTransform !== true || dstArray === null) {
  9223. const flatSize = dstOffset + nPlanes * 4,
  9224. viewMatrix = camera.matrixWorldInverse;
  9225. viewNormalMatrix.getNormalMatrix(viewMatrix);
  9226. if (dstArray === null || dstArray.length < flatSize) {
  9227. dstArray = new Float32Array(flatSize);
  9228. }
  9229. for (let i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
  9230. plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
  9231. plane.normal.toArray(dstArray, i4);
  9232. dstArray[i4 + 3] = plane.constant;
  9233. }
  9234. }
  9235. uniform.value = dstArray;
  9236. uniform.needsUpdate = true;
  9237. }
  9238. scope.numPlanes = nPlanes;
  9239. scope.numIntersection = 0;
  9240. return dstArray;
  9241. }
  9242. }
  9243. function WebGLCubeMaps(renderer) {
  9244. let cubemaps = new WeakMap();
  9245. function mapTextureMapping(texture, mapping) {
  9246. if (mapping === EquirectangularReflectionMapping) {
  9247. texture.mapping = CubeReflectionMapping;
  9248. } else if (mapping === EquirectangularRefractionMapping) {
  9249. texture.mapping = CubeRefractionMapping;
  9250. }
  9251. return texture;
  9252. }
  9253. function get(texture) {
  9254. if (texture && texture.isTexture) {
  9255. const mapping = texture.mapping;
  9256. if (mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping) {
  9257. if (cubemaps.has(texture)) {
  9258. const cubemap = cubemaps.get(texture).texture;
  9259. return mapTextureMapping(cubemap, texture.mapping);
  9260. } else {
  9261. const image = texture.image;
  9262. if (image && image.height > 0) {
  9263. const currentRenderTarget = renderer.getRenderTarget();
  9264. const renderTarget = new WebGLCubeRenderTarget(image.height / 2);
  9265. renderTarget.fromEquirectangularTexture(renderer, texture);
  9266. cubemaps.set(texture, renderTarget);
  9267. renderer.setRenderTarget(currentRenderTarget);
  9268. texture.addEventListener('dispose', onTextureDispose);
  9269. return mapTextureMapping(renderTarget.texture, texture.mapping);
  9270. } else {
  9271. // image not yet ready. try the conversion next frame
  9272. return null;
  9273. }
  9274. }
  9275. }
  9276. }
  9277. return texture;
  9278. }
  9279. function onTextureDispose(event) {
  9280. const texture = event.target;
  9281. texture.removeEventListener('dispose', onTextureDispose);
  9282. const cubemap = cubemaps.get(texture);
  9283. if (cubemap !== undefined) {
  9284. cubemaps.delete(texture);
  9285. cubemap.dispose();
  9286. }
  9287. }
  9288. function dispose() {
  9289. cubemaps = new WeakMap();
  9290. }
  9291. return {
  9292. get: get,
  9293. dispose: dispose
  9294. };
  9295. }
  9296. function WebGLExtensions(gl) {
  9297. const extensions = {};
  9298. function getExtension(name) {
  9299. if (extensions[name] !== undefined) {
  9300. return extensions[name];
  9301. }
  9302. let extension;
  9303. switch (name) {
  9304. case 'WEBGL_depth_texture':
  9305. extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
  9306. break;
  9307. case 'EXT_texture_filter_anisotropic':
  9308. extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
  9309. break;
  9310. case 'WEBGL_compressed_texture_s3tc':
  9311. extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  9312. break;
  9313. case 'WEBGL_compressed_texture_pvrtc':
  9314. extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  9315. break;
  9316. default:
  9317. extension = gl.getExtension(name);
  9318. }
  9319. extensions[name] = extension;
  9320. return extension;
  9321. }
  9322. return {
  9323. has: function (name) {
  9324. return getExtension(name) !== null;
  9325. },
  9326. init: function (capabilities) {
  9327. if (capabilities.isWebGL2) {
  9328. getExtension('EXT_color_buffer_float');
  9329. } else {
  9330. getExtension('WEBGL_depth_texture');
  9331. getExtension('OES_texture_float');
  9332. getExtension('OES_texture_half_float');
  9333. getExtension('OES_texture_half_float_linear');
  9334. getExtension('OES_standard_derivatives');
  9335. getExtension('OES_element_index_uint');
  9336. getExtension('OES_vertex_array_object');
  9337. getExtension('ANGLE_instanced_arrays');
  9338. }
  9339. getExtension('OES_texture_float_linear');
  9340. getExtension('EXT_color_buffer_half_float');
  9341. },
  9342. get: function (name) {
  9343. const extension = getExtension(name);
  9344. if (extension === null) {
  9345. console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
  9346. }
  9347. return extension;
  9348. }
  9349. };
  9350. }
  9351. function WebGLGeometries(gl, attributes, info, bindingStates) {
  9352. const geometries = {};
  9353. const wireframeAttributes = new WeakMap();
  9354. function onGeometryDispose(event) {
  9355. const geometry = event.target;
  9356. if (geometry.index !== null) {
  9357. attributes.remove(geometry.index);
  9358. }
  9359. for (const name in geometry.attributes) {
  9360. attributes.remove(geometry.attributes[name]);
  9361. }
  9362. geometry.removeEventListener('dispose', onGeometryDispose);
  9363. delete geometries[geometry.id];
  9364. const attribute = wireframeAttributes.get(geometry);
  9365. if (attribute) {
  9366. attributes.remove(attribute);
  9367. wireframeAttributes.delete(geometry);
  9368. }
  9369. bindingStates.releaseStatesOfGeometry(geometry);
  9370. if (geometry.isInstancedBufferGeometry === true) {
  9371. delete geometry._maxInstanceCount;
  9372. } //
  9373. info.memory.geometries--;
  9374. }
  9375. function get(object, geometry) {
  9376. if (geometries[geometry.id] === true) return geometry;
  9377. geometry.addEventListener('dispose', onGeometryDispose);
  9378. geometries[geometry.id] = true;
  9379. info.memory.geometries++;
  9380. return geometry;
  9381. }
  9382. function update(geometry) {
  9383. const geometryAttributes = geometry.attributes; // Updating index buffer in VAO now. See WebGLBindingStates.
  9384. for (const name in geometryAttributes) {
  9385. attributes.update(geometryAttributes[name], gl.ARRAY_BUFFER);
  9386. } // morph targets
  9387. const morphAttributes = geometry.morphAttributes;
  9388. for (const name in morphAttributes) {
  9389. const array = morphAttributes[name];
  9390. for (let i = 0, l = array.length; i < l; i++) {
  9391. attributes.update(array[i], gl.ARRAY_BUFFER);
  9392. }
  9393. }
  9394. }
  9395. function updateWireframeAttribute(geometry) {
  9396. const indices = [];
  9397. const geometryIndex = geometry.index;
  9398. const geometryPosition = geometry.attributes.position;
  9399. let version = 0;
  9400. if (geometryIndex !== null) {
  9401. const array = geometryIndex.array;
  9402. version = geometryIndex.version;
  9403. for (let i = 0, l = array.length; i < l; i += 3) {
  9404. const a = array[i + 0];
  9405. const b = array[i + 1];
  9406. const c = array[i + 2];
  9407. indices.push(a, b, b, c, c, a);
  9408. }
  9409. } else {
  9410. const array = geometryPosition.array;
  9411. version = geometryPosition.version;
  9412. for (let i = 0, l = array.length / 3 - 1; i < l; i += 3) {
  9413. const a = i + 0;
  9414. const b = i + 1;
  9415. const c = i + 2;
  9416. indices.push(a, b, b, c, c, a);
  9417. }
  9418. }
  9419. const attribute = new (arrayMax(indices) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
  9420. attribute.version = version; // Updating index buffer in VAO now. See WebGLBindingStates
  9421. //
  9422. const previousAttribute = wireframeAttributes.get(geometry);
  9423. if (previousAttribute) attributes.remove(previousAttribute); //
  9424. wireframeAttributes.set(geometry, attribute);
  9425. }
  9426. function getWireframeAttribute(geometry) {
  9427. const currentAttribute = wireframeAttributes.get(geometry);
  9428. if (currentAttribute) {
  9429. const geometryIndex = geometry.index;
  9430. if (geometryIndex !== null) {
  9431. // if the attribute is obsolete, create a new one
  9432. if (currentAttribute.version < geometryIndex.version) {
  9433. updateWireframeAttribute(geometry);
  9434. }
  9435. }
  9436. } else {
  9437. updateWireframeAttribute(geometry);
  9438. }
  9439. return wireframeAttributes.get(geometry);
  9440. }
  9441. return {
  9442. get: get,
  9443. update: update,
  9444. getWireframeAttribute: getWireframeAttribute
  9445. };
  9446. }
  9447. function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
  9448. const isWebGL2 = capabilities.isWebGL2;
  9449. let mode;
  9450. function setMode(value) {
  9451. mode = value;
  9452. }
  9453. let type, bytesPerElement;
  9454. function setIndex(value) {
  9455. type = value.type;
  9456. bytesPerElement = value.bytesPerElement;
  9457. }
  9458. function render(start, count) {
  9459. gl.drawElements(mode, count, type, start * bytesPerElement);
  9460. info.update(count, mode, 1);
  9461. }
  9462. function renderInstances(start, count, primcount) {
  9463. if (primcount === 0) return;
  9464. let extension, methodName;
  9465. if (isWebGL2) {
  9466. extension = gl;
  9467. methodName = 'drawElementsInstanced';
  9468. } else {
  9469. extension = extensions.get('ANGLE_instanced_arrays');
  9470. methodName = 'drawElementsInstancedANGLE';
  9471. if (extension === null) {
  9472. console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  9473. return;
  9474. }
  9475. }
  9476. extension[methodName](mode, count, type, start * bytesPerElement, primcount);
  9477. info.update(count, mode, primcount);
  9478. } //
  9479. this.setMode = setMode;
  9480. this.setIndex = setIndex;
  9481. this.render = render;
  9482. this.renderInstances = renderInstances;
  9483. }
  9484. function WebGLInfo(gl) {
  9485. const memory = {
  9486. geometries: 0,
  9487. textures: 0
  9488. };
  9489. const render = {
  9490. frame: 0,
  9491. calls: 0,
  9492. triangles: 0,
  9493. points: 0,
  9494. lines: 0
  9495. };
  9496. function update(count, mode, instanceCount) {
  9497. render.calls++;
  9498. switch (mode) {
  9499. case gl.TRIANGLES:
  9500. render.triangles += instanceCount * (count / 3);
  9501. break;
  9502. case gl.LINES:
  9503. render.lines += instanceCount * (count / 2);
  9504. break;
  9505. case gl.LINE_STRIP:
  9506. render.lines += instanceCount * (count - 1);
  9507. break;
  9508. case gl.LINE_LOOP:
  9509. render.lines += instanceCount * count;
  9510. break;
  9511. case gl.POINTS:
  9512. render.points += instanceCount * count;
  9513. break;
  9514. default:
  9515. console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
  9516. break;
  9517. }
  9518. }
  9519. function reset() {
  9520. render.frame++;
  9521. render.calls = 0;
  9522. render.triangles = 0;
  9523. render.points = 0;
  9524. render.lines = 0;
  9525. }
  9526. return {
  9527. memory: memory,
  9528. render: render,
  9529. programs: null,
  9530. autoReset: true,
  9531. reset: reset,
  9532. update: update
  9533. };
  9534. }
  9535. function numericalSort(a, b) {
  9536. return a[0] - b[0];
  9537. }
  9538. function absNumericalSort(a, b) {
  9539. return Math.abs(b[1]) - Math.abs(a[1]);
  9540. }
  9541. function WebGLMorphtargets(gl) {
  9542. const influencesList = {};
  9543. const morphInfluences = new Float32Array(8);
  9544. const workInfluences = [];
  9545. for (let i = 0; i < 8; i++) {
  9546. workInfluences[i] = [i, 0];
  9547. }
  9548. function update(object, geometry, material, program) {
  9549. const objectInfluences = object.morphTargetInfluences; // When object doesn't have morph target influences defined, we treat it as a 0-length array
  9550. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  9551. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  9552. let influences = influencesList[geometry.id];
  9553. if (influences === undefined) {
  9554. // initialise list
  9555. influences = [];
  9556. for (let i = 0; i < length; i++) {
  9557. influences[i] = [i, 0];
  9558. }
  9559. influencesList[geometry.id] = influences;
  9560. } // Collect influences
  9561. for (let i = 0; i < length; i++) {
  9562. const influence = influences[i];
  9563. influence[0] = i;
  9564. influence[1] = objectInfluences[i];
  9565. }
  9566. influences.sort(absNumericalSort);
  9567. for (let i = 0; i < 8; i++) {
  9568. if (i < length && influences[i][1]) {
  9569. workInfluences[i][0] = influences[i][0];
  9570. workInfluences[i][1] = influences[i][1];
  9571. } else {
  9572. workInfluences[i][0] = Number.MAX_SAFE_INTEGER;
  9573. workInfluences[i][1] = 0;
  9574. }
  9575. }
  9576. workInfluences.sort(numericalSort);
  9577. const morphTargets = material.morphTargets && geometry.morphAttributes.position;
  9578. const morphNormals = material.morphNormals && geometry.morphAttributes.normal;
  9579. let morphInfluencesSum = 0;
  9580. for (let i = 0; i < 8; i++) {
  9581. const influence = workInfluences[i];
  9582. const index = influence[0];
  9583. const value = influence[1];
  9584. if (index !== Number.MAX_SAFE_INTEGER && value) {
  9585. if (morphTargets && geometry.getAttribute('morphTarget' + i) !== morphTargets[index]) {
  9586. geometry.setAttribute('morphTarget' + i, morphTargets[index]);
  9587. }
  9588. if (morphNormals && geometry.getAttribute('morphNormal' + i) !== morphNormals[index]) {
  9589. geometry.setAttribute('morphNormal' + i, morphNormals[index]);
  9590. }
  9591. morphInfluences[i] = value;
  9592. morphInfluencesSum += value;
  9593. } else {
  9594. if (morphTargets && geometry.hasAttribute('morphTarget' + i) === true) {
  9595. geometry.deleteAttribute('morphTarget' + i);
  9596. }
  9597. if (morphNormals && geometry.hasAttribute('morphNormal' + i) === true) {
  9598. geometry.deleteAttribute('morphNormal' + i);
  9599. }
  9600. morphInfluences[i] = 0;
  9601. }
  9602. } // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  9603. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  9604. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  9605. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  9606. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  9607. program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
  9608. }
  9609. return {
  9610. update: update
  9611. };
  9612. }
  9613. function WebGLObjects(gl, geometries, attributes, info) {
  9614. let updateMap = new WeakMap();
  9615. function update(object) {
  9616. const frame = info.render.frame;
  9617. const geometry = object.geometry;
  9618. const buffergeometry = geometries.get(object, geometry); // Update once per frame
  9619. if (updateMap.get(buffergeometry) !== frame) {
  9620. geometries.update(buffergeometry);
  9621. updateMap.set(buffergeometry, frame);
  9622. }
  9623. if (object.isInstancedMesh) {
  9624. if (object.hasEventListener('dispose', onInstancedMeshDispose) === false) {
  9625. object.addEventListener('dispose', onInstancedMeshDispose);
  9626. }
  9627. attributes.update(object.instanceMatrix, gl.ARRAY_BUFFER);
  9628. if (object.instanceColor !== null) {
  9629. attributes.update(object.instanceColor, gl.ARRAY_BUFFER);
  9630. }
  9631. }
  9632. return buffergeometry;
  9633. }
  9634. function dispose() {
  9635. updateMap = new WeakMap();
  9636. }
  9637. function onInstancedMeshDispose(event) {
  9638. const instancedMesh = event.target;
  9639. instancedMesh.removeEventListener('dispose', onInstancedMeshDispose);
  9640. attributes.remove(instancedMesh.instanceMatrix);
  9641. if (instancedMesh.instanceColor !== null) attributes.remove(instancedMesh.instanceColor);
  9642. }
  9643. return {
  9644. update: update,
  9645. dispose: dispose
  9646. };
  9647. }
  9648. class DataTexture2DArray extends Texture {
  9649. constructor(data = null, width = 1, height = 1, depth = 1) {
  9650. super(null);
  9651. this.image = {
  9652. data,
  9653. width,
  9654. height,
  9655. depth
  9656. };
  9657. this.magFilter = NearestFilter;
  9658. this.minFilter = NearestFilter;
  9659. this.wrapR = ClampToEdgeWrapping;
  9660. this.generateMipmaps = false;
  9661. this.flipY = false;
  9662. this.unpackAlignment = 1;
  9663. this.needsUpdate = true;
  9664. }
  9665. }
  9666. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  9667. class DataTexture3D extends Texture {
  9668. constructor(data = null, width = 1, height = 1, depth = 1) {
  9669. // We're going to add .setXXX() methods for setting properties later.
  9670. // Users can still set in DataTexture3D directly.
  9671. //
  9672. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  9673. // texture.anisotropy = 16;
  9674. //
  9675. // See #14839
  9676. super(null);
  9677. this.image = {
  9678. data,
  9679. width,
  9680. height,
  9681. depth
  9682. };
  9683. this.magFilter = NearestFilter;
  9684. this.minFilter = NearestFilter;
  9685. this.wrapR = ClampToEdgeWrapping;
  9686. this.generateMipmaps = false;
  9687. this.flipY = false;
  9688. this.unpackAlignment = 1;
  9689. this.needsUpdate = true;
  9690. }
  9691. }
  9692. DataTexture3D.prototype.isDataTexture3D = true;
  9693. /**
  9694. * Uniforms of a program.
  9695. * Those form a tree structure with a special top-level container for the root,
  9696. * which you get by calling 'new WebGLUniforms( gl, program )'.
  9697. *
  9698. *
  9699. * Properties of inner nodes including the top-level container:
  9700. *
  9701. * .seq - array of nested uniforms
  9702. * .map - nested uniforms by name
  9703. *
  9704. *
  9705. * Methods of all nodes except the top-level container:
  9706. *
  9707. * .setValue( gl, value, [textures] )
  9708. *
  9709. * uploads a uniform value(s)
  9710. * the 'textures' parameter is needed for sampler uniforms
  9711. *
  9712. *
  9713. * Static methods of the top-level container (textures factorizations):
  9714. *
  9715. * .upload( gl, seq, values, textures )
  9716. *
  9717. * sets uniforms in 'seq' to 'values[id].value'
  9718. *
  9719. * .seqWithValue( seq, values ) : filteredSeq
  9720. *
  9721. * filters 'seq' entries with corresponding entry in values
  9722. *
  9723. *
  9724. * Methods of the top-level container (textures factorizations):
  9725. *
  9726. * .setValue( gl, name, value, textures )
  9727. *
  9728. * sets uniform with name 'name' to 'value'
  9729. *
  9730. * .setOptional( gl, obj, prop )
  9731. *
  9732. * like .set for an optional property of the object
  9733. *
  9734. */
  9735. const emptyTexture = new Texture();
  9736. const emptyTexture2dArray = new DataTexture2DArray();
  9737. const emptyTexture3d = new DataTexture3D();
  9738. const emptyCubeTexture = new CubeTexture(); // --- Utilities ---
  9739. // Array Caches (provide typed arrays for temporary by size)
  9740. const arrayCacheF32 = [];
  9741. const arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms
  9742. const mat4array = new Float32Array(16);
  9743. const mat3array = new Float32Array(9);
  9744. const mat2array = new Float32Array(4); // Flattening for arrays of vectors and matrices
  9745. function flatten(array, nBlocks, blockSize) {
  9746. const firstElem = array[0];
  9747. if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )
  9748. // see http://jacksondunstan.com/articles/983
  9749. const n = nBlocks * blockSize;
  9750. let r = arrayCacheF32[n];
  9751. if (r === undefined) {
  9752. r = new Float32Array(n);
  9753. arrayCacheF32[n] = r;
  9754. }
  9755. if (nBlocks !== 0) {
  9756. firstElem.toArray(r, 0);
  9757. for (let i = 1, offset = 0; i !== nBlocks; ++i) {
  9758. offset += blockSize;
  9759. array[i].toArray(r, offset);
  9760. }
  9761. }
  9762. return r;
  9763. }
  9764. function arraysEqual(a, b) {
  9765. if (a.length !== b.length) return false;
  9766. for (let i = 0, l = a.length; i < l; i++) {
  9767. if (a[i] !== b[i]) return false;
  9768. }
  9769. return true;
  9770. }
  9771. function copyArray(a, b) {
  9772. for (let i = 0, l = b.length; i < l; i++) {
  9773. a[i] = b[i];
  9774. }
  9775. } // Texture unit allocation
  9776. function allocTexUnits(textures, n) {
  9777. let r = arrayCacheI32[n];
  9778. if (r === undefined) {
  9779. r = new Int32Array(n);
  9780. arrayCacheI32[n] = r;
  9781. }
  9782. for (let i = 0; i !== n; ++i) {
  9783. r[i] = textures.allocateTextureUnit();
  9784. }
  9785. return r;
  9786. } // --- Setters ---
  9787. // Note: Defining these methods externally, because they come in a bunch
  9788. // and this way their names minify.
  9789. // Single scalar
  9790. function setValueV1f(gl, v) {
  9791. const cache = this.cache;
  9792. if (cache[0] === v) return;
  9793. gl.uniform1f(this.addr, v);
  9794. cache[0] = v;
  9795. } // Single float vector (from flat array or THREE.VectorN)
  9796. function setValueV2f(gl, v) {
  9797. const cache = this.cache;
  9798. if (v.x !== undefined) {
  9799. if (cache[0] !== v.x || cache[1] !== v.y) {
  9800. gl.uniform2f(this.addr, v.x, v.y);
  9801. cache[0] = v.x;
  9802. cache[1] = v.y;
  9803. }
  9804. } else {
  9805. if (arraysEqual(cache, v)) return;
  9806. gl.uniform2fv(this.addr, v);
  9807. copyArray(cache, v);
  9808. }
  9809. }
  9810. function setValueV3f(gl, v) {
  9811. const cache = this.cache;
  9812. if (v.x !== undefined) {
  9813. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  9814. gl.uniform3f(this.addr, v.x, v.y, v.z);
  9815. cache[0] = v.x;
  9816. cache[1] = v.y;
  9817. cache[2] = v.z;
  9818. }
  9819. } else if (v.r !== undefined) {
  9820. if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
  9821. gl.uniform3f(this.addr, v.r, v.g, v.b);
  9822. cache[0] = v.r;
  9823. cache[1] = v.g;
  9824. cache[2] = v.b;
  9825. }
  9826. } else {
  9827. if (arraysEqual(cache, v)) return;
  9828. gl.uniform3fv(this.addr, v);
  9829. copyArray(cache, v);
  9830. }
  9831. }
  9832. function setValueV4f(gl, v) {
  9833. const cache = this.cache;
  9834. if (v.x !== undefined) {
  9835. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  9836. gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
  9837. cache[0] = v.x;
  9838. cache[1] = v.y;
  9839. cache[2] = v.z;
  9840. cache[3] = v.w;
  9841. }
  9842. } else {
  9843. if (arraysEqual(cache, v)) return;
  9844. gl.uniform4fv(this.addr, v);
  9845. copyArray(cache, v);
  9846. }
  9847. } // Single matrix (from flat array or THREE.MatrixN)
  9848. function setValueM2(gl, v) {
  9849. const cache = this.cache;
  9850. const elements = v.elements;
  9851. if (elements === undefined) {
  9852. if (arraysEqual(cache, v)) return;
  9853. gl.uniformMatrix2fv(this.addr, false, v);
  9854. copyArray(cache, v);
  9855. } else {
  9856. if (arraysEqual(cache, elements)) return;
  9857. mat2array.set(elements);
  9858. gl.uniformMatrix2fv(this.addr, false, mat2array);
  9859. copyArray(cache, elements);
  9860. }
  9861. }
  9862. function setValueM3(gl, v) {
  9863. const cache = this.cache;
  9864. const elements = v.elements;
  9865. if (elements === undefined) {
  9866. if (arraysEqual(cache, v)) return;
  9867. gl.uniformMatrix3fv(this.addr, false, v);
  9868. copyArray(cache, v);
  9869. } else {
  9870. if (arraysEqual(cache, elements)) return;
  9871. mat3array.set(elements);
  9872. gl.uniformMatrix3fv(this.addr, false, mat3array);
  9873. copyArray(cache, elements);
  9874. }
  9875. }
  9876. function setValueM4(gl, v) {
  9877. const cache = this.cache;
  9878. const elements = v.elements;
  9879. if (elements === undefined) {
  9880. if (arraysEqual(cache, v)) return;
  9881. gl.uniformMatrix4fv(this.addr, false, v);
  9882. copyArray(cache, v);
  9883. } else {
  9884. if (arraysEqual(cache, elements)) return;
  9885. mat4array.set(elements);
  9886. gl.uniformMatrix4fv(this.addr, false, mat4array);
  9887. copyArray(cache, elements);
  9888. }
  9889. } // Single integer / boolean
  9890. function setValueV1i(gl, v) {
  9891. const cache = this.cache;
  9892. if (cache[0] === v) return;
  9893. gl.uniform1i(this.addr, v);
  9894. cache[0] = v;
  9895. } // Single integer / boolean vector (from flat array)
  9896. function setValueV2i(gl, v) {
  9897. const cache = this.cache;
  9898. if (arraysEqual(cache, v)) return;
  9899. gl.uniform2iv(this.addr, v);
  9900. copyArray(cache, v);
  9901. }
  9902. function setValueV3i(gl, v) {
  9903. const cache = this.cache;
  9904. if (arraysEqual(cache, v)) return;
  9905. gl.uniform3iv(this.addr, v);
  9906. copyArray(cache, v);
  9907. }
  9908. function setValueV4i(gl, v) {
  9909. const cache = this.cache;
  9910. if (arraysEqual(cache, v)) return;
  9911. gl.uniform4iv(this.addr, v);
  9912. copyArray(cache, v);
  9913. } // Single unsigned integer
  9914. function setValueV1ui(gl, v) {
  9915. const cache = this.cache;
  9916. if (cache[0] === v) return;
  9917. gl.uniform1ui(this.addr, v);
  9918. cache[0] = v;
  9919. } // Single unsigned integer vector (from flat array)
  9920. function setValueV2ui(gl, v) {
  9921. const cache = this.cache;
  9922. if (arraysEqual(cache, v)) return;
  9923. gl.uniform2uiv(this.addr, v);
  9924. copyArray(cache, v);
  9925. }
  9926. function setValueV3ui(gl, v) {
  9927. const cache = this.cache;
  9928. if (arraysEqual(cache, v)) return;
  9929. gl.uniform3uiv(this.addr, v);
  9930. copyArray(cache, v);
  9931. }
  9932. function setValueV4ui(gl, v) {
  9933. const cache = this.cache;
  9934. if (arraysEqual(cache, v)) return;
  9935. gl.uniform4uiv(this.addr, v);
  9936. copyArray(cache, v);
  9937. } // Single texture (2D / Cube)
  9938. function setValueT1(gl, v, textures) {
  9939. const cache = this.cache;
  9940. const unit = textures.allocateTextureUnit();
  9941. if (cache[0] !== unit) {
  9942. gl.uniform1i(this.addr, unit);
  9943. cache[0] = unit;
  9944. }
  9945. textures.safeSetTexture2D(v || emptyTexture, unit);
  9946. }
  9947. function setValueT3D1(gl, v, textures) {
  9948. const cache = this.cache;
  9949. const unit = textures.allocateTextureUnit();
  9950. if (cache[0] !== unit) {
  9951. gl.uniform1i(this.addr, unit);
  9952. cache[0] = unit;
  9953. }
  9954. textures.setTexture3D(v || emptyTexture3d, unit);
  9955. }
  9956. function setValueT6(gl, v, textures) {
  9957. const cache = this.cache;
  9958. const unit = textures.allocateTextureUnit();
  9959. if (cache[0] !== unit) {
  9960. gl.uniform1i(this.addr, unit);
  9961. cache[0] = unit;
  9962. }
  9963. textures.safeSetTextureCube(v || emptyCubeTexture, unit);
  9964. }
  9965. function setValueT2DArray1(gl, v, textures) {
  9966. const cache = this.cache;
  9967. const unit = textures.allocateTextureUnit();
  9968. if (cache[0] !== unit) {
  9969. gl.uniform1i(this.addr, unit);
  9970. cache[0] = unit;
  9971. }
  9972. textures.setTexture2DArray(v || emptyTexture2dArray, unit);
  9973. } // Helper to pick the right setter for the singular case
  9974. function getSingularSetter(type) {
  9975. switch (type) {
  9976. case 0x1406:
  9977. return setValueV1f;
  9978. // FLOAT
  9979. case 0x8b50:
  9980. return setValueV2f;
  9981. // _VEC2
  9982. case 0x8b51:
  9983. return setValueV3f;
  9984. // _VEC3
  9985. case 0x8b52:
  9986. return setValueV4f;
  9987. // _VEC4
  9988. case 0x8b5a:
  9989. return setValueM2;
  9990. // _MAT2
  9991. case 0x8b5b:
  9992. return setValueM3;
  9993. // _MAT3
  9994. case 0x8b5c:
  9995. return setValueM4;
  9996. // _MAT4
  9997. case 0x1404:
  9998. case 0x8b56:
  9999. return setValueV1i;
  10000. // INT, BOOL
  10001. case 0x8b53:
  10002. case 0x8b57:
  10003. return setValueV2i;
  10004. // _VEC2
  10005. case 0x8b54:
  10006. case 0x8b58:
  10007. return setValueV3i;
  10008. // _VEC3
  10009. case 0x8b55:
  10010. case 0x8b59:
  10011. return setValueV4i;
  10012. // _VEC4
  10013. case 0x1405:
  10014. return setValueV1ui;
  10015. // UINT
  10016. case 0x8dc6:
  10017. return setValueV2ui;
  10018. // _VEC2
  10019. case 0x8dc7:
  10020. return setValueV3ui;
  10021. // _VEC3
  10022. case 0x8dc8:
  10023. return setValueV4ui;
  10024. // _VEC4
  10025. case 0x8b5e: // SAMPLER_2D
  10026. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10027. case 0x8dca: // INT_SAMPLER_2D
  10028. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10029. case 0x8b62:
  10030. // SAMPLER_2D_SHADOW
  10031. return setValueT1;
  10032. case 0x8b5f: // SAMPLER_3D
  10033. case 0x8dcb: // INT_SAMPLER_3D
  10034. case 0x8dd3:
  10035. // UNSIGNED_INT_SAMPLER_3D
  10036. return setValueT3D1;
  10037. case 0x8b60: // SAMPLER_CUBE
  10038. case 0x8dcc: // INT_SAMPLER_CUBE
  10039. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10040. case 0x8dc5:
  10041. // SAMPLER_CUBE_SHADOW
  10042. return setValueT6;
  10043. case 0x8dc1: // SAMPLER_2D_ARRAY
  10044. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10045. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10046. case 0x8dc4:
  10047. // SAMPLER_2D_ARRAY_SHADOW
  10048. return setValueT2DArray1;
  10049. }
  10050. } // Array of scalars
  10051. function setValueV1fArray(gl, v) {
  10052. gl.uniform1fv(this.addr, v);
  10053. } // Array of vectors (from flat array or array of THREE.VectorN)
  10054. function setValueV2fArray(gl, v) {
  10055. const data = flatten(v, this.size, 2);
  10056. gl.uniform2fv(this.addr, data);
  10057. }
  10058. function setValueV3fArray(gl, v) {
  10059. const data = flatten(v, this.size, 3);
  10060. gl.uniform3fv(this.addr, data);
  10061. }
  10062. function setValueV4fArray(gl, v) {
  10063. const data = flatten(v, this.size, 4);
  10064. gl.uniform4fv(this.addr, data);
  10065. } // Array of matrices (from flat array or array of THREE.MatrixN)
  10066. function setValueM2Array(gl, v) {
  10067. const data = flatten(v, this.size, 4);
  10068. gl.uniformMatrix2fv(this.addr, false, data);
  10069. }
  10070. function setValueM3Array(gl, v) {
  10071. const data = flatten(v, this.size, 9);
  10072. gl.uniformMatrix3fv(this.addr, false, data);
  10073. }
  10074. function setValueM4Array(gl, v) {
  10075. const data = flatten(v, this.size, 16);
  10076. gl.uniformMatrix4fv(this.addr, false, data);
  10077. } // Array of integer / boolean
  10078. function setValueV1iArray(gl, v) {
  10079. gl.uniform1iv(this.addr, v);
  10080. } // Array of integer / boolean vectors (from flat array)
  10081. function setValueV2iArray(gl, v) {
  10082. gl.uniform2iv(this.addr, v);
  10083. }
  10084. function setValueV3iArray(gl, v) {
  10085. gl.uniform3iv(this.addr, v);
  10086. }
  10087. function setValueV4iArray(gl, v) {
  10088. gl.uniform4iv(this.addr, v);
  10089. } // Array of unsigned integer
  10090. function setValueV1uiArray(gl, v) {
  10091. gl.uniform1uiv(this.addr, v);
  10092. } // Array of unsigned integer vectors (from flat array)
  10093. function setValueV2uiArray(gl, v) {
  10094. gl.uniform2uiv(this.addr, v);
  10095. }
  10096. function setValueV3uiArray(gl, v) {
  10097. gl.uniform3uiv(this.addr, v);
  10098. }
  10099. function setValueV4uiArray(gl, v) {
  10100. gl.uniform4uiv(this.addr, v);
  10101. } // Array of textures (2D / Cube)
  10102. function setValueT1Array(gl, v, textures) {
  10103. const n = v.length;
  10104. const units = allocTexUnits(textures, n);
  10105. gl.uniform1iv(this.addr, units);
  10106. for (let i = 0; i !== n; ++i) {
  10107. textures.safeSetTexture2D(v[i] || emptyTexture, units[i]);
  10108. }
  10109. }
  10110. function setValueT6Array(gl, v, textures) {
  10111. const n = v.length;
  10112. const units = allocTexUnits(textures, n);
  10113. gl.uniform1iv(this.addr, units);
  10114. for (let i = 0; i !== n; ++i) {
  10115. textures.safeSetTextureCube(v[i] || emptyCubeTexture, units[i]);
  10116. }
  10117. } // Helper to pick the right setter for a pure (bottom-level) array
  10118. function getPureArraySetter(type) {
  10119. switch (type) {
  10120. case 0x1406:
  10121. return setValueV1fArray;
  10122. // FLOAT
  10123. case 0x8b50:
  10124. return setValueV2fArray;
  10125. // _VEC2
  10126. case 0x8b51:
  10127. return setValueV3fArray;
  10128. // _VEC3
  10129. case 0x8b52:
  10130. return setValueV4fArray;
  10131. // _VEC4
  10132. case 0x8b5a:
  10133. return setValueM2Array;
  10134. // _MAT2
  10135. case 0x8b5b:
  10136. return setValueM3Array;
  10137. // _MAT3
  10138. case 0x8b5c:
  10139. return setValueM4Array;
  10140. // _MAT4
  10141. case 0x1404:
  10142. case 0x8b56:
  10143. return setValueV1iArray;
  10144. // INT, BOOL
  10145. case 0x8b53:
  10146. case 0x8b57:
  10147. return setValueV2iArray;
  10148. // _VEC2
  10149. case 0x8b54:
  10150. case 0x8b58:
  10151. return setValueV3iArray;
  10152. // _VEC3
  10153. case 0x8b55:
  10154. case 0x8b59:
  10155. return setValueV4iArray;
  10156. // _VEC4
  10157. case 0x1405:
  10158. return setValueV1uiArray;
  10159. // UINT
  10160. case 0x8dc6:
  10161. return setValueV2uiArray;
  10162. // _VEC2
  10163. case 0x8dc7:
  10164. return setValueV3uiArray;
  10165. // _VEC3
  10166. case 0x8dc8:
  10167. return setValueV4uiArray;
  10168. // _VEC4
  10169. case 0x8b5e: // SAMPLER_2D
  10170. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10171. case 0x8dca: // INT_SAMPLER_2D
  10172. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10173. case 0x8b62:
  10174. // SAMPLER_2D_SHADOW
  10175. return setValueT1Array;
  10176. case 0x8b60: // SAMPLER_CUBE
  10177. case 0x8dcc: // INT_SAMPLER_CUBE
  10178. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10179. case 0x8dc5:
  10180. // SAMPLER_CUBE_SHADOW
  10181. return setValueT6Array;
  10182. }
  10183. } // --- Uniform Classes ---
  10184. function SingleUniform(id, activeInfo, addr) {
  10185. this.id = id;
  10186. this.addr = addr;
  10187. this.cache = [];
  10188. this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  10189. }
  10190. function PureArrayUniform(id, activeInfo, addr) {
  10191. this.id = id;
  10192. this.addr = addr;
  10193. this.cache = [];
  10194. this.size = activeInfo.size;
  10195. this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  10196. }
  10197. PureArrayUniform.prototype.updateCache = function (data) {
  10198. const cache = this.cache;
  10199. if (data instanceof Float32Array && cache.length !== data.length) {
  10200. this.cache = new Float32Array(data.length);
  10201. }
  10202. copyArray(cache, data);
  10203. };
  10204. function StructuredUniform(id) {
  10205. this.id = id;
  10206. this.seq = [];
  10207. this.map = {};
  10208. }
  10209. StructuredUniform.prototype.setValue = function (gl, value, textures) {
  10210. const seq = this.seq;
  10211. for (let i = 0, n = seq.length; i !== n; ++i) {
  10212. const u = seq[i];
  10213. u.setValue(gl, value[u.id], textures);
  10214. }
  10215. }; // --- Top-level ---
  10216. // Parser - builds up the property tree from the path strings
  10217. const RePathPart = /(\w+)(\])?(\[|\.)?/g; // extracts
  10218. // - the identifier (member name or array index)
  10219. // - followed by an optional right bracket (found when array index)
  10220. // - followed by an optional left bracket or dot (type of subscript)
  10221. //
  10222. // Note: These portions can be read in a non-overlapping fashion and
  10223. // allow straightforward parsing of the hierarchy that WebGL encodes
  10224. // in the uniform names.
  10225. function addUniform(container, uniformObject) {
  10226. container.seq.push(uniformObject);
  10227. container.map[uniformObject.id] = uniformObject;
  10228. }
  10229. function parseUniform(activeInfo, addr, container) {
  10230. const path = activeInfo.name,
  10231. pathLength = path.length; // reset RegExp object, because of the early exit of a previous run
  10232. RePathPart.lastIndex = 0;
  10233. while (true) {
  10234. const match = RePathPart.exec(path),
  10235. matchEnd = RePathPart.lastIndex;
  10236. let id = match[1];
  10237. const idIsIndex = match[2] === ']',
  10238. subscript = match[3];
  10239. if (idIsIndex) id = id | 0; // convert to integer
  10240. if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
  10241. // bare name or "pure" bottom-level array "[0]" suffix
  10242. addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
  10243. break;
  10244. } else {
  10245. // step into inner node / create it in case it doesn't exist
  10246. const map = container.map;
  10247. let next = map[id];
  10248. if (next === undefined) {
  10249. next = new StructuredUniform(id);
  10250. addUniform(container, next);
  10251. }
  10252. container = next;
  10253. }
  10254. }
  10255. } // Root Container
  10256. function WebGLUniforms(gl, program) {
  10257. this.seq = [];
  10258. this.map = {};
  10259. const n = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  10260. for (let i = 0; i < n; ++i) {
  10261. const info = gl.getActiveUniform(program, i),
  10262. addr = gl.getUniformLocation(program, info.name);
  10263. parseUniform(info, addr, this);
  10264. }
  10265. }
  10266. WebGLUniforms.prototype.setValue = function (gl, name, value, textures) {
  10267. const u = this.map[name];
  10268. if (u !== undefined) u.setValue(gl, value, textures);
  10269. };
  10270. WebGLUniforms.prototype.setOptional = function (gl, object, name) {
  10271. const v = object[name];
  10272. if (v !== undefined) this.setValue(gl, name, v);
  10273. }; // Static interface
  10274. WebGLUniforms.upload = function (gl, seq, values, textures) {
  10275. for (let i = 0, n = seq.length; i !== n; ++i) {
  10276. const u = seq[i],
  10277. v = values[u.id];
  10278. if (v.needsUpdate !== false) {
  10279. // note: always updating when .needsUpdate is undefined
  10280. u.setValue(gl, v.value, textures);
  10281. }
  10282. }
  10283. };
  10284. WebGLUniforms.seqWithValue = function (seq, values) {
  10285. const r = [];
  10286. for (let i = 0, n = seq.length; i !== n; ++i) {
  10287. const u = seq[i];
  10288. if (u.id in values) r.push(u);
  10289. }
  10290. return r;
  10291. };
  10292. function WebGLShader(gl, type, string) {
  10293. const shader = gl.createShader(type);
  10294. gl.shaderSource(shader, string);
  10295. gl.compileShader(shader);
  10296. return shader;
  10297. }
  10298. let programIdCount = 0;
  10299. function addLineNumbers(string) {
  10300. const lines = string.split('\n');
  10301. for (let i = 0; i < lines.length; i++) {
  10302. lines[i] = i + 1 + ': ' + lines[i];
  10303. }
  10304. return lines.join('\n');
  10305. }
  10306. function getEncodingComponents(encoding) {
  10307. switch (encoding) {
  10308. case LinearEncoding:
  10309. return ['Linear', '( value )'];
  10310. case sRGBEncoding:
  10311. return ['sRGB', '( value )'];
  10312. case RGBEEncoding:
  10313. return ['RGBE', '( value )'];
  10314. case RGBM7Encoding:
  10315. return ['RGBM', '( value, 7.0 )'];
  10316. case RGBM16Encoding:
  10317. return ['RGBM', '( value, 16.0 )'];
  10318. case RGBDEncoding:
  10319. return ['RGBD', '( value, 256.0 )'];
  10320. case GammaEncoding:
  10321. return ['Gamma', '( value, float( GAMMA_FACTOR ) )'];
  10322. case LogLuvEncoding:
  10323. return ['LogLuv', '( value )'];
  10324. default:
  10325. console.warn('THREE.WebGLProgram: Unsupported encoding:', encoding);
  10326. return ['Linear', '( value )'];
  10327. }
  10328. }
  10329. function getShaderErrors(gl, shader, type) {
  10330. const status = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  10331. const log = gl.getShaderInfoLog(shader).trim();
  10332. if (status && log === '') return ''; // --enable-privileged-webgl-extension
  10333. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  10334. const source = gl.getShaderSource(shader);
  10335. return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers(source);
  10336. }
  10337. function getTexelDecodingFunction(functionName, encoding) {
  10338. const components = getEncodingComponents(encoding);
  10339. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[0] + 'ToLinear' + components[1] + '; }';
  10340. }
  10341. function getTexelEncodingFunction(functionName, encoding) {
  10342. const components = getEncodingComponents(encoding);
  10343. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
  10344. }
  10345. function getToneMappingFunction(functionName, toneMapping) {
  10346. let toneMappingName;
  10347. switch (toneMapping) {
  10348. case LinearToneMapping:
  10349. toneMappingName = 'Linear';
  10350. break;
  10351. case ReinhardToneMapping:
  10352. toneMappingName = 'Reinhard';
  10353. break;
  10354. case CineonToneMapping:
  10355. toneMappingName = 'OptimizedCineon';
  10356. break;
  10357. case ACESFilmicToneMapping:
  10358. toneMappingName = 'ACESFilmic';
  10359. break;
  10360. case CustomToneMapping:
  10361. toneMappingName = 'Custom';
  10362. break;
  10363. default:
  10364. console.warn('THREE.WebGLProgram: Unsupported toneMapping:', toneMapping);
  10365. toneMappingName = 'Linear';
  10366. }
  10367. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  10368. }
  10369. function generateExtensions(parameters) {
  10370. 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.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''];
  10371. return chunks.filter(filterEmptyLine).join('\n');
  10372. }
  10373. function generateDefines(defines) {
  10374. const chunks = [];
  10375. for (const name in defines) {
  10376. const value = defines[name];
  10377. if (value === false) continue;
  10378. chunks.push('#define ' + name + ' ' + value);
  10379. }
  10380. return chunks.join('\n');
  10381. }
  10382. function fetchAttributeLocations(gl, program) {
  10383. const attributes = {};
  10384. const n = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
  10385. for (let i = 0; i < n; i++) {
  10386. const info = gl.getActiveAttrib(program, i);
  10387. const name = info.name; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  10388. attributes[name] = gl.getAttribLocation(program, name);
  10389. }
  10390. return attributes;
  10391. }
  10392. function filterEmptyLine(string) {
  10393. return string !== '';
  10394. }
  10395. function replaceLightNums(string, parameters) {
  10396. 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);
  10397. }
  10398. function replaceClippingPlaneNums(string, parameters) {
  10399. return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
  10400. } // Resolve Includes
  10401. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  10402. function resolveIncludes(string) {
  10403. return string.replace(includePattern, includeReplacer);
  10404. }
  10405. function includeReplacer(match, include) {
  10406. const string = ShaderChunk[include];
  10407. if (string === undefined) {
  10408. throw new Error('Can not resolve #include <' + include + '>');
  10409. }
  10410. return resolveIncludes(string);
  10411. } // Unroll Loops
  10412. const deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  10413. 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;
  10414. function unrollLoops(string) {
  10415. return string.replace(unrollLoopPattern, loopReplacer).replace(deprecatedUnrollLoopPattern, deprecatedLoopReplacer);
  10416. }
  10417. function deprecatedLoopReplacer(match, start, end, snippet) {
  10418. console.warn('WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.');
  10419. return loopReplacer(match, start, end, snippet);
  10420. }
  10421. function loopReplacer(match, start, end, snippet) {
  10422. let string = '';
  10423. for (let i = parseInt(start); i < parseInt(end); i++) {
  10424. string += snippet.replace(/\[\s*i\s*\]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);
  10425. }
  10426. return string;
  10427. } //
  10428. function generatePrecision(parameters) {
  10429. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  10430. if (parameters.precision === 'highp') {
  10431. precisionstring += '\n#define HIGH_PRECISION';
  10432. } else if (parameters.precision === 'mediump') {
  10433. precisionstring += '\n#define MEDIUM_PRECISION';
  10434. } else if (parameters.precision === 'lowp') {
  10435. precisionstring += '\n#define LOW_PRECISION';
  10436. }
  10437. return precisionstring;
  10438. }
  10439. function generateShadowMapTypeDefine(parameters) {
  10440. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  10441. if (parameters.shadowMapType === PCFShadowMap) {
  10442. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  10443. } else if (parameters.shadowMapType === PCFSoftShadowMap) {
  10444. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  10445. } else if (parameters.shadowMapType === VSMShadowMap) {
  10446. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  10447. }
  10448. return shadowMapTypeDefine;
  10449. }
  10450. function generateEnvMapTypeDefine(parameters) {
  10451. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10452. if (parameters.envMap) {
  10453. switch (parameters.envMapMode) {
  10454. case CubeReflectionMapping:
  10455. case CubeRefractionMapping:
  10456. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10457. break;
  10458. case CubeUVReflectionMapping:
  10459. case CubeUVRefractionMapping:
  10460. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  10461. break;
  10462. }
  10463. }
  10464. return envMapTypeDefine;
  10465. }
  10466. function generateEnvMapModeDefine(parameters) {
  10467. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  10468. if (parameters.envMap) {
  10469. switch (parameters.envMapMode) {
  10470. case CubeRefractionMapping:
  10471. case CubeUVRefractionMapping:
  10472. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  10473. break;
  10474. }
  10475. }
  10476. return envMapModeDefine;
  10477. }
  10478. function generateEnvMapBlendingDefine(parameters) {
  10479. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  10480. if (parameters.envMap) {
  10481. switch (parameters.combine) {
  10482. case MultiplyOperation:
  10483. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  10484. break;
  10485. case MixOperation:
  10486. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  10487. break;
  10488. case AddOperation:
  10489. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  10490. break;
  10491. }
  10492. }
  10493. return envMapBlendingDefine;
  10494. }
  10495. function WebGLProgram(renderer, cacheKey, parameters, bindingStates) {
  10496. const gl = renderer.getContext();
  10497. const defines = parameters.defines;
  10498. let vertexShader = parameters.vertexShader;
  10499. let fragmentShader = parameters.fragmentShader;
  10500. const shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
  10501. const envMapTypeDefine = generateEnvMapTypeDefine(parameters);
  10502. const envMapModeDefine = generateEnvMapModeDefine(parameters);
  10503. const envMapBlendingDefine = generateEnvMapBlendingDefine(parameters);
  10504. const gammaFactorDefine = renderer.gammaFactor > 0 ? renderer.gammaFactor : 1.0;
  10505. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions(parameters);
  10506. const customDefines = generateDefines(defines);
  10507. const program = gl.createProgram();
  10508. let prefixVertex, prefixFragment;
  10509. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  10510. if (parameters.isRawShaderMaterial) {
  10511. prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
  10512. if (prefixVertex.length > 0) {
  10513. prefixVertex += '\n';
  10514. }
  10515. prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
  10516. if (prefixFragment.length > 0) {
  10517. prefixFragment += '\n';
  10518. }
  10519. } else {
  10520. prefixVertex = [generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.instancing ? '#define USE_INSTANCING' : '', parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '', parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', '#define GAMMA_FACTOR ' + gammaFactorDefine, '#define MAX_BONES ' + parameters.maxBones, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors ? '#define USE_COLOR' : '', parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.skinning ? '#define USE_SKINNING' : '', parameters.useVertexTexture ? '#define BONE_TEXTURE' : '', parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', parameters.doubleSided ? '#define DOUBLE_SIDED' : '', parameters.flipSided ? '#define FLIP_SIDED' : '', parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '', 'uniform mat4 modelMatrix;', 'uniform mat4 modelViewMatrix;', 'uniform mat4 projectionMatrix;', 'uniform mat4 viewMatrix;', 'uniform mat3 normalMatrix;', 'uniform vec3 cameraPosition;', 'uniform bool isOrthographic;', '#ifdef USE_INSTANCING', ' attribute mat4 instanceMatrix;', '#endif', '#ifdef USE_INSTANCING_COLOR', ' attribute vec3 instanceColor;', '#endif', 'attribute vec3 position;', 'attribute vec3 normal;', 'attribute vec2 uv;', '#ifdef USE_TANGENT', ' attribute vec4 tangent;', '#endif', '#if defined( USE_COLOR_ALPHA )', ' attribute vec4 color;', '#elif defined( USE_COLOR )', ' attribute vec3 color;', '#endif', '#ifdef USE_MORPHTARGETS', ' attribute vec3 morphTarget0;', ' attribute vec3 morphTarget1;', ' attribute vec3 morphTarget2;', ' attribute vec3 morphTarget3;', ' #ifdef USE_MORPHNORMALS', ' attribute vec3 morphNormal0;', ' attribute vec3 morphNormal1;', ' attribute vec3 morphNormal2;', ' attribute vec3 morphNormal3;', ' #else', ' attribute vec3 morphTarget4;', ' attribute vec3 morphTarget5;', ' attribute vec3 morphTarget6;', ' attribute vec3 morphTarget7;', ' #endif', '#endif', '#ifdef USE_SKINNING', ' attribute vec4 skinIndex;', ' attribute vec4 skinWeight;', '#endif', '\n'].filter(filterEmptyLine).join('\n');
  10521. prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + (parameters.alphaTest % 1 ? '' : '.0') : '', // add '.0' if integer
  10522. '#define GAMMA_FACTOR ' + gammaFactorDefine, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.matcap ? '#define USE_MATCAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapTypeDefine : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.envMap ? '#define ' + envMapBlendingDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.sheen ? '#define USE_SHEEN' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', 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
  10523. parameters.toneMapping !== NoToneMapping ? getToneMappingFunction('toneMapping', parameters.toneMapping) : '', parameters.dithering ? '#define DITHERING' : '', ShaderChunk['encodings_pars_fragment'], // this code is required here because it is used by the various encoding/decoding function defined below
  10524. parameters.map ? getTexelDecodingFunction('mapTexelToLinear', parameters.mapEncoding) : '', parameters.matcap ? getTexelDecodingFunction('matcapTexelToLinear', parameters.matcapEncoding) : '', parameters.envMap ? getTexelDecodingFunction('envMapTexelToLinear', parameters.envMapEncoding) : '', parameters.emissiveMap ? getTexelDecodingFunction('emissiveMapTexelToLinear', parameters.emissiveMapEncoding) : '', parameters.lightMap ? getTexelDecodingFunction('lightMapTexelToLinear', parameters.lightMapEncoding) : '', getTexelEncodingFunction('linearToOutputTexel', parameters.outputEncoding), parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', '\n'].filter(filterEmptyLine).join('\n');
  10525. }
  10526. vertexShader = resolveIncludes(vertexShader);
  10527. vertexShader = replaceLightNums(vertexShader, parameters);
  10528. vertexShader = replaceClippingPlaneNums(vertexShader, parameters);
  10529. fragmentShader = resolveIncludes(fragmentShader);
  10530. fragmentShader = replaceLightNums(fragmentShader, parameters);
  10531. fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);
  10532. vertexShader = unrollLoops(vertexShader);
  10533. fragmentShader = unrollLoops(fragmentShader);
  10534. if (parameters.isWebGL2 && parameters.isRawShaderMaterial !== true) {
  10535. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  10536. versionString = '#version 300 es\n';
  10537. prefixVertex = ['#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;
  10538. prefixFragment = ['#define varying in', parameters.glslVersion === GLSL3 ? '' : 'out highp vec4 pc_fragColor;', parameters.glslVersion === GLSL3 ? '' : '#define gl_FragColor pc_fragColor', '#define gl_FragDepthEXT gl_FragDepth', '#define texture2D texture', '#define textureCube texture', '#define texture2DProj textureProj', '#define texture2DLodEXT textureLod', '#define texture2DProjLodEXT textureProjLod', '#define textureCubeLodEXT textureLod', '#define texture2DGradEXT textureGrad', '#define texture2DProjGradEXT textureProjGrad', '#define textureCubeGradEXT textureGrad'].join('\n') + '\n' + prefixFragment;
  10539. }
  10540. const vertexGlsl = versionString + prefixVertex + vertexShader;
  10541. const fragmentGlsl = versionString + prefixFragment + fragmentShader; // console.log( '*VERTEX*', vertexGlsl );
  10542. // console.log( '*FRAGMENT*', fragmentGlsl );
  10543. const glVertexShader = WebGLShader(gl, gl.VERTEX_SHADER, vertexGlsl);
  10544. const glFragmentShader = WebGLShader(gl, gl.FRAGMENT_SHADER, fragmentGlsl);
  10545. gl.attachShader(program, glVertexShader);
  10546. gl.attachShader(program, glFragmentShader); // Force a particular attribute to index 0.
  10547. if (parameters.index0AttributeName !== undefined) {
  10548. gl.bindAttribLocation(program, 0, parameters.index0AttributeName);
  10549. } else if (parameters.morphTargets === true) {
  10550. // programs with morphTargets displace position out of attribute 0
  10551. gl.bindAttribLocation(program, 0, 'position');
  10552. }
  10553. gl.linkProgram(program); // check for link errors
  10554. if (renderer.debug.checkShaderErrors) {
  10555. const programLog = gl.getProgramInfoLog(program).trim();
  10556. const vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
  10557. const fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
  10558. let runnable = true;
  10559. let haveDiagnostics = true;
  10560. if (gl.getProgramParameter(program, gl.LINK_STATUS) === false) {
  10561. runnable = false;
  10562. const vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
  10563. const fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
  10564. console.error('THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors);
  10565. } else if (programLog !== '') {
  10566. console.warn('THREE.WebGLProgram: gl.getProgramInfoLog()', programLog);
  10567. } else if (vertexLog === '' || fragmentLog === '') {
  10568. haveDiagnostics = false;
  10569. }
  10570. if (haveDiagnostics) {
  10571. this.diagnostics = {
  10572. runnable: runnable,
  10573. programLog: programLog,
  10574. vertexShader: {
  10575. log: vertexLog,
  10576. prefix: prefixVertex
  10577. },
  10578. fragmentShader: {
  10579. log: fragmentLog,
  10580. prefix: prefixFragment
  10581. }
  10582. };
  10583. }
  10584. } // Clean up
  10585. // Crashes in iOS9 and iOS10. #18402
  10586. // gl.detachShader( program, glVertexShader );
  10587. // gl.detachShader( program, glFragmentShader );
  10588. gl.deleteShader(glVertexShader);
  10589. gl.deleteShader(glFragmentShader); // set up caching for uniform locations
  10590. let cachedUniforms;
  10591. this.getUniforms = function () {
  10592. if (cachedUniforms === undefined) {
  10593. cachedUniforms = new WebGLUniforms(gl, program);
  10594. }
  10595. return cachedUniforms;
  10596. }; // set up caching for attribute locations
  10597. let cachedAttributes;
  10598. this.getAttributes = function () {
  10599. if (cachedAttributes === undefined) {
  10600. cachedAttributes = fetchAttributeLocations(gl, program);
  10601. }
  10602. return cachedAttributes;
  10603. }; // free resource
  10604. this.destroy = function () {
  10605. bindingStates.releaseStatesOfProgram(this);
  10606. gl.deleteProgram(program);
  10607. this.program = undefined;
  10608. }; //
  10609. this.name = parameters.shaderName;
  10610. this.id = programIdCount++;
  10611. this.cacheKey = cacheKey;
  10612. this.usedTimes = 1;
  10613. this.program = program;
  10614. this.vertexShader = glVertexShader;
  10615. this.fragmentShader = glFragmentShader;
  10616. return this;
  10617. }
  10618. function WebGLPrograms(renderer, cubemaps, extensions, capabilities, bindingStates, clipping) {
  10619. const programs = [];
  10620. const isWebGL2 = capabilities.isWebGL2;
  10621. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  10622. const floatVertexTextures = capabilities.floatVertexTextures;
  10623. const maxVertexUniforms = capabilities.maxVertexUniforms;
  10624. const vertexTextures = capabilities.vertexTextures;
  10625. let precision = capabilities.precision;
  10626. const shaderIDs = {
  10627. MeshDepthMaterial: 'depth',
  10628. MeshDistanceMaterial: 'distanceRGBA',
  10629. MeshNormalMaterial: 'normal',
  10630. MeshBasicMaterial: 'basic',
  10631. MeshLambertMaterial: 'lambert',
  10632. MeshPhongMaterial: 'phong',
  10633. MeshToonMaterial: 'toon',
  10634. MeshStandardMaterial: 'physical',
  10635. MeshPhysicalMaterial: 'physical',
  10636. MeshMatcapMaterial: 'matcap',
  10637. LineBasicMaterial: 'basic',
  10638. LineDashedMaterial: 'dashed',
  10639. PointsMaterial: 'points',
  10640. ShadowMaterial: 'shadow',
  10641. SpriteMaterial: 'sprite'
  10642. };
  10643. const parameterNames = ['precision', 'isWebGL2', 'supportsVertexTextures', 'outputEncoding', 'instancing', 'instancingColor', 'map', 'mapEncoding', 'matcap', 'matcapEncoding', 'envMap', 'envMapMode', 'envMapEncoding', 'envMapCubeUV', 'lightMap', 'lightMapEncoding', 'aoMap', 'emissiveMap', 'emissiveMapEncoding', 'bumpMap', 'normalMap', 'objectSpaceNormalMap', 'tangentSpaceNormalMap', 'clearcoatMap', 'clearcoatRoughnessMap', 'clearcoatNormalMap', 'displacementMap', 'specularMap', 'roughnessMap', 'metalnessMap', 'gradientMap', 'alphaMap', 'combine', 'vertexColors', 'vertexAlphas', 'vertexTangents', 'vertexUvs', 'uvsVertexOnly', 'fog', 'useFog', 'fogExp2', 'flatShading', 'sizeAttenuation', 'logarithmicDepthBuffer', 'skinning', 'maxBones', 'useVertexTexture', 'morphTargets', 'morphNormals', 'premultipliedAlpha', 'numDirLights', 'numPointLights', 'numSpotLights', 'numHemiLights', 'numRectAreaLights', 'numDirLightShadows', 'numPointLightShadows', 'numSpotLightShadows', 'shadowMapEnabled', 'shadowMapType', 'toneMapping', 'physicallyCorrectLights', 'alphaTest', 'doubleSided', 'flipSided', 'numClippingPlanes', 'numClipIntersection', 'depthPacking', 'dithering', 'sheen', 'transmissionMap'];
  10644. function getMaxBones(object) {
  10645. const skeleton = object.skeleton;
  10646. const bones = skeleton.bones;
  10647. if (floatVertexTextures) {
  10648. return 1024;
  10649. } else {
  10650. // default for when object is not specified
  10651. // ( for example when prebuilding shader to be used with multiple objects )
  10652. //
  10653. // - leave some extra space for other uniforms
  10654. // - limit here is ANGLE's 254 max uniform vectors
  10655. // (up to 54 should be safe)
  10656. const nVertexUniforms = maxVertexUniforms;
  10657. const nVertexMatrices = Math.floor((nVertexUniforms - 20) / 4);
  10658. const maxBones = Math.min(nVertexMatrices, bones.length);
  10659. if (maxBones < bones.length) {
  10660. console.warn('THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.');
  10661. return 0;
  10662. }
  10663. return maxBones;
  10664. }
  10665. }
  10666. function getTextureEncodingFromMap(map) {
  10667. let encoding;
  10668. if (map && map.isTexture) {
  10669. encoding = map.encoding;
  10670. } else if (map && map.isWebGLRenderTarget) {
  10671. console.warn('THREE.WebGLPrograms.getTextureEncodingFromMap: don\'t use render targets as textures. Use their .texture property instead.');
  10672. encoding = map.texture.encoding;
  10673. } else {
  10674. encoding = LinearEncoding;
  10675. }
  10676. return encoding;
  10677. }
  10678. function getParameters(material, lights, shadows, scene, object) {
  10679. const fog = scene.fog;
  10680. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  10681. const envMap = cubemaps.get(material.envMap || environment);
  10682. const shaderID = shaderIDs[material.type]; // heuristics to create shader parameters according to lights in the scene
  10683. // (not to blow over maxLights budget)
  10684. const maxBones = object.isSkinnedMesh ? getMaxBones(object) : 0;
  10685. if (material.precision !== null) {
  10686. precision = capabilities.getMaxPrecision(material.precision);
  10687. if (precision !== material.precision) {
  10688. console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
  10689. }
  10690. }
  10691. let vertexShader, fragmentShader;
  10692. if (shaderID) {
  10693. const shader = ShaderLib[shaderID];
  10694. vertexShader = shader.vertexShader;
  10695. fragmentShader = shader.fragmentShader;
  10696. } else {
  10697. vertexShader = material.vertexShader;
  10698. fragmentShader = material.fragmentShader;
  10699. }
  10700. const currentRenderTarget = renderer.getRenderTarget();
  10701. const parameters = {
  10702. isWebGL2: isWebGL2,
  10703. shaderID: shaderID,
  10704. shaderName: material.type,
  10705. vertexShader: vertexShader,
  10706. fragmentShader: fragmentShader,
  10707. defines: material.defines,
  10708. isRawShaderMaterial: material.isRawShaderMaterial === true,
  10709. glslVersion: material.glslVersion,
  10710. precision: precision,
  10711. instancing: object.isInstancedMesh === true,
  10712. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  10713. supportsVertexTextures: vertexTextures,
  10714. outputEncoding: currentRenderTarget !== null ? getTextureEncodingFromMap(currentRenderTarget.texture) : renderer.outputEncoding,
  10715. map: !!material.map,
  10716. mapEncoding: getTextureEncodingFromMap(material.map),
  10717. matcap: !!material.matcap,
  10718. matcapEncoding: getTextureEncodingFromMap(material.matcap),
  10719. envMap: !!envMap,
  10720. envMapMode: envMap && envMap.mapping,
  10721. envMapEncoding: getTextureEncodingFromMap(envMap),
  10722. envMapCubeUV: !!envMap && (envMap.mapping === CubeUVReflectionMapping || envMap.mapping === CubeUVRefractionMapping),
  10723. lightMap: !!material.lightMap,
  10724. lightMapEncoding: getTextureEncodingFromMap(material.lightMap),
  10725. aoMap: !!material.aoMap,
  10726. emissiveMap: !!material.emissiveMap,
  10727. emissiveMapEncoding: getTextureEncodingFromMap(material.emissiveMap),
  10728. bumpMap: !!material.bumpMap,
  10729. normalMap: !!material.normalMap,
  10730. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  10731. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  10732. clearcoatMap: !!material.clearcoatMap,
  10733. clearcoatRoughnessMap: !!material.clearcoatRoughnessMap,
  10734. clearcoatNormalMap: !!material.clearcoatNormalMap,
  10735. displacementMap: !!material.displacementMap,
  10736. roughnessMap: !!material.roughnessMap,
  10737. metalnessMap: !!material.metalnessMap,
  10738. specularMap: !!material.specularMap,
  10739. alphaMap: !!material.alphaMap,
  10740. gradientMap: !!material.gradientMap,
  10741. sheen: !!material.sheen,
  10742. transmissionMap: !!material.transmissionMap,
  10743. combine: material.combine,
  10744. vertexTangents: material.normalMap && material.vertexTangents,
  10745. vertexColors: material.vertexColors,
  10746. vertexAlphas: material.vertexColors === true && object.geometry && object.geometry.attributes.color && object.geometry.attributes.color.itemSize === 4,
  10747. 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,
  10748. uvsVertexOnly: !(!!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatNormalMap || !!material.transmissionMap) && !!material.displacementMap,
  10749. fog: !!fog,
  10750. useFog: material.fog,
  10751. fogExp2: fog && fog.isFogExp2,
  10752. flatShading: !!material.flatShading,
  10753. sizeAttenuation: material.sizeAttenuation,
  10754. logarithmicDepthBuffer: logarithmicDepthBuffer,
  10755. skinning: object.isSkinnedMesh === true && maxBones > 0,
  10756. maxBones: maxBones,
  10757. useVertexTexture: floatVertexTextures,
  10758. morphTargets: material.morphTargets,
  10759. morphNormals: material.morphNormals,
  10760. numDirLights: lights.directional.length,
  10761. numPointLights: lights.point.length,
  10762. numSpotLights: lights.spot.length,
  10763. numRectAreaLights: lights.rectArea.length,
  10764. numHemiLights: lights.hemi.length,
  10765. numDirLightShadows: lights.directionalShadowMap.length,
  10766. numPointLightShadows: lights.pointShadowMap.length,
  10767. numSpotLightShadows: lights.spotShadowMap.length,
  10768. numClippingPlanes: clipping.numPlanes,
  10769. numClipIntersection: clipping.numIntersection,
  10770. dithering: material.dithering,
  10771. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  10772. shadowMapType: renderer.shadowMap.type,
  10773. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  10774. physicallyCorrectLights: renderer.physicallyCorrectLights,
  10775. premultipliedAlpha: material.premultipliedAlpha,
  10776. alphaTest: material.alphaTest,
  10777. doubleSided: material.side === DoubleSide,
  10778. flipSided: material.side === BackSide,
  10779. depthPacking: material.depthPacking !== undefined ? material.depthPacking : false,
  10780. index0AttributeName: material.index0AttributeName,
  10781. extensionDerivatives: material.extensions && material.extensions.derivatives,
  10782. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  10783. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  10784. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  10785. rendererExtensionFragDepth: isWebGL2 || extensions.has('EXT_frag_depth'),
  10786. rendererExtensionDrawBuffers: isWebGL2 || extensions.has('WEBGL_draw_buffers'),
  10787. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has('EXT_shader_texture_lod'),
  10788. customProgramCacheKey: material.customProgramCacheKey()
  10789. };
  10790. return parameters;
  10791. }
  10792. function getProgramCacheKey(parameters) {
  10793. const array = [];
  10794. if (parameters.shaderID) {
  10795. array.push(parameters.shaderID);
  10796. } else {
  10797. array.push(parameters.fragmentShader);
  10798. array.push(parameters.vertexShader);
  10799. }
  10800. if (parameters.defines !== undefined) {
  10801. for (const name in parameters.defines) {
  10802. array.push(name);
  10803. array.push(parameters.defines[name]);
  10804. }
  10805. }
  10806. if (parameters.isRawShaderMaterial === false) {
  10807. for (let i = 0; i < parameterNames.length; i++) {
  10808. array.push(parameters[parameterNames[i]]);
  10809. }
  10810. array.push(renderer.outputEncoding);
  10811. array.push(renderer.gammaFactor);
  10812. }
  10813. array.push(parameters.customProgramCacheKey);
  10814. return array.join();
  10815. }
  10816. function getUniforms(material) {
  10817. const shaderID = shaderIDs[material.type];
  10818. let uniforms;
  10819. if (shaderID) {
  10820. const shader = ShaderLib[shaderID];
  10821. uniforms = UniformsUtils.clone(shader.uniforms);
  10822. } else {
  10823. uniforms = material.uniforms;
  10824. }
  10825. return uniforms;
  10826. }
  10827. function acquireProgram(parameters, cacheKey) {
  10828. let program; // Check if code has been already compiled
  10829. for (let p = 0, pl = programs.length; p < pl; p++) {
  10830. const preexistingProgram = programs[p];
  10831. if (preexistingProgram.cacheKey === cacheKey) {
  10832. program = preexistingProgram;
  10833. ++program.usedTimes;
  10834. break;
  10835. }
  10836. }
  10837. if (program === undefined) {
  10838. program = new WebGLProgram(renderer, cacheKey, parameters, bindingStates);
  10839. programs.push(program);
  10840. }
  10841. return program;
  10842. }
  10843. function releaseProgram(program) {
  10844. if (--program.usedTimes === 0) {
  10845. // Remove from unordered set
  10846. const i = programs.indexOf(program);
  10847. programs[i] = programs[programs.length - 1];
  10848. programs.pop(); // Free WebGL resources
  10849. program.destroy();
  10850. }
  10851. }
  10852. return {
  10853. getParameters: getParameters,
  10854. getProgramCacheKey: getProgramCacheKey,
  10855. getUniforms: getUniforms,
  10856. acquireProgram: acquireProgram,
  10857. releaseProgram: releaseProgram,
  10858. // Exposed for resource monitoring & error feedback via renderer.info:
  10859. programs: programs
  10860. };
  10861. }
  10862. function WebGLProperties() {
  10863. let properties = new WeakMap();
  10864. function get(object) {
  10865. let map = properties.get(object);
  10866. if (map === undefined) {
  10867. map = {};
  10868. properties.set(object, map);
  10869. }
  10870. return map;
  10871. }
  10872. function remove(object) {
  10873. properties.delete(object);
  10874. }
  10875. function update(object, key, value) {
  10876. properties.get(object)[key] = value;
  10877. }
  10878. function dispose() {
  10879. properties = new WeakMap();
  10880. }
  10881. return {
  10882. get: get,
  10883. remove: remove,
  10884. update: update,
  10885. dispose: dispose
  10886. };
  10887. }
  10888. function painterSortStable(a, b) {
  10889. if (a.groupOrder !== b.groupOrder) {
  10890. return a.groupOrder - b.groupOrder;
  10891. } else if (a.renderOrder !== b.renderOrder) {
  10892. return a.renderOrder - b.renderOrder;
  10893. } else if (a.program !== b.program) {
  10894. return a.program.id - b.program.id;
  10895. } else if (a.material.id !== b.material.id) {
  10896. return a.material.id - b.material.id;
  10897. } else if (a.z !== b.z) {
  10898. return a.z - b.z;
  10899. } else {
  10900. return a.id - b.id;
  10901. }
  10902. }
  10903. function reversePainterSortStable(a, b) {
  10904. if (a.groupOrder !== b.groupOrder) {
  10905. return a.groupOrder - b.groupOrder;
  10906. } else if (a.renderOrder !== b.renderOrder) {
  10907. return a.renderOrder - b.renderOrder;
  10908. } else if (a.z !== b.z) {
  10909. return b.z - a.z;
  10910. } else {
  10911. return a.id - b.id;
  10912. }
  10913. }
  10914. function WebGLRenderList(properties) {
  10915. const renderItems = [];
  10916. let renderItemsIndex = 0;
  10917. const opaque = [];
  10918. const transparent = [];
  10919. const defaultProgram = {
  10920. id: -1
  10921. };
  10922. function init() {
  10923. renderItemsIndex = 0;
  10924. opaque.length = 0;
  10925. transparent.length = 0;
  10926. }
  10927. function getNextRenderItem(object, geometry, material, groupOrder, z, group) {
  10928. let renderItem = renderItems[renderItemsIndex];
  10929. const materialProperties = properties.get(material);
  10930. if (renderItem === undefined) {
  10931. renderItem = {
  10932. id: object.id,
  10933. object: object,
  10934. geometry: geometry,
  10935. material: material,
  10936. program: materialProperties.program || defaultProgram,
  10937. groupOrder: groupOrder,
  10938. renderOrder: object.renderOrder,
  10939. z: z,
  10940. group: group
  10941. };
  10942. renderItems[renderItemsIndex] = renderItem;
  10943. } else {
  10944. renderItem.id = object.id;
  10945. renderItem.object = object;
  10946. renderItem.geometry = geometry;
  10947. renderItem.material = material;
  10948. renderItem.program = materialProperties.program || defaultProgram;
  10949. renderItem.groupOrder = groupOrder;
  10950. renderItem.renderOrder = object.renderOrder;
  10951. renderItem.z = z;
  10952. renderItem.group = group;
  10953. }
  10954. renderItemsIndex++;
  10955. return renderItem;
  10956. }
  10957. function push(object, geometry, material, groupOrder, z, group) {
  10958. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  10959. (material.transparent === true ? transparent : opaque).push(renderItem);
  10960. }
  10961. function unshift(object, geometry, material, groupOrder, z, group) {
  10962. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  10963. (material.transparent === true ? transparent : opaque).unshift(renderItem);
  10964. }
  10965. function sort(customOpaqueSort, customTransparentSort) {
  10966. if (opaque.length > 1) opaque.sort(customOpaqueSort || painterSortStable);
  10967. if (transparent.length > 1) transparent.sort(customTransparentSort || reversePainterSortStable);
  10968. }
  10969. function finish() {
  10970. // Clear references from inactive renderItems in the list
  10971. for (let i = renderItemsIndex, il = renderItems.length; i < il; i++) {
  10972. const renderItem = renderItems[i];
  10973. if (renderItem.id === null) break;
  10974. renderItem.id = null;
  10975. renderItem.object = null;
  10976. renderItem.geometry = null;
  10977. renderItem.material = null;
  10978. renderItem.program = null;
  10979. renderItem.group = null;
  10980. }
  10981. }
  10982. return {
  10983. opaque: opaque,
  10984. transparent: transparent,
  10985. init: init,
  10986. push: push,
  10987. unshift: unshift,
  10988. finish: finish,
  10989. sort: sort
  10990. };
  10991. }
  10992. function WebGLRenderLists(properties) {
  10993. let lists = new WeakMap();
  10994. function get(scene, renderCallDepth) {
  10995. let list;
  10996. if (lists.has(scene) === false) {
  10997. list = new WebGLRenderList(properties);
  10998. lists.set(scene, [list]);
  10999. } else {
  11000. if (renderCallDepth >= lists.get(scene).length) {
  11001. list = new WebGLRenderList(properties);
  11002. lists.get(scene).push(list);
  11003. } else {
  11004. list = lists.get(scene)[renderCallDepth];
  11005. }
  11006. }
  11007. return list;
  11008. }
  11009. function dispose() {
  11010. lists = new WeakMap();
  11011. }
  11012. return {
  11013. get: get,
  11014. dispose: dispose
  11015. };
  11016. }
  11017. function UniformsCache() {
  11018. const lights = {};
  11019. return {
  11020. get: function (light) {
  11021. if (lights[light.id] !== undefined) {
  11022. return lights[light.id];
  11023. }
  11024. let uniforms;
  11025. switch (light.type) {
  11026. case 'DirectionalLight':
  11027. uniforms = {
  11028. direction: new Vector3(),
  11029. color: new Color()
  11030. };
  11031. break;
  11032. case 'SpotLight':
  11033. uniforms = {
  11034. position: new Vector3(),
  11035. direction: new Vector3(),
  11036. color: new Color(),
  11037. distance: 0,
  11038. coneCos: 0,
  11039. penumbraCos: 0,
  11040. decay: 0
  11041. };
  11042. break;
  11043. case 'PointLight':
  11044. uniforms = {
  11045. position: new Vector3(),
  11046. color: new Color(),
  11047. distance: 0,
  11048. decay: 0
  11049. };
  11050. break;
  11051. case 'HemisphereLight':
  11052. uniforms = {
  11053. direction: new Vector3(),
  11054. skyColor: new Color(),
  11055. groundColor: new Color()
  11056. };
  11057. break;
  11058. case 'RectAreaLight':
  11059. uniforms = {
  11060. color: new Color(),
  11061. position: new Vector3(),
  11062. halfWidth: new Vector3(),
  11063. halfHeight: new Vector3()
  11064. };
  11065. break;
  11066. }
  11067. lights[light.id] = uniforms;
  11068. return uniforms;
  11069. }
  11070. };
  11071. }
  11072. function ShadowUniformsCache() {
  11073. const lights = {};
  11074. return {
  11075. get: function (light) {
  11076. if (lights[light.id] !== undefined) {
  11077. return lights[light.id];
  11078. }
  11079. let uniforms;
  11080. switch (light.type) {
  11081. case 'DirectionalLight':
  11082. uniforms = {
  11083. shadowBias: 0,
  11084. shadowNormalBias: 0,
  11085. shadowRadius: 1,
  11086. shadowMapSize: new Vector2()
  11087. };
  11088. break;
  11089. case 'SpotLight':
  11090. uniforms = {
  11091. shadowBias: 0,
  11092. shadowNormalBias: 0,
  11093. shadowRadius: 1,
  11094. shadowMapSize: new Vector2()
  11095. };
  11096. break;
  11097. case 'PointLight':
  11098. uniforms = {
  11099. shadowBias: 0,
  11100. shadowNormalBias: 0,
  11101. shadowRadius: 1,
  11102. shadowMapSize: new Vector2(),
  11103. shadowCameraNear: 1,
  11104. shadowCameraFar: 1000
  11105. };
  11106. break;
  11107. // TODO (abelnation): set RectAreaLight shadow uniforms
  11108. }
  11109. lights[light.id] = uniforms;
  11110. return uniforms;
  11111. }
  11112. };
  11113. }
  11114. let nextVersion = 0;
  11115. function shadowCastingLightsFirst(lightA, lightB) {
  11116. return (lightB.castShadow ? 1 : 0) - (lightA.castShadow ? 1 : 0);
  11117. }
  11118. function WebGLLights(extensions, capabilities) {
  11119. const cache = new UniformsCache();
  11120. const shadowCache = ShadowUniformsCache();
  11121. const state = {
  11122. version: 0,
  11123. hash: {
  11124. directionalLength: -1,
  11125. pointLength: -1,
  11126. spotLength: -1,
  11127. rectAreaLength: -1,
  11128. hemiLength: -1,
  11129. numDirectionalShadows: -1,
  11130. numPointShadows: -1,
  11131. numSpotShadows: -1
  11132. },
  11133. ambient: [0, 0, 0],
  11134. probe: [],
  11135. directional: [],
  11136. directionalShadow: [],
  11137. directionalShadowMap: [],
  11138. directionalShadowMatrix: [],
  11139. spot: [],
  11140. spotShadow: [],
  11141. spotShadowMap: [],
  11142. spotShadowMatrix: [],
  11143. rectArea: [],
  11144. rectAreaLTC1: null,
  11145. rectAreaLTC2: null,
  11146. point: [],
  11147. pointShadow: [],
  11148. pointShadowMap: [],
  11149. pointShadowMatrix: [],
  11150. hemi: []
  11151. };
  11152. for (let i = 0; i < 9; i++) state.probe.push(new Vector3());
  11153. const vector3 = new Vector3();
  11154. const matrix4 = new Matrix4();
  11155. const matrix42 = new Matrix4();
  11156. function setup(lights) {
  11157. let r = 0,
  11158. g = 0,
  11159. b = 0;
  11160. for (let i = 0; i < 9; i++) state.probe[i].set(0, 0, 0);
  11161. let directionalLength = 0;
  11162. let pointLength = 0;
  11163. let spotLength = 0;
  11164. let rectAreaLength = 0;
  11165. let hemiLength = 0;
  11166. let numDirectionalShadows = 0;
  11167. let numPointShadows = 0;
  11168. let numSpotShadows = 0;
  11169. lights.sort(shadowCastingLightsFirst);
  11170. for (let i = 0, l = lights.length; i < l; i++) {
  11171. const light = lights[i];
  11172. const color = light.color;
  11173. const intensity = light.intensity;
  11174. const distance = light.distance;
  11175. const shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
  11176. if (light.isAmbientLight) {
  11177. r += color.r * intensity;
  11178. g += color.g * intensity;
  11179. b += color.b * intensity;
  11180. } else if (light.isLightProbe) {
  11181. for (let j = 0; j < 9; j++) {
  11182. state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
  11183. }
  11184. } else if (light.isDirectionalLight) {
  11185. const uniforms = cache.get(light);
  11186. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  11187. if (light.castShadow) {
  11188. const shadow = light.shadow;
  11189. const shadowUniforms = shadowCache.get(light);
  11190. shadowUniforms.shadowBias = shadow.bias;
  11191. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11192. shadowUniforms.shadowRadius = shadow.radius;
  11193. shadowUniforms.shadowMapSize = shadow.mapSize;
  11194. state.directionalShadow[directionalLength] = shadowUniforms;
  11195. state.directionalShadowMap[directionalLength] = shadowMap;
  11196. state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
  11197. numDirectionalShadows++;
  11198. }
  11199. state.directional[directionalLength] = uniforms;
  11200. directionalLength++;
  11201. } else if (light.isSpotLight) {
  11202. const uniforms = cache.get(light);
  11203. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  11204. uniforms.color.copy(color).multiplyScalar(intensity);
  11205. uniforms.distance = distance;
  11206. uniforms.coneCos = Math.cos(light.angle);
  11207. uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
  11208. uniforms.decay = light.decay;
  11209. if (light.castShadow) {
  11210. const shadow = light.shadow;
  11211. const shadowUniforms = shadowCache.get(light);
  11212. shadowUniforms.shadowBias = shadow.bias;
  11213. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11214. shadowUniforms.shadowRadius = shadow.radius;
  11215. shadowUniforms.shadowMapSize = shadow.mapSize;
  11216. state.spotShadow[spotLength] = shadowUniforms;
  11217. state.spotShadowMap[spotLength] = shadowMap;
  11218. state.spotShadowMatrix[spotLength] = light.shadow.matrix;
  11219. numSpotShadows++;
  11220. }
  11221. state.spot[spotLength] = uniforms;
  11222. spotLength++;
  11223. } else if (light.isRectAreaLight) {
  11224. const uniforms = cache.get(light); // (a) intensity is the total visible light emitted
  11225. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  11226. // (b) intensity is the brightness of the light
  11227. uniforms.color.copy(color).multiplyScalar(intensity);
  11228. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  11229. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  11230. state.rectArea[rectAreaLength] = uniforms;
  11231. rectAreaLength++;
  11232. } else if (light.isPointLight) {
  11233. const uniforms = cache.get(light);
  11234. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  11235. uniforms.distance = light.distance;
  11236. uniforms.decay = light.decay;
  11237. if (light.castShadow) {
  11238. const shadow = light.shadow;
  11239. const shadowUniforms = shadowCache.get(light);
  11240. shadowUniforms.shadowBias = shadow.bias;
  11241. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11242. shadowUniforms.shadowRadius = shadow.radius;
  11243. shadowUniforms.shadowMapSize = shadow.mapSize;
  11244. shadowUniforms.shadowCameraNear = shadow.camera.near;
  11245. shadowUniforms.shadowCameraFar = shadow.camera.far;
  11246. state.pointShadow[pointLength] = shadowUniforms;
  11247. state.pointShadowMap[pointLength] = shadowMap;
  11248. state.pointShadowMatrix[pointLength] = light.shadow.matrix;
  11249. numPointShadows++;
  11250. }
  11251. state.point[pointLength] = uniforms;
  11252. pointLength++;
  11253. } else if (light.isHemisphereLight) {
  11254. const uniforms = cache.get(light);
  11255. uniforms.skyColor.copy(light.color).multiplyScalar(intensity);
  11256. uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity);
  11257. state.hemi[hemiLength] = uniforms;
  11258. hemiLength++;
  11259. }
  11260. }
  11261. if (rectAreaLength > 0) {
  11262. if (capabilities.isWebGL2) {
  11263. // WebGL 2
  11264. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  11265. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  11266. } else {
  11267. // WebGL 1
  11268. if (extensions.has('OES_texture_float_linear') === true) {
  11269. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  11270. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  11271. } else if (extensions.has('OES_texture_half_float_linear') === true) {
  11272. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  11273. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  11274. } else {
  11275. console.error('THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.');
  11276. }
  11277. }
  11278. }
  11279. state.ambient[0] = r;
  11280. state.ambient[1] = g;
  11281. state.ambient[2] = b;
  11282. const hash = state.hash;
  11283. 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) {
  11284. state.directional.length = directionalLength;
  11285. state.spot.length = spotLength;
  11286. state.rectArea.length = rectAreaLength;
  11287. state.point.length = pointLength;
  11288. state.hemi.length = hemiLength;
  11289. state.directionalShadow.length = numDirectionalShadows;
  11290. state.directionalShadowMap.length = numDirectionalShadows;
  11291. state.pointShadow.length = numPointShadows;
  11292. state.pointShadowMap.length = numPointShadows;
  11293. state.spotShadow.length = numSpotShadows;
  11294. state.spotShadowMap.length = numSpotShadows;
  11295. state.directionalShadowMatrix.length = numDirectionalShadows;
  11296. state.pointShadowMatrix.length = numPointShadows;
  11297. state.spotShadowMatrix.length = numSpotShadows;
  11298. hash.directionalLength = directionalLength;
  11299. hash.pointLength = pointLength;
  11300. hash.spotLength = spotLength;
  11301. hash.rectAreaLength = rectAreaLength;
  11302. hash.hemiLength = hemiLength;
  11303. hash.numDirectionalShadows = numDirectionalShadows;
  11304. hash.numPointShadows = numPointShadows;
  11305. hash.numSpotShadows = numSpotShadows;
  11306. state.version = nextVersion++;
  11307. }
  11308. }
  11309. function setupView(lights, camera) {
  11310. let directionalLength = 0;
  11311. let pointLength = 0;
  11312. let spotLength = 0;
  11313. let rectAreaLength = 0;
  11314. let hemiLength = 0;
  11315. const viewMatrix = camera.matrixWorldInverse;
  11316. for (let i = 0, l = lights.length; i < l; i++) {
  11317. const light = lights[i];
  11318. if (light.isDirectionalLight) {
  11319. const uniforms = state.directional[directionalLength];
  11320. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  11321. vector3.setFromMatrixPosition(light.target.matrixWorld);
  11322. uniforms.direction.sub(vector3);
  11323. uniforms.direction.transformDirection(viewMatrix);
  11324. directionalLength++;
  11325. } else if (light.isSpotLight) {
  11326. const uniforms = state.spot[spotLength];
  11327. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  11328. uniforms.position.applyMatrix4(viewMatrix);
  11329. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  11330. vector3.setFromMatrixPosition(light.target.matrixWorld);
  11331. uniforms.direction.sub(vector3);
  11332. uniforms.direction.transformDirection(viewMatrix);
  11333. spotLength++;
  11334. } else if (light.isRectAreaLight) {
  11335. const uniforms = state.rectArea[rectAreaLength];
  11336. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  11337. uniforms.position.applyMatrix4(viewMatrix); // extract local rotation of light to derive width/height half vectors
  11338. matrix42.identity();
  11339. matrix4.copy(light.matrixWorld);
  11340. matrix4.premultiply(viewMatrix);
  11341. matrix42.extractRotation(matrix4);
  11342. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  11343. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  11344. uniforms.halfWidth.applyMatrix4(matrix42);
  11345. uniforms.halfHeight.applyMatrix4(matrix42);
  11346. rectAreaLength++;
  11347. } else if (light.isPointLight) {
  11348. const uniforms = state.point[pointLength];
  11349. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  11350. uniforms.position.applyMatrix4(viewMatrix);
  11351. pointLength++;
  11352. } else if (light.isHemisphereLight) {
  11353. const uniforms = state.hemi[hemiLength];
  11354. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  11355. uniforms.direction.transformDirection(viewMatrix);
  11356. uniforms.direction.normalize();
  11357. hemiLength++;
  11358. }
  11359. }
  11360. }
  11361. return {
  11362. setup: setup,
  11363. setupView: setupView,
  11364. state: state
  11365. };
  11366. }
  11367. function WebGLRenderState(extensions, capabilities) {
  11368. const lights = new WebGLLights(extensions, capabilities);
  11369. const lightsArray = [];
  11370. const shadowsArray = [];
  11371. function init() {
  11372. lightsArray.length = 0;
  11373. shadowsArray.length = 0;
  11374. }
  11375. function pushLight(light) {
  11376. lightsArray.push(light);
  11377. }
  11378. function pushShadow(shadowLight) {
  11379. shadowsArray.push(shadowLight);
  11380. }
  11381. function setupLights() {
  11382. lights.setup(lightsArray);
  11383. }
  11384. function setupLightsView(camera) {
  11385. lights.setupView(lightsArray, camera);
  11386. }
  11387. const state = {
  11388. lightsArray: lightsArray,
  11389. shadowsArray: shadowsArray,
  11390. lights: lights
  11391. };
  11392. return {
  11393. init: init,
  11394. state: state,
  11395. setupLights: setupLights,
  11396. setupLightsView: setupLightsView,
  11397. pushLight: pushLight,
  11398. pushShadow: pushShadow
  11399. };
  11400. }
  11401. function WebGLRenderStates(extensions, capabilities) {
  11402. let renderStates = new WeakMap();
  11403. function get(scene, renderCallDepth = 0) {
  11404. let renderState;
  11405. if (renderStates.has(scene) === false) {
  11406. renderState = new WebGLRenderState(extensions, capabilities);
  11407. renderStates.set(scene, [renderState]);
  11408. } else {
  11409. if (renderCallDepth >= renderStates.get(scene).length) {
  11410. renderState = new WebGLRenderState(extensions, capabilities);
  11411. renderStates.get(scene).push(renderState);
  11412. } else {
  11413. renderState = renderStates.get(scene)[renderCallDepth];
  11414. }
  11415. }
  11416. return renderState;
  11417. }
  11418. function dispose() {
  11419. renderStates = new WeakMap();
  11420. }
  11421. return {
  11422. get: get,
  11423. dispose: dispose
  11424. };
  11425. }
  11426. /**
  11427. * parameters = {
  11428. *
  11429. * opacity: <float>,
  11430. *
  11431. * map: new THREE.Texture( <Image> ),
  11432. *
  11433. * alphaMap: new THREE.Texture( <Image> ),
  11434. *
  11435. * displacementMap: new THREE.Texture( <Image> ),
  11436. * displacementScale: <float>,
  11437. * displacementBias: <float>,
  11438. *
  11439. * wireframe: <boolean>,
  11440. * wireframeLinewidth: <float>
  11441. * }
  11442. */
  11443. class MeshDepthMaterial extends Material {
  11444. constructor(parameters) {
  11445. super();
  11446. this.type = 'MeshDepthMaterial';
  11447. this.depthPacking = BasicDepthPacking;
  11448. this.morphTargets = false;
  11449. this.map = null;
  11450. this.alphaMap = null;
  11451. this.displacementMap = null;
  11452. this.displacementScale = 1;
  11453. this.displacementBias = 0;
  11454. this.wireframe = false;
  11455. this.wireframeLinewidth = 1;
  11456. this.fog = false;
  11457. this.setValues(parameters);
  11458. }
  11459. copy(source) {
  11460. super.copy(source);
  11461. this.depthPacking = source.depthPacking;
  11462. this.morphTargets = source.morphTargets;
  11463. this.map = source.map;
  11464. this.alphaMap = source.alphaMap;
  11465. this.displacementMap = source.displacementMap;
  11466. this.displacementScale = source.displacementScale;
  11467. this.displacementBias = source.displacementBias;
  11468. this.wireframe = source.wireframe;
  11469. this.wireframeLinewidth = source.wireframeLinewidth;
  11470. return this;
  11471. }
  11472. }
  11473. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  11474. /**
  11475. * parameters = {
  11476. *
  11477. * referencePosition: <float>,
  11478. * nearDistance: <float>,
  11479. * farDistance: <float>,
  11480. *
  11481. * morphTargets: <bool>,
  11482. *
  11483. * map: new THREE.Texture( <Image> ),
  11484. *
  11485. * alphaMap: new THREE.Texture( <Image> ),
  11486. *
  11487. * displacementMap: new THREE.Texture( <Image> ),
  11488. * displacementScale: <float>,
  11489. * displacementBias: <float>
  11490. *
  11491. * }
  11492. */
  11493. class MeshDistanceMaterial extends Material {
  11494. constructor(parameters) {
  11495. super();
  11496. this.type = 'MeshDistanceMaterial';
  11497. this.referencePosition = new Vector3();
  11498. this.nearDistance = 1;
  11499. this.farDistance = 1000;
  11500. this.morphTargets = false;
  11501. this.map = null;
  11502. this.alphaMap = null;
  11503. this.displacementMap = null;
  11504. this.displacementScale = 1;
  11505. this.displacementBias = 0;
  11506. this.fog = false;
  11507. this.setValues(parameters);
  11508. }
  11509. copy(source) {
  11510. super.copy(source);
  11511. this.referencePosition.copy(source.referencePosition);
  11512. this.nearDistance = source.nearDistance;
  11513. this.farDistance = source.farDistance;
  11514. this.morphTargets = source.morphTargets;
  11515. this.map = source.map;
  11516. this.alphaMap = source.alphaMap;
  11517. this.displacementMap = source.displacementMap;
  11518. this.displacementScale = source.displacementScale;
  11519. this.displacementBias = source.displacementBias;
  11520. return this;
  11521. }
  11522. }
  11523. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  11524. var vsm_frag = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy ) / resolution ) );\n\tfor ( float i = -1.0; i < 1.0 ; i += SAMPLE_RATE) {\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( i, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, i ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean * HALF_SAMPLE_RATE;\n\tsquared_mean = squared_mean * HALF_SAMPLE_RATE;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";
  11525. var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  11526. function WebGLShadowMap(_renderer, _objects, _capabilities) {
  11527. let _frustum = new Frustum();
  11528. const _shadowMapSize = new Vector2(),
  11529. _viewportSize = new Vector2(),
  11530. _viewport = new Vector4(),
  11531. _depthMaterials = [],
  11532. _distanceMaterials = [],
  11533. _materialCache = {},
  11534. _maxTextureSize = _capabilities.maxTextureSize;
  11535. const shadowSide = {
  11536. 0: BackSide,
  11537. 1: FrontSide,
  11538. 2: DoubleSide
  11539. };
  11540. const shadowMaterialVertical = new ShaderMaterial({
  11541. defines: {
  11542. SAMPLE_RATE: 2.0 / 8.0,
  11543. HALF_SAMPLE_RATE: 1.0 / 8.0
  11544. },
  11545. uniforms: {
  11546. shadow_pass: {
  11547. value: null
  11548. },
  11549. resolution: {
  11550. value: new Vector2()
  11551. },
  11552. radius: {
  11553. value: 4.0
  11554. }
  11555. },
  11556. vertexShader: vsm_vert,
  11557. fragmentShader: vsm_frag
  11558. });
  11559. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  11560. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  11561. const fullScreenTri = new BufferGeometry();
  11562. fullScreenTri.setAttribute('position', new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));
  11563. const fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical);
  11564. const scope = this;
  11565. this.enabled = false;
  11566. this.autoUpdate = true;
  11567. this.needsUpdate = false;
  11568. this.type = PCFShadowMap;
  11569. this.render = function (lights, scene, camera) {
  11570. if (scope.enabled === false) return;
  11571. if (scope.autoUpdate === false && scope.needsUpdate === false) return;
  11572. if (lights.length === 0) return;
  11573. const currentRenderTarget = _renderer.getRenderTarget();
  11574. const activeCubeFace = _renderer.getActiveCubeFace();
  11575. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  11576. const _state = _renderer.state; // Set GL state for depth map.
  11577. _state.setBlending(NoBlending);
  11578. _state.buffers.color.setClear(1, 1, 1, 1);
  11579. _state.buffers.depth.setTest(true);
  11580. _state.setScissorTest(false); // render depth map
  11581. for (let i = 0, il = lights.length; i < il; i++) {
  11582. const light = lights[i];
  11583. const shadow = light.shadow;
  11584. if (shadow === undefined) {
  11585. console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');
  11586. continue;
  11587. }
  11588. if (shadow.autoUpdate === false && shadow.needsUpdate === false) continue;
  11589. _shadowMapSize.copy(shadow.mapSize);
  11590. const shadowFrameExtents = shadow.getFrameExtents();
  11591. _shadowMapSize.multiply(shadowFrameExtents);
  11592. _viewportSize.copy(shadow.mapSize);
  11593. if (_shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize) {
  11594. if (_shadowMapSize.x > _maxTextureSize) {
  11595. _viewportSize.x = Math.floor(_maxTextureSize / shadowFrameExtents.x);
  11596. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  11597. shadow.mapSize.x = _viewportSize.x;
  11598. }
  11599. if (_shadowMapSize.y > _maxTextureSize) {
  11600. _viewportSize.y = Math.floor(_maxTextureSize / shadowFrameExtents.y);
  11601. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  11602. shadow.mapSize.y = _viewportSize.y;
  11603. }
  11604. }
  11605. if (shadow.map === null && !shadow.isPointLightShadow && this.type === VSMShadowMap) {
  11606. const pars = {
  11607. minFilter: LinearFilter,
  11608. magFilter: LinearFilter,
  11609. format: RGBAFormat
  11610. };
  11611. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  11612. shadow.map.texture.name = light.name + '.shadowMap';
  11613. shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  11614. shadow.camera.updateProjectionMatrix();
  11615. }
  11616. if (shadow.map === null) {
  11617. const pars = {
  11618. minFilter: NearestFilter,
  11619. magFilter: NearestFilter,
  11620. format: RGBAFormat
  11621. };
  11622. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  11623. shadow.map.texture.name = light.name + '.shadowMap';
  11624. shadow.camera.updateProjectionMatrix();
  11625. }
  11626. _renderer.setRenderTarget(shadow.map);
  11627. _renderer.clear();
  11628. const viewportCount = shadow.getViewportCount();
  11629. for (let vp = 0; vp < viewportCount; vp++) {
  11630. const viewport = shadow.getViewport(vp);
  11631. _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
  11632. _state.viewport(_viewport);
  11633. shadow.updateMatrices(light, vp);
  11634. _frustum = shadow.getFrustum();
  11635. renderObject(scene, camera, shadow.camera, light, this.type);
  11636. } // do blur pass for VSM
  11637. if (!shadow.isPointLightShadow && this.type === VSMShadowMap) {
  11638. VSMPass(shadow, camera);
  11639. }
  11640. shadow.needsUpdate = false;
  11641. }
  11642. scope.needsUpdate = false;
  11643. _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
  11644. };
  11645. function VSMPass(shadow, camera) {
  11646. const geometry = _objects.update(fullScreenMesh); // vertical pass
  11647. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  11648. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  11649. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  11650. _renderer.setRenderTarget(shadow.mapPass);
  11651. _renderer.clear();
  11652. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); // horizontal pass
  11653. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  11654. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  11655. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  11656. _renderer.setRenderTarget(shadow.map);
  11657. _renderer.clear();
  11658. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null);
  11659. }
  11660. function getDepthMaterialVariant(useMorphing) {
  11661. const index = useMorphing << 0;
  11662. let material = _depthMaterials[index];
  11663. if (material === undefined) {
  11664. material = new MeshDepthMaterial({
  11665. depthPacking: RGBADepthPacking,
  11666. morphTargets: useMorphing
  11667. });
  11668. _depthMaterials[index] = material;
  11669. }
  11670. return material;
  11671. }
  11672. function getDistanceMaterialVariant(useMorphing) {
  11673. const index = useMorphing << 0;
  11674. let material = _distanceMaterials[index];
  11675. if (material === undefined) {
  11676. material = new MeshDistanceMaterial({
  11677. morphTargets: useMorphing
  11678. });
  11679. _distanceMaterials[index] = material;
  11680. }
  11681. return material;
  11682. }
  11683. function getDepthMaterial(object, geometry, material, light, shadowCameraNear, shadowCameraFar, type) {
  11684. let result = null;
  11685. let getMaterialVariant = getDepthMaterialVariant;
  11686. let customMaterial = object.customDepthMaterial;
  11687. if (light.isPointLight === true) {
  11688. getMaterialVariant = getDistanceMaterialVariant;
  11689. customMaterial = object.customDistanceMaterial;
  11690. }
  11691. if (customMaterial === undefined) {
  11692. let useMorphing = false;
  11693. if (material.morphTargets === true) {
  11694. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  11695. }
  11696. result = getMaterialVariant(useMorphing);
  11697. } else {
  11698. result = customMaterial;
  11699. }
  11700. if (_renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0) {
  11701. // in this case we need a unique material instance reflecting the
  11702. // appropriate state
  11703. const keyA = result.uuid,
  11704. keyB = material.uuid;
  11705. let materialsForVariant = _materialCache[keyA];
  11706. if (materialsForVariant === undefined) {
  11707. materialsForVariant = {};
  11708. _materialCache[keyA] = materialsForVariant;
  11709. }
  11710. let cachedMaterial = materialsForVariant[keyB];
  11711. if (cachedMaterial === undefined) {
  11712. cachedMaterial = result.clone();
  11713. materialsForVariant[keyB] = cachedMaterial;
  11714. }
  11715. result = cachedMaterial;
  11716. }
  11717. result.visible = material.visible;
  11718. result.wireframe = material.wireframe;
  11719. if (type === VSMShadowMap) {
  11720. result.side = material.shadowSide !== null ? material.shadowSide : material.side;
  11721. } else {
  11722. result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side];
  11723. }
  11724. result.clipShadows = material.clipShadows;
  11725. result.clippingPlanes = material.clippingPlanes;
  11726. result.clipIntersection = material.clipIntersection;
  11727. result.wireframeLinewidth = material.wireframeLinewidth;
  11728. result.linewidth = material.linewidth;
  11729. if (light.isPointLight === true && result.isMeshDistanceMaterial === true) {
  11730. result.referencePosition.setFromMatrixPosition(light.matrixWorld);
  11731. result.nearDistance = shadowCameraNear;
  11732. result.farDistance = shadowCameraFar;
  11733. }
  11734. return result;
  11735. }
  11736. function renderObject(object, camera, shadowCamera, light, type) {
  11737. if (object.visible === false) return;
  11738. const visible = object.layers.test(camera.layers);
  11739. if (visible && (object.isMesh || object.isLine || object.isPoints)) {
  11740. if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {
  11741. object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
  11742. const geometry = _objects.update(object);
  11743. const material = object.material;
  11744. if (Array.isArray(material)) {
  11745. const groups = geometry.groups;
  11746. for (let k = 0, kl = groups.length; k < kl; k++) {
  11747. const group = groups[k];
  11748. const groupMaterial = material[group.materialIndex];
  11749. if (groupMaterial && groupMaterial.visible) {
  11750. const depthMaterial = getDepthMaterial(object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
  11751. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
  11752. }
  11753. }
  11754. } else if (material.visible) {
  11755. const depthMaterial = getDepthMaterial(object, geometry, material, light, shadowCamera.near, shadowCamera.far, type);
  11756. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null);
  11757. }
  11758. }
  11759. }
  11760. const children = object.children;
  11761. for (let i = 0, l = children.length; i < l; i++) {
  11762. renderObject(children[i], camera, shadowCamera, light, type);
  11763. }
  11764. }
  11765. }
  11766. function WebGLState(gl, extensions, capabilities) {
  11767. const isWebGL2 = capabilities.isWebGL2;
  11768. function ColorBuffer() {
  11769. let locked = false;
  11770. const color = new Vector4();
  11771. let currentColorMask = null;
  11772. const currentColorClear = new Vector4(0, 0, 0, 0);
  11773. return {
  11774. setMask: function (colorMask) {
  11775. if (currentColorMask !== colorMask && !locked) {
  11776. gl.colorMask(colorMask, colorMask, colorMask, colorMask);
  11777. currentColorMask = colorMask;
  11778. }
  11779. },
  11780. setLocked: function (lock) {
  11781. locked = lock;
  11782. },
  11783. setClear: function (r, g, b, a, premultipliedAlpha) {
  11784. if (premultipliedAlpha === true) {
  11785. r *= a;
  11786. g *= a;
  11787. b *= a;
  11788. }
  11789. color.set(r, g, b, a);
  11790. if (currentColorClear.equals(color) === false) {
  11791. gl.clearColor(r, g, b, a);
  11792. currentColorClear.copy(color);
  11793. }
  11794. },
  11795. reset: function () {
  11796. locked = false;
  11797. currentColorMask = null;
  11798. currentColorClear.set(-1, 0, 0, 0); // set to invalid state
  11799. }
  11800. };
  11801. }
  11802. function DepthBuffer() {
  11803. let locked = false;
  11804. let currentDepthMask = null;
  11805. let currentDepthFunc = null;
  11806. let currentDepthClear = null;
  11807. return {
  11808. setTest: function (depthTest) {
  11809. if (depthTest) {
  11810. enable(gl.DEPTH_TEST);
  11811. } else {
  11812. disable(gl.DEPTH_TEST);
  11813. }
  11814. },
  11815. setMask: function (depthMask) {
  11816. if (currentDepthMask !== depthMask && !locked) {
  11817. gl.depthMask(depthMask);
  11818. currentDepthMask = depthMask;
  11819. }
  11820. },
  11821. setFunc: function (depthFunc) {
  11822. if (currentDepthFunc !== depthFunc) {
  11823. if (depthFunc) {
  11824. switch (depthFunc) {
  11825. case NeverDepth:
  11826. gl.depthFunc(gl.NEVER);
  11827. break;
  11828. case AlwaysDepth:
  11829. gl.depthFunc(gl.ALWAYS);
  11830. break;
  11831. case LessDepth:
  11832. gl.depthFunc(gl.LESS);
  11833. break;
  11834. case LessEqualDepth:
  11835. gl.depthFunc(gl.LEQUAL);
  11836. break;
  11837. case EqualDepth:
  11838. gl.depthFunc(gl.EQUAL);
  11839. break;
  11840. case GreaterEqualDepth:
  11841. gl.depthFunc(gl.GEQUAL);
  11842. break;
  11843. case GreaterDepth:
  11844. gl.depthFunc(gl.GREATER);
  11845. break;
  11846. case NotEqualDepth:
  11847. gl.depthFunc(gl.NOTEQUAL);
  11848. break;
  11849. default:
  11850. gl.depthFunc(gl.LEQUAL);
  11851. }
  11852. } else {
  11853. gl.depthFunc(gl.LEQUAL);
  11854. }
  11855. currentDepthFunc = depthFunc;
  11856. }
  11857. },
  11858. setLocked: function (lock) {
  11859. locked = lock;
  11860. },
  11861. setClear: function (depth) {
  11862. if (currentDepthClear !== depth) {
  11863. gl.clearDepth(depth);
  11864. currentDepthClear = depth;
  11865. }
  11866. },
  11867. reset: function () {
  11868. locked = false;
  11869. currentDepthMask = null;
  11870. currentDepthFunc = null;
  11871. currentDepthClear = null;
  11872. }
  11873. };
  11874. }
  11875. function StencilBuffer() {
  11876. let locked = false;
  11877. let currentStencilMask = null;
  11878. let currentStencilFunc = null;
  11879. let currentStencilRef = null;
  11880. let currentStencilFuncMask = null;
  11881. let currentStencilFail = null;
  11882. let currentStencilZFail = null;
  11883. let currentStencilZPass = null;
  11884. let currentStencilClear = null;
  11885. return {
  11886. setTest: function (stencilTest) {
  11887. if (!locked) {
  11888. if (stencilTest) {
  11889. enable(gl.STENCIL_TEST);
  11890. } else {
  11891. disable(gl.STENCIL_TEST);
  11892. }
  11893. }
  11894. },
  11895. setMask: function (stencilMask) {
  11896. if (currentStencilMask !== stencilMask && !locked) {
  11897. gl.stencilMask(stencilMask);
  11898. currentStencilMask = stencilMask;
  11899. }
  11900. },
  11901. setFunc: function (stencilFunc, stencilRef, stencilMask) {
  11902. if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
  11903. gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
  11904. currentStencilFunc = stencilFunc;
  11905. currentStencilRef = stencilRef;
  11906. currentStencilFuncMask = stencilMask;
  11907. }
  11908. },
  11909. setOp: function (stencilFail, stencilZFail, stencilZPass) {
  11910. if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
  11911. gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
  11912. currentStencilFail = stencilFail;
  11913. currentStencilZFail = stencilZFail;
  11914. currentStencilZPass = stencilZPass;
  11915. }
  11916. },
  11917. setLocked: function (lock) {
  11918. locked = lock;
  11919. },
  11920. setClear: function (stencil) {
  11921. if (currentStencilClear !== stencil) {
  11922. gl.clearStencil(stencil);
  11923. currentStencilClear = stencil;
  11924. }
  11925. },
  11926. reset: function () {
  11927. locked = false;
  11928. currentStencilMask = null;
  11929. currentStencilFunc = null;
  11930. currentStencilRef = null;
  11931. currentStencilFuncMask = null;
  11932. currentStencilFail = null;
  11933. currentStencilZFail = null;
  11934. currentStencilZPass = null;
  11935. currentStencilClear = null;
  11936. }
  11937. };
  11938. } //
  11939. const colorBuffer = new ColorBuffer();
  11940. const depthBuffer = new DepthBuffer();
  11941. const stencilBuffer = new StencilBuffer();
  11942. let enabledCapabilities = {};
  11943. let xrFramebuffer = null;
  11944. let currentBoundFramebuffers = {};
  11945. let currentProgram = null;
  11946. let currentBlendingEnabled = false;
  11947. let currentBlending = null;
  11948. let currentBlendEquation = null;
  11949. let currentBlendSrc = null;
  11950. let currentBlendDst = null;
  11951. let currentBlendEquationAlpha = null;
  11952. let currentBlendSrcAlpha = null;
  11953. let currentBlendDstAlpha = null;
  11954. let currentPremultipledAlpha = false;
  11955. let currentFlipSided = null;
  11956. let currentCullFace = null;
  11957. let currentLineWidth = null;
  11958. let currentPolygonOffsetFactor = null;
  11959. let currentPolygonOffsetUnits = null;
  11960. const maxTextures = gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11961. let lineWidthAvailable = false;
  11962. let version = 0;
  11963. const glVersion = gl.getParameter(gl.VERSION);
  11964. if (glVersion.indexOf('WebGL') !== -1) {
  11965. version = parseFloat(/^WebGL (\d)/.exec(glVersion)[1]);
  11966. lineWidthAvailable = version >= 1.0;
  11967. } else if (glVersion.indexOf('OpenGL ES') !== -1) {
  11968. version = parseFloat(/^OpenGL ES (\d)/.exec(glVersion)[1]);
  11969. lineWidthAvailable = version >= 2.0;
  11970. }
  11971. let currentTextureSlot = null;
  11972. let currentBoundTextures = {};
  11973. const currentScissor = new Vector4(0, 0, gl.canvas.width, gl.canvas.height);
  11974. const currentViewport = new Vector4(0, 0, gl.canvas.width, gl.canvas.height);
  11975. function createTexture(type, target, count) {
  11976. const data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.
  11977. const texture = gl.createTexture();
  11978. gl.bindTexture(type, texture);
  11979. gl.texParameteri(type, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11980. gl.texParameteri(type, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11981. for (let i = 0; i < count; i++) {
  11982. gl.texImage2D(target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
  11983. }
  11984. return texture;
  11985. }
  11986. const emptyTextures = {};
  11987. emptyTextures[gl.TEXTURE_2D] = createTexture(gl.TEXTURE_2D, gl.TEXTURE_2D, 1);
  11988. emptyTextures[gl.TEXTURE_CUBE_MAP] = createTexture(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6); // init
  11989. colorBuffer.setClear(0, 0, 0, 1);
  11990. depthBuffer.setClear(1);
  11991. stencilBuffer.setClear(0);
  11992. enable(gl.DEPTH_TEST);
  11993. depthBuffer.setFunc(LessEqualDepth);
  11994. setFlipSided(false);
  11995. setCullFace(CullFaceBack);
  11996. enable(gl.CULL_FACE);
  11997. setBlending(NoBlending); //
  11998. function enable(id) {
  11999. if (enabledCapabilities[id] !== true) {
  12000. gl.enable(id);
  12001. enabledCapabilities[id] = true;
  12002. }
  12003. }
  12004. function disable(id) {
  12005. if (enabledCapabilities[id] !== false) {
  12006. gl.disable(id);
  12007. enabledCapabilities[id] = false;
  12008. }
  12009. }
  12010. function bindXRFramebuffer(framebuffer) {
  12011. if (framebuffer !== xrFramebuffer) {
  12012. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  12013. xrFramebuffer = framebuffer;
  12014. }
  12015. }
  12016. function bindFramebuffer(target, framebuffer) {
  12017. if (framebuffer === null && xrFramebuffer !== null) framebuffer = xrFramebuffer; // use active XR framebuffer if available
  12018. if (currentBoundFramebuffers[target] !== framebuffer) {
  12019. gl.bindFramebuffer(target, framebuffer);
  12020. currentBoundFramebuffers[target] = framebuffer;
  12021. if (isWebGL2) {
  12022. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  12023. if (target === gl.DRAW_FRAMEBUFFER) {
  12024. currentBoundFramebuffers[gl.FRAMEBUFFER] = framebuffer;
  12025. }
  12026. if (target === gl.FRAMEBUFFER) {
  12027. currentBoundFramebuffers[gl.DRAW_FRAMEBUFFER] = framebuffer;
  12028. }
  12029. }
  12030. return true;
  12031. }
  12032. return false;
  12033. }
  12034. function useProgram(program) {
  12035. if (currentProgram !== program) {
  12036. gl.useProgram(program);
  12037. currentProgram = program;
  12038. return true;
  12039. }
  12040. return false;
  12041. }
  12042. const equationToGL = {
  12043. [AddEquation]: gl.FUNC_ADD,
  12044. [SubtractEquation]: gl.FUNC_SUBTRACT,
  12045. [ReverseSubtractEquation]: gl.FUNC_REVERSE_SUBTRACT
  12046. };
  12047. if (isWebGL2) {
  12048. equationToGL[MinEquation] = gl.MIN;
  12049. equationToGL[MaxEquation] = gl.MAX;
  12050. } else {
  12051. const extension = extensions.get('EXT_blend_minmax');
  12052. if (extension !== null) {
  12053. equationToGL[MinEquation] = extension.MIN_EXT;
  12054. equationToGL[MaxEquation] = extension.MAX_EXT;
  12055. }
  12056. }
  12057. const factorToGL = {
  12058. [ZeroFactor]: gl.ZERO,
  12059. [OneFactor]: gl.ONE,
  12060. [SrcColorFactor]: gl.SRC_COLOR,
  12061. [SrcAlphaFactor]: gl.SRC_ALPHA,
  12062. [SrcAlphaSaturateFactor]: gl.SRC_ALPHA_SATURATE,
  12063. [DstColorFactor]: gl.DST_COLOR,
  12064. [DstAlphaFactor]: gl.DST_ALPHA,
  12065. [OneMinusSrcColorFactor]: gl.ONE_MINUS_SRC_COLOR,
  12066. [OneMinusSrcAlphaFactor]: gl.ONE_MINUS_SRC_ALPHA,
  12067. [OneMinusDstColorFactor]: gl.ONE_MINUS_DST_COLOR,
  12068. [OneMinusDstAlphaFactor]: gl.ONE_MINUS_DST_ALPHA
  12069. };
  12070. function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
  12071. if (blending === NoBlending) {
  12072. if (currentBlendingEnabled === true) {
  12073. disable(gl.BLEND);
  12074. currentBlendingEnabled = false;
  12075. }
  12076. return;
  12077. }
  12078. if (currentBlendingEnabled === false) {
  12079. enable(gl.BLEND);
  12080. currentBlendingEnabled = true;
  12081. }
  12082. if (blending !== CustomBlending) {
  12083. if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
  12084. if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
  12085. gl.blendEquation(gl.FUNC_ADD);
  12086. currentBlendEquation = AddEquation;
  12087. currentBlendEquationAlpha = AddEquation;
  12088. }
  12089. if (premultipliedAlpha) {
  12090. switch (blending) {
  12091. case NormalBlending:
  12092. gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  12093. break;
  12094. case AdditiveBlending:
  12095. gl.blendFunc(gl.ONE, gl.ONE);
  12096. break;
  12097. case SubtractiveBlending:
  12098. gl.blendFuncSeparate(gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA);
  12099. break;
  12100. case MultiplyBlending:
  12101. gl.blendFuncSeparate(gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA);
  12102. break;
  12103. default:
  12104. console.error('THREE.WebGLState: Invalid blending: ', blending);
  12105. break;
  12106. }
  12107. } else {
  12108. switch (blending) {
  12109. case NormalBlending:
  12110. gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  12111. break;
  12112. case AdditiveBlending:
  12113. gl.blendFunc(gl.SRC_ALPHA, gl.ONE);
  12114. break;
  12115. case SubtractiveBlending:
  12116. gl.blendFunc(gl.ZERO, gl.ONE_MINUS_SRC_COLOR);
  12117. break;
  12118. case MultiplyBlending:
  12119. gl.blendFunc(gl.ZERO, gl.SRC_COLOR);
  12120. break;
  12121. default:
  12122. console.error('THREE.WebGLState: Invalid blending: ', blending);
  12123. break;
  12124. }
  12125. }
  12126. currentBlendSrc = null;
  12127. currentBlendDst = null;
  12128. currentBlendSrcAlpha = null;
  12129. currentBlendDstAlpha = null;
  12130. currentBlending = blending;
  12131. currentPremultipledAlpha = premultipliedAlpha;
  12132. }
  12133. return;
  12134. } // custom blending
  12135. blendEquationAlpha = blendEquationAlpha || blendEquation;
  12136. blendSrcAlpha = blendSrcAlpha || blendSrc;
  12137. blendDstAlpha = blendDstAlpha || blendDst;
  12138. if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
  12139. gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]);
  12140. currentBlendEquation = blendEquation;
  12141. currentBlendEquationAlpha = blendEquationAlpha;
  12142. }
  12143. if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
  12144. gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]);
  12145. currentBlendSrc = blendSrc;
  12146. currentBlendDst = blendDst;
  12147. currentBlendSrcAlpha = blendSrcAlpha;
  12148. currentBlendDstAlpha = blendDstAlpha;
  12149. }
  12150. currentBlending = blending;
  12151. currentPremultipledAlpha = null;
  12152. }
  12153. function setMaterial(material, frontFaceCW) {
  12154. material.side === DoubleSide ? disable(gl.CULL_FACE) : enable(gl.CULL_FACE);
  12155. let flipSided = material.side === BackSide;
  12156. if (frontFaceCW) flipSided = !flipSided;
  12157. setFlipSided(flipSided);
  12158. 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);
  12159. depthBuffer.setFunc(material.depthFunc);
  12160. depthBuffer.setTest(material.depthTest);
  12161. depthBuffer.setMask(material.depthWrite);
  12162. colorBuffer.setMask(material.colorWrite);
  12163. const stencilWrite = material.stencilWrite;
  12164. stencilBuffer.setTest(stencilWrite);
  12165. if (stencilWrite) {
  12166. stencilBuffer.setMask(material.stencilWriteMask);
  12167. stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
  12168. stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
  12169. }
  12170. setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
  12171. material.alphaToCoverage === true ? enable(gl.SAMPLE_ALPHA_TO_COVERAGE) : disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  12172. } //
  12173. function setFlipSided(flipSided) {
  12174. if (currentFlipSided !== flipSided) {
  12175. if (flipSided) {
  12176. gl.frontFace(gl.CW);
  12177. } else {
  12178. gl.frontFace(gl.CCW);
  12179. }
  12180. currentFlipSided = flipSided;
  12181. }
  12182. }
  12183. function setCullFace(cullFace) {
  12184. if (cullFace !== CullFaceNone) {
  12185. enable(gl.CULL_FACE);
  12186. if (cullFace !== currentCullFace) {
  12187. if (cullFace === CullFaceBack) {
  12188. gl.cullFace(gl.BACK);
  12189. } else if (cullFace === CullFaceFront) {
  12190. gl.cullFace(gl.FRONT);
  12191. } else {
  12192. gl.cullFace(gl.FRONT_AND_BACK);
  12193. }
  12194. }
  12195. } else {
  12196. disable(gl.CULL_FACE);
  12197. }
  12198. currentCullFace = cullFace;
  12199. }
  12200. function setLineWidth(width) {
  12201. if (width !== currentLineWidth) {
  12202. if (lineWidthAvailable) gl.lineWidth(width);
  12203. currentLineWidth = width;
  12204. }
  12205. }
  12206. function setPolygonOffset(polygonOffset, factor, units) {
  12207. if (polygonOffset) {
  12208. enable(gl.POLYGON_OFFSET_FILL);
  12209. if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
  12210. gl.polygonOffset(factor, units);
  12211. currentPolygonOffsetFactor = factor;
  12212. currentPolygonOffsetUnits = units;
  12213. }
  12214. } else {
  12215. disable(gl.POLYGON_OFFSET_FILL);
  12216. }
  12217. }
  12218. function setScissorTest(scissorTest) {
  12219. if (scissorTest) {
  12220. enable(gl.SCISSOR_TEST);
  12221. } else {
  12222. disable(gl.SCISSOR_TEST);
  12223. }
  12224. } // texture
  12225. function activeTexture(webglSlot) {
  12226. if (webglSlot === undefined) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  12227. if (currentTextureSlot !== webglSlot) {
  12228. gl.activeTexture(webglSlot);
  12229. currentTextureSlot = webglSlot;
  12230. }
  12231. }
  12232. function bindTexture(webglType, webglTexture) {
  12233. if (currentTextureSlot === null) {
  12234. activeTexture();
  12235. }
  12236. let boundTexture = currentBoundTextures[currentTextureSlot];
  12237. if (boundTexture === undefined) {
  12238. boundTexture = {
  12239. type: undefined,
  12240. texture: undefined
  12241. };
  12242. currentBoundTextures[currentTextureSlot] = boundTexture;
  12243. }
  12244. if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
  12245. gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
  12246. boundTexture.type = webglType;
  12247. boundTexture.texture = webglTexture;
  12248. }
  12249. }
  12250. function unbindTexture() {
  12251. const boundTexture = currentBoundTextures[currentTextureSlot];
  12252. if (boundTexture !== undefined && boundTexture.type !== undefined) {
  12253. gl.bindTexture(boundTexture.type, null);
  12254. boundTexture.type = undefined;
  12255. boundTexture.texture = undefined;
  12256. }
  12257. }
  12258. function compressedTexImage2D() {
  12259. try {
  12260. gl.compressedTexImage2D.apply(gl, arguments);
  12261. } catch (error) {
  12262. console.error('THREE.WebGLState:', error);
  12263. }
  12264. }
  12265. function texImage2D() {
  12266. try {
  12267. gl.texImage2D.apply(gl, arguments);
  12268. } catch (error) {
  12269. console.error('THREE.WebGLState:', error);
  12270. }
  12271. }
  12272. function texImage3D() {
  12273. try {
  12274. gl.texImage3D.apply(gl, arguments);
  12275. } catch (error) {
  12276. console.error('THREE.WebGLState:', error);
  12277. }
  12278. } //
  12279. function scissor(scissor) {
  12280. if (currentScissor.equals(scissor) === false) {
  12281. gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
  12282. currentScissor.copy(scissor);
  12283. }
  12284. }
  12285. function viewport(viewport) {
  12286. if (currentViewport.equals(viewport) === false) {
  12287. gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
  12288. currentViewport.copy(viewport);
  12289. }
  12290. } //
  12291. function reset() {
  12292. // reset state
  12293. gl.disable(gl.BLEND);
  12294. gl.disable(gl.CULL_FACE);
  12295. gl.disable(gl.DEPTH_TEST);
  12296. gl.disable(gl.POLYGON_OFFSET_FILL);
  12297. gl.disable(gl.SCISSOR_TEST);
  12298. gl.disable(gl.STENCIL_TEST);
  12299. gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  12300. gl.blendEquation(gl.FUNC_ADD);
  12301. gl.blendFunc(gl.ONE, gl.ZERO);
  12302. gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ZERO);
  12303. gl.colorMask(true, true, true, true);
  12304. gl.clearColor(0, 0, 0, 0);
  12305. gl.depthMask(true);
  12306. gl.depthFunc(gl.LESS);
  12307. gl.clearDepth(1);
  12308. gl.stencilMask(0xffffffff);
  12309. gl.stencilFunc(gl.ALWAYS, 0, 0xffffffff);
  12310. gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
  12311. gl.clearStencil(0);
  12312. gl.cullFace(gl.BACK);
  12313. gl.frontFace(gl.CCW);
  12314. gl.polygonOffset(0, 0);
  12315. gl.activeTexture(gl.TEXTURE0);
  12316. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  12317. if (isWebGL2 === true) {
  12318. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);
  12319. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
  12320. }
  12321. gl.useProgram(null);
  12322. gl.lineWidth(1);
  12323. gl.scissor(0, 0, gl.canvas.width, gl.canvas.height);
  12324. gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); // reset internals
  12325. enabledCapabilities = {};
  12326. currentTextureSlot = null;
  12327. currentBoundTextures = {};
  12328. xrFramebuffer = null;
  12329. currentBoundFramebuffers = {};
  12330. currentProgram = null;
  12331. currentBlendingEnabled = false;
  12332. currentBlending = null;
  12333. currentBlendEquation = null;
  12334. currentBlendSrc = null;
  12335. currentBlendDst = null;
  12336. currentBlendEquationAlpha = null;
  12337. currentBlendSrcAlpha = null;
  12338. currentBlendDstAlpha = null;
  12339. currentPremultipledAlpha = false;
  12340. currentFlipSided = null;
  12341. currentCullFace = null;
  12342. currentLineWidth = null;
  12343. currentPolygonOffsetFactor = null;
  12344. currentPolygonOffsetUnits = null;
  12345. currentScissor.set(0, 0, gl.canvas.width, gl.canvas.height);
  12346. currentViewport.set(0, 0, gl.canvas.width, gl.canvas.height);
  12347. colorBuffer.reset();
  12348. depthBuffer.reset();
  12349. stencilBuffer.reset();
  12350. }
  12351. return {
  12352. buffers: {
  12353. color: colorBuffer,
  12354. depth: depthBuffer,
  12355. stencil: stencilBuffer
  12356. },
  12357. enable: enable,
  12358. disable: disable,
  12359. bindFramebuffer: bindFramebuffer,
  12360. bindXRFramebuffer: bindXRFramebuffer,
  12361. useProgram: useProgram,
  12362. setBlending: setBlending,
  12363. setMaterial: setMaterial,
  12364. setFlipSided: setFlipSided,
  12365. setCullFace: setCullFace,
  12366. setLineWidth: setLineWidth,
  12367. setPolygonOffset: setPolygonOffset,
  12368. setScissorTest: setScissorTest,
  12369. activeTexture: activeTexture,
  12370. bindTexture: bindTexture,
  12371. unbindTexture: unbindTexture,
  12372. compressedTexImage2D: compressedTexImage2D,
  12373. texImage2D: texImage2D,
  12374. texImage3D: texImage3D,
  12375. scissor: scissor,
  12376. viewport: viewport,
  12377. reset: reset
  12378. };
  12379. }
  12380. function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
  12381. const isWebGL2 = capabilities.isWebGL2;
  12382. const maxTextures = capabilities.maxTextures;
  12383. const maxCubemapSize = capabilities.maxCubemapSize;
  12384. const maxTextureSize = capabilities.maxTextureSize;
  12385. const maxSamples = capabilities.maxSamples;
  12386. const _videoTextures = new WeakMap();
  12387. let _canvas; // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  12388. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  12389. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  12390. let useOffscreenCanvas = false;
  12391. try {
  12392. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && new OffscreenCanvas(1, 1).getContext('2d') !== null;
  12393. } catch (err) {// Ignore any errors
  12394. }
  12395. function createCanvas(width, height) {
  12396. // Use OffscreenCanvas when available. Specially needed in web workers
  12397. return useOffscreenCanvas ? new OffscreenCanvas(width, height) : document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  12398. }
  12399. function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
  12400. let scale = 1; // handle case if texture exceeds max size
  12401. if (image.width > maxSize || image.height > maxSize) {
  12402. scale = maxSize / Math.max(image.width, image.height);
  12403. } // only perform resize if necessary
  12404. if (scale < 1 || needsPowerOfTwo === true) {
  12405. // only perform resize for certain image types
  12406. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  12407. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  12408. const width = floor(scale * image.width);
  12409. const height = floor(scale * image.height);
  12410. if (_canvas === undefined) _canvas = createCanvas(width, height); // cube textures can't reuse the same canvas
  12411. const canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
  12412. canvas.width = width;
  12413. canvas.height = height;
  12414. const context = canvas.getContext('2d');
  12415. context.drawImage(image, 0, 0, width, height);
  12416. console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
  12417. return canvas;
  12418. } else {
  12419. if ('data' in image) {
  12420. console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
  12421. }
  12422. return image;
  12423. }
  12424. }
  12425. return image;
  12426. }
  12427. function isPowerOfTwo$1(image) {
  12428. return isPowerOfTwo(image.width) && isPowerOfTwo(image.height);
  12429. }
  12430. function textureNeedsPowerOfTwo(texture) {
  12431. if (isWebGL2) return false;
  12432. return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  12433. }
  12434. function textureNeedsGenerateMipmaps(texture, supportsMips) {
  12435. return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  12436. }
  12437. function generateMipmap(target, texture, width, height) {
  12438. _gl.generateMipmap(target);
  12439. const textureProperties = properties.get(texture);
  12440. textureProperties.__maxMipLevel = Math.log2(Math.max(width, height));
  12441. }
  12442. function getInternalFormat(internalFormatName, glFormat, glType) {
  12443. if (isWebGL2 === false) return glFormat;
  12444. if (internalFormatName !== null) {
  12445. if (_gl[internalFormatName] !== undefined) return _gl[internalFormatName];
  12446. console.warn('THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'');
  12447. }
  12448. let internalFormat = glFormat;
  12449. if (glFormat === _gl.RED) {
  12450. if (glType === _gl.FLOAT) internalFormat = _gl.R32F;
  12451. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.R16F;
  12452. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.R8;
  12453. }
  12454. if (glFormat === _gl.RGB) {
  12455. if (glType === _gl.FLOAT) internalFormat = _gl.RGB32F;
  12456. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGB16F;
  12457. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RGB8;
  12458. }
  12459. if (glFormat === _gl.RGBA) {
  12460. if (glType === _gl.FLOAT) internalFormat = _gl.RGBA32F;
  12461. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGBA16F;
  12462. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RGBA8;
  12463. }
  12464. if (internalFormat === _gl.R16F || internalFormat === _gl.R32F || internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F) {
  12465. extensions.get('EXT_color_buffer_float');
  12466. }
  12467. return internalFormat;
  12468. } // Fallback filters for non-power-of-2 textures
  12469. function filterFallback(f) {
  12470. if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
  12471. return _gl.NEAREST;
  12472. }
  12473. return _gl.LINEAR;
  12474. } //
  12475. function onTextureDispose(event) {
  12476. const texture = event.target;
  12477. texture.removeEventListener('dispose', onTextureDispose);
  12478. deallocateTexture(texture);
  12479. if (texture.isVideoTexture) {
  12480. _videoTextures.delete(texture);
  12481. }
  12482. info.memory.textures--;
  12483. }
  12484. function onRenderTargetDispose(event) {
  12485. const renderTarget = event.target;
  12486. renderTarget.removeEventListener('dispose', onRenderTargetDispose);
  12487. deallocateRenderTarget(renderTarget);
  12488. } //
  12489. function deallocateTexture(texture) {
  12490. const textureProperties = properties.get(texture);
  12491. if (textureProperties.__webglInit === undefined) return;
  12492. _gl.deleteTexture(textureProperties.__webglTexture);
  12493. properties.remove(texture);
  12494. }
  12495. function deallocateRenderTarget(renderTarget) {
  12496. const texture = renderTarget.texture;
  12497. const renderTargetProperties = properties.get(renderTarget);
  12498. const textureProperties = properties.get(texture);
  12499. if (!renderTarget) return;
  12500. if (textureProperties.__webglTexture !== undefined) {
  12501. _gl.deleteTexture(textureProperties.__webglTexture);
  12502. info.memory.textures--;
  12503. }
  12504. if (renderTarget.depthTexture) {
  12505. renderTarget.depthTexture.dispose();
  12506. }
  12507. if (renderTarget.isWebGLCubeRenderTarget) {
  12508. for (let i = 0; i < 6; i++) {
  12509. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
  12510. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
  12511. }
  12512. } else {
  12513. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
  12514. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
  12515. if (renderTargetProperties.__webglMultisampledFramebuffer) _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer);
  12516. if (renderTargetProperties.__webglColorRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer);
  12517. if (renderTargetProperties.__webglDepthRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer);
  12518. }
  12519. if (renderTarget.isWebGLMultipleRenderTargets) {
  12520. for (let i = 0, il = texture.length; i < il; i++) {
  12521. const attachmentProperties = properties.get(texture[i]);
  12522. if (attachmentProperties.__webglTexture) {
  12523. _gl.deleteTexture(attachmentProperties.__webglTexture);
  12524. info.memory.textures--;
  12525. }
  12526. properties.remove(texture[i]);
  12527. }
  12528. }
  12529. properties.remove(texture);
  12530. properties.remove(renderTarget);
  12531. } //
  12532. let textureUnits = 0;
  12533. function resetTextureUnits() {
  12534. textureUnits = 0;
  12535. }
  12536. function allocateTextureUnit() {
  12537. const textureUnit = textureUnits;
  12538. if (textureUnit >= maxTextures) {
  12539. console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures);
  12540. }
  12541. textureUnits += 1;
  12542. return textureUnit;
  12543. } //
  12544. function setTexture2D(texture, slot) {
  12545. const textureProperties = properties.get(texture);
  12546. if (texture.isVideoTexture) updateVideoTexture(texture);
  12547. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  12548. const image = texture.image;
  12549. if (image === undefined) {
  12550. console.warn('THREE.WebGLRenderer: Texture marked for update but image is undefined');
  12551. } else if (image.complete === false) {
  12552. console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
  12553. } else {
  12554. uploadTexture(textureProperties, texture, slot);
  12555. return;
  12556. }
  12557. }
  12558. state.activeTexture(_gl.TEXTURE0 + slot);
  12559. state.bindTexture(_gl.TEXTURE_2D, textureProperties.__webglTexture);
  12560. }
  12561. function setTexture2DArray(texture, slot) {
  12562. const textureProperties = properties.get(texture);
  12563. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  12564. uploadTexture(textureProperties, texture, slot);
  12565. return;
  12566. }
  12567. state.activeTexture(_gl.TEXTURE0 + slot);
  12568. state.bindTexture(_gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture);
  12569. }
  12570. function setTexture3D(texture, slot) {
  12571. const textureProperties = properties.get(texture);
  12572. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  12573. uploadTexture(textureProperties, texture, slot);
  12574. return;
  12575. }
  12576. state.activeTexture(_gl.TEXTURE0 + slot);
  12577. state.bindTexture(_gl.TEXTURE_3D, textureProperties.__webglTexture);
  12578. }
  12579. function setTextureCube(texture, slot) {
  12580. const textureProperties = properties.get(texture);
  12581. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  12582. uploadCubeTexture(textureProperties, texture, slot);
  12583. return;
  12584. }
  12585. state.activeTexture(_gl.TEXTURE0 + slot);
  12586. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  12587. }
  12588. const wrappingToGL = {
  12589. [RepeatWrapping]: _gl.REPEAT,
  12590. [ClampToEdgeWrapping]: _gl.CLAMP_TO_EDGE,
  12591. [MirroredRepeatWrapping]: _gl.MIRRORED_REPEAT
  12592. };
  12593. const filterToGL = {
  12594. [NearestFilter]: _gl.NEAREST,
  12595. [NearestMipmapNearestFilter]: _gl.NEAREST_MIPMAP_NEAREST,
  12596. [NearestMipmapLinearFilter]: _gl.NEAREST_MIPMAP_LINEAR,
  12597. [LinearFilter]: _gl.LINEAR,
  12598. [LinearMipmapNearestFilter]: _gl.LINEAR_MIPMAP_NEAREST,
  12599. [LinearMipmapLinearFilter]: _gl.LINEAR_MIPMAP_LINEAR
  12600. };
  12601. function setTextureParameters(textureType, texture, supportsMips) {
  12602. if (supportsMips) {
  12603. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[texture.wrapS]);
  12604. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[texture.wrapT]);
  12605. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  12606. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[texture.wrapR]);
  12607. }
  12608. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[texture.magFilter]);
  12609. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[texture.minFilter]);
  12610. } else {
  12611. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE);
  12612. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE);
  12613. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  12614. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, _gl.CLAMP_TO_EDGE);
  12615. }
  12616. if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
  12617. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
  12618. }
  12619. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterFallback(texture.magFilter));
  12620. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterFallback(texture.minFilter));
  12621. if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  12622. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
  12623. }
  12624. }
  12625. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  12626. const extension = extensions.get('EXT_texture_filter_anisotropic');
  12627. if (texture.type === FloatType && extensions.has('OES_texture_float_linear') === false) return; // verify extension for WebGL 1 and WebGL 2
  12628. if (isWebGL2 === false && texture.type === HalfFloatType && extensions.has('OES_texture_half_float_linear') === false) return; // verify extension for WebGL 1 only
  12629. if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
  12630. _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
  12631. properties.get(texture).__currentAnisotropy = texture.anisotropy;
  12632. }
  12633. }
  12634. }
  12635. function initTexture(textureProperties, texture) {
  12636. if (textureProperties.__webglInit === undefined) {
  12637. textureProperties.__webglInit = true;
  12638. texture.addEventListener('dispose', onTextureDispose);
  12639. textureProperties.__webglTexture = _gl.createTexture();
  12640. info.memory.textures++;
  12641. }
  12642. }
  12643. function uploadTexture(textureProperties, texture, slot) {
  12644. let textureType = _gl.TEXTURE_2D;
  12645. if (texture.isDataTexture2DArray) textureType = _gl.TEXTURE_2D_ARRAY;
  12646. if (texture.isDataTexture3D) textureType = _gl.TEXTURE_3D;
  12647. initTexture(textureProperties, texture);
  12648. state.activeTexture(_gl.TEXTURE0 + slot);
  12649. state.bindTexture(textureType, textureProperties.__webglTexture);
  12650. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  12651. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  12652. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  12653. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  12654. const needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo$1(texture.image) === false;
  12655. const image = resizeImage(texture.image, needsPowerOfTwo, false, maxTextureSize);
  12656. const supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  12657. glFormat = utils.convert(texture.format);
  12658. let glType = utils.convert(texture.type),
  12659. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  12660. setTextureParameters(textureType, texture, supportsMips);
  12661. let mipmap;
  12662. const mipmaps = texture.mipmaps;
  12663. if (texture.isDepthTexture) {
  12664. // populate depth texture with dummy data
  12665. glInternalFormat = _gl.DEPTH_COMPONENT;
  12666. if (isWebGL2) {
  12667. if (texture.type === FloatType) {
  12668. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  12669. } else if (texture.type === UnsignedIntType) {
  12670. glInternalFormat = _gl.DEPTH_COMPONENT24;
  12671. } else if (texture.type === UnsignedInt248Type) {
  12672. glInternalFormat = _gl.DEPTH24_STENCIL8;
  12673. } else {
  12674. glInternalFormat = _gl.DEPTH_COMPONENT16; // WebGL2 requires sized internalformat for glTexImage2D
  12675. }
  12676. } else {
  12677. if (texture.type === FloatType) {
  12678. console.error('WebGLRenderer: Floating point depth texture requires WebGL2.');
  12679. }
  12680. } // validation checks for WebGL 1
  12681. if (texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  12682. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  12683. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  12684. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  12685. if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
  12686. console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
  12687. texture.type = UnsignedShortType;
  12688. glType = utils.convert(texture.type);
  12689. }
  12690. }
  12691. if (texture.format === DepthStencilFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  12692. // Depth stencil textures need the DEPTH_STENCIL internal format
  12693. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  12694. glInternalFormat = _gl.DEPTH_STENCIL; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  12695. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  12696. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  12697. if (texture.type !== UnsignedInt248Type) {
  12698. console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
  12699. texture.type = UnsignedInt248Type;
  12700. glType = utils.convert(texture.type);
  12701. }
  12702. } //
  12703. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  12704. } else if (texture.isDataTexture) {
  12705. // use manually created mipmaps if available
  12706. // if there are no manual mipmaps
  12707. // set 0 level mipmap and then use GL to generate other mipmap levels
  12708. if (mipmaps.length > 0 && supportsMips) {
  12709. for (let i = 0, il = mipmaps.length; i < il; i++) {
  12710. mipmap = mipmaps[i];
  12711. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  12712. }
  12713. texture.generateMipmaps = false;
  12714. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12715. } else {
  12716. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
  12717. textureProperties.__maxMipLevel = 0;
  12718. }
  12719. } else if (texture.isCompressedTexture) {
  12720. for (let i = 0, il = mipmaps.length; i < il; i++) {
  12721. mipmap = mipmaps[i];
  12722. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  12723. if (glFormat !== null) {
  12724. state.compressedTexImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  12725. } else {
  12726. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
  12727. }
  12728. } else {
  12729. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  12730. }
  12731. }
  12732. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12733. } else if (texture.isDataTexture2DArray) {
  12734. state.texImage3D(_gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  12735. textureProperties.__maxMipLevel = 0;
  12736. } else if (texture.isDataTexture3D) {
  12737. state.texImage3D(_gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  12738. textureProperties.__maxMipLevel = 0;
  12739. } else {
  12740. // regular Texture (image, video, canvas)
  12741. // use manually created mipmaps if available
  12742. // if there are no manual mipmaps
  12743. // set 0 level mipmap and then use GL to generate other mipmap levels
  12744. if (mipmaps.length > 0 && supportsMips) {
  12745. for (let i = 0, il = mipmaps.length; i < il; i++) {
  12746. mipmap = mipmaps[i];
  12747. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap);
  12748. }
  12749. texture.generateMipmaps = false;
  12750. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12751. } else {
  12752. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image);
  12753. textureProperties.__maxMipLevel = 0;
  12754. }
  12755. }
  12756. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  12757. generateMipmap(textureType, texture, image.width, image.height);
  12758. }
  12759. textureProperties.__version = texture.version;
  12760. if (texture.onUpdate) texture.onUpdate(texture);
  12761. }
  12762. function uploadCubeTexture(textureProperties, texture, slot) {
  12763. if (texture.image.length !== 6) return;
  12764. initTexture(textureProperties, texture);
  12765. state.activeTexture(_gl.TEXTURE0 + slot);
  12766. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  12767. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  12768. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  12769. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  12770. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  12771. const isCompressed = texture && (texture.isCompressedTexture || texture.image[0].isCompressedTexture);
  12772. const isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
  12773. const cubeImage = [];
  12774. for (let i = 0; i < 6; i++) {
  12775. if (!isCompressed && !isDataTexture) {
  12776. cubeImage[i] = resizeImage(texture.image[i], false, true, maxCubemapSize);
  12777. } else {
  12778. cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
  12779. }
  12780. }
  12781. const image = cubeImage[0],
  12782. supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  12783. glFormat = utils.convert(texture.format),
  12784. glType = utils.convert(texture.type),
  12785. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  12786. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  12787. let mipmaps;
  12788. if (isCompressed) {
  12789. for (let i = 0; i < 6; i++) {
  12790. mipmaps = cubeImage[i].mipmaps;
  12791. for (let j = 0; j < mipmaps.length; j++) {
  12792. const mipmap = mipmaps[j];
  12793. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  12794. if (glFormat !== null) {
  12795. state.compressedTexImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  12796. } else {
  12797. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
  12798. }
  12799. } else {
  12800. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  12801. }
  12802. }
  12803. }
  12804. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12805. } else {
  12806. mipmaps = texture.mipmaps;
  12807. for (let i = 0; i < 6; i++) {
  12808. if (isDataTexture) {
  12809. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data);
  12810. for (let j = 0; j < mipmaps.length; j++) {
  12811. const mipmap = mipmaps[j];
  12812. const mipmapImage = mipmap.image[i].image;
  12813. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
  12814. }
  12815. } else {
  12816. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]);
  12817. for (let j = 0; j < mipmaps.length; j++) {
  12818. const mipmap = mipmaps[j];
  12819. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]);
  12820. }
  12821. }
  12822. }
  12823. textureProperties.__maxMipLevel = mipmaps.length;
  12824. }
  12825. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  12826. // We assume images for cube map have the same size.
  12827. generateMipmap(_gl.TEXTURE_CUBE_MAP, texture, image.width, image.height);
  12828. }
  12829. textureProperties.__version = texture.version;
  12830. if (texture.onUpdate) texture.onUpdate(texture);
  12831. } // Render targets
  12832. // Setup storage for target texture and bind it to correct framebuffer
  12833. function setupFrameBufferTexture(framebuffer, renderTarget, texture, attachment, textureTarget) {
  12834. const glFormat = utils.convert(texture.format);
  12835. const glType = utils.convert(texture.type);
  12836. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  12837. if (textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY) {
  12838. state.texImage3D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null);
  12839. } else {
  12840. state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
  12841. }
  12842. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  12843. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, attachment, textureTarget, properties.get(texture).__webglTexture, 0);
  12844. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  12845. } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  12846. function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
  12847. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer);
  12848. if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
  12849. let glInternalFormat = _gl.DEPTH_COMPONENT16;
  12850. if (isMultisample) {
  12851. const depthTexture = renderTarget.depthTexture;
  12852. if (depthTexture && depthTexture.isDepthTexture) {
  12853. if (depthTexture.type === FloatType) {
  12854. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  12855. } else if (depthTexture.type === UnsignedIntType) {
  12856. glInternalFormat = _gl.DEPTH_COMPONENT24;
  12857. }
  12858. }
  12859. const samples = getRenderTargetSamples(renderTarget);
  12860. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  12861. } else {
  12862. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  12863. }
  12864. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  12865. } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
  12866. if (isMultisample) {
  12867. const samples = getRenderTargetSamples(renderTarget);
  12868. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height);
  12869. } else {
  12870. _gl.renderbufferStorage(_gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height);
  12871. }
  12872. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  12873. } else {
  12874. // Use the first texture for MRT so far
  12875. const texture = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture[0] : renderTarget.texture;
  12876. const glFormat = utils.convert(texture.format);
  12877. const glType = utils.convert(texture.type);
  12878. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  12879. if (isMultisample) {
  12880. const samples = getRenderTargetSamples(renderTarget);
  12881. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  12882. } else {
  12883. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  12884. }
  12885. }
  12886. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  12887. } // Setup resources for a Depth Texture for a FBO (needs an extension)
  12888. function setupDepthTexture(framebuffer, renderTarget) {
  12889. const isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget;
  12890. if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
  12891. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  12892. if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
  12893. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  12894. } // upload an empty depth texture with framebuffer size
  12895. if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
  12896. renderTarget.depthTexture.image.width = renderTarget.width;
  12897. renderTarget.depthTexture.image.height = renderTarget.height;
  12898. renderTarget.depthTexture.needsUpdate = true;
  12899. }
  12900. setTexture2D(renderTarget.depthTexture, 0);
  12901. const webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
  12902. if (renderTarget.depthTexture.format === DepthFormat) {
  12903. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  12904. } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
  12905. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  12906. } else {
  12907. throw new Error('Unknown depthTexture format');
  12908. }
  12909. } // Setup GL resources for a non-texture depth buffer
  12910. function setupDepthRenderbuffer(renderTarget) {
  12911. const renderTargetProperties = properties.get(renderTarget);
  12912. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  12913. if (renderTarget.depthTexture) {
  12914. if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
  12915. setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
  12916. } else {
  12917. if (isCube) {
  12918. renderTargetProperties.__webglDepthbuffer = [];
  12919. for (let i = 0; i < 6; i++) {
  12920. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[i]);
  12921. renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
  12922. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false);
  12923. }
  12924. } else {
  12925. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  12926. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  12927. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false);
  12928. }
  12929. }
  12930. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  12931. } // Set up GL resources for the render target
  12932. function setupRenderTarget(renderTarget) {
  12933. const texture = renderTarget.texture;
  12934. const renderTargetProperties = properties.get(renderTarget);
  12935. const textureProperties = properties.get(texture);
  12936. renderTarget.addEventListener('dispose', onRenderTargetDispose);
  12937. if (renderTarget.isWebGLMultipleRenderTargets !== true) {
  12938. textureProperties.__webglTexture = _gl.createTexture();
  12939. textureProperties.__version = texture.version;
  12940. info.memory.textures++;
  12941. }
  12942. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  12943. const isMultipleRenderTargets = renderTarget.isWebGLMultipleRenderTargets === true;
  12944. const isMultisample = renderTarget.isWebGLMultisampleRenderTarget === true;
  12945. const isRenderTarget3D = texture.isDataTexture3D || texture.isDataTexture2DArray;
  12946. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2; // Handles WebGL2 RGBFormat fallback - #18858
  12947. if (isWebGL2 && texture.format === RGBFormat && (texture.type === FloatType || texture.type === HalfFloatType)) {
  12948. texture.format = RGBAFormat;
  12949. console.warn('THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.');
  12950. } // Setup framebuffer
  12951. if (isCube) {
  12952. renderTargetProperties.__webglFramebuffer = [];
  12953. for (let i = 0; i < 6; i++) {
  12954. renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
  12955. }
  12956. } else {
  12957. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  12958. if (isMultipleRenderTargets) {
  12959. if (capabilities.drawBuffers) {
  12960. const textures = renderTarget.texture;
  12961. for (let i = 0, il = textures.length; i < il; i++) {
  12962. const attachmentProperties = properties.get(textures[i]);
  12963. if (attachmentProperties.__webglTexture === undefined) {
  12964. attachmentProperties.__webglTexture = _gl.createTexture();
  12965. info.memory.textures++;
  12966. }
  12967. }
  12968. } else {
  12969. console.warn('THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.');
  12970. }
  12971. } else if (isMultisample) {
  12972. if (isWebGL2) {
  12973. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  12974. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  12975. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer);
  12976. const glFormat = utils.convert(texture.format);
  12977. const glType = utils.convert(texture.type);
  12978. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  12979. const samples = getRenderTargetSamples(renderTarget);
  12980. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  12981. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  12982. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer);
  12983. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  12984. if (renderTarget.depthBuffer) {
  12985. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  12986. setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
  12987. }
  12988. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  12989. } else {
  12990. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  12991. }
  12992. }
  12993. } // Setup color buffer
  12994. if (isCube) {
  12995. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  12996. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  12997. for (let i = 0; i < 6; i++) {
  12998. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i);
  12999. }
  13000. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13001. generateMipmap(_gl.TEXTURE_CUBE_MAP, texture, renderTarget.width, renderTarget.height);
  13002. }
  13003. state.bindTexture(_gl.TEXTURE_CUBE_MAP, null);
  13004. } else if (isMultipleRenderTargets) {
  13005. const textures = renderTarget.texture;
  13006. for (let i = 0, il = textures.length; i < il; i++) {
  13007. const attachment = textures[i];
  13008. const attachmentProperties = properties.get(attachment);
  13009. state.bindTexture(_gl.TEXTURE_2D, attachmentProperties.__webglTexture);
  13010. setTextureParameters(_gl.TEXTURE_2D, attachment, supportsMips);
  13011. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D);
  13012. if (textureNeedsGenerateMipmaps(attachment, supportsMips)) {
  13013. generateMipmap(_gl.TEXTURE_2D, attachment, renderTarget.width, renderTarget.height);
  13014. }
  13015. }
  13016. state.bindTexture(_gl.TEXTURE_2D, null);
  13017. } else {
  13018. let glTextureType = _gl.TEXTURE_2D;
  13019. if (isRenderTarget3D) {
  13020. // Render targets containing layers, i.e: Texture 3D and 2d arrays
  13021. if (isWebGL2) {
  13022. const isTexture3D = texture.isDataTexture3D;
  13023. glTextureType = isTexture3D ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  13024. } else {
  13025. console.warn('THREE.DataTexture3D and THREE.DataTexture2DArray only supported with WebGL2.');
  13026. }
  13027. }
  13028. state.bindTexture(glTextureType, textureProperties.__webglTexture);
  13029. setTextureParameters(glTextureType, texture, supportsMips);
  13030. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType);
  13031. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13032. generateMipmap(_gl.TEXTURE_2D, texture, renderTarget.width, renderTarget.height);
  13033. }
  13034. state.bindTexture(_gl.TEXTURE_2D, null);
  13035. } // Setup depth and stencil buffers
  13036. if (renderTarget.depthBuffer) {
  13037. setupDepthRenderbuffer(renderTarget);
  13038. }
  13039. }
  13040. function updateRenderTargetMipmap(renderTarget) {
  13041. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2;
  13042. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [renderTarget.texture];
  13043. for (let i = 0, il = textures.length; i < il; i++) {
  13044. const texture = textures[i];
  13045. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13046. const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  13047. const webglTexture = properties.get(texture).__webglTexture;
  13048. state.bindTexture(target, webglTexture);
  13049. generateMipmap(target, texture, renderTarget.width, renderTarget.height);
  13050. state.bindTexture(target, null);
  13051. }
  13052. }
  13053. }
  13054. function updateMultisampleRenderTarget(renderTarget) {
  13055. if (renderTarget.isWebGLMultisampleRenderTarget) {
  13056. if (isWebGL2) {
  13057. const width = renderTarget.width;
  13058. const height = renderTarget.height;
  13059. let mask = _gl.COLOR_BUFFER_BIT;
  13060. if (renderTarget.depthBuffer) mask |= _gl.DEPTH_BUFFER_BIT;
  13061. if (renderTarget.stencilBuffer) mask |= _gl.STENCIL_BUFFER_BIT;
  13062. const renderTargetProperties = properties.get(renderTarget);
  13063. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  13064. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  13065. _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST);
  13066. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null);
  13067. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  13068. } else {
  13069. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  13070. }
  13071. }
  13072. }
  13073. function getRenderTargetSamples(renderTarget) {
  13074. return isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ? Math.min(maxSamples, renderTarget.samples) : 0;
  13075. }
  13076. function updateVideoTexture(texture) {
  13077. const frame = info.render.frame; // Check the last frame we updated the VideoTexture
  13078. if (_videoTextures.get(texture) !== frame) {
  13079. _videoTextures.set(texture, frame);
  13080. texture.update();
  13081. }
  13082. } // backwards compatibility
  13083. let warnedTexture2D = false;
  13084. let warnedTextureCube = false;
  13085. function safeSetTexture2D(texture, slot) {
  13086. if (texture && texture.isWebGLRenderTarget) {
  13087. if (warnedTexture2D === false) {
  13088. console.warn('THREE.WebGLTextures.safeSetTexture2D: don\'t use render targets as textures. Use their .texture property instead.');
  13089. warnedTexture2D = true;
  13090. }
  13091. texture = texture.texture;
  13092. }
  13093. setTexture2D(texture, slot);
  13094. }
  13095. function safeSetTextureCube(texture, slot) {
  13096. if (texture && texture.isWebGLCubeRenderTarget) {
  13097. if (warnedTextureCube === false) {
  13098. console.warn('THREE.WebGLTextures.safeSetTextureCube: don\'t use cube render targets as textures. Use their .texture property instead.');
  13099. warnedTextureCube = true;
  13100. }
  13101. texture = texture.texture;
  13102. }
  13103. setTextureCube(texture, slot);
  13104. } //
  13105. this.allocateTextureUnit = allocateTextureUnit;
  13106. this.resetTextureUnits = resetTextureUnits;
  13107. this.setTexture2D = setTexture2D;
  13108. this.setTexture2DArray = setTexture2DArray;
  13109. this.setTexture3D = setTexture3D;
  13110. this.setTextureCube = setTextureCube;
  13111. this.setupRenderTarget = setupRenderTarget;
  13112. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  13113. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  13114. this.safeSetTexture2D = safeSetTexture2D;
  13115. this.safeSetTextureCube = safeSetTextureCube;
  13116. }
  13117. function WebGLUtils(gl, extensions, capabilities) {
  13118. const isWebGL2 = capabilities.isWebGL2;
  13119. function convert(p) {
  13120. let extension;
  13121. if (p === UnsignedByteType) return gl.UNSIGNED_BYTE;
  13122. if (p === UnsignedShort4444Type) return gl.UNSIGNED_SHORT_4_4_4_4;
  13123. if (p === UnsignedShort5551Type) return gl.UNSIGNED_SHORT_5_5_5_1;
  13124. if (p === UnsignedShort565Type) return gl.UNSIGNED_SHORT_5_6_5;
  13125. if (p === ByteType) return gl.BYTE;
  13126. if (p === ShortType) return gl.SHORT;
  13127. if (p === UnsignedShortType) return gl.UNSIGNED_SHORT;
  13128. if (p === IntType) return gl.INT;
  13129. if (p === UnsignedIntType) return gl.UNSIGNED_INT;
  13130. if (p === FloatType) return gl.FLOAT;
  13131. if (p === HalfFloatType) {
  13132. if (isWebGL2) return gl.HALF_FLOAT;
  13133. extension = extensions.get('OES_texture_half_float');
  13134. if (extension !== null) {
  13135. return extension.HALF_FLOAT_OES;
  13136. } else {
  13137. return null;
  13138. }
  13139. }
  13140. if (p === AlphaFormat) return gl.ALPHA;
  13141. if (p === RGBFormat) return gl.RGB;
  13142. if (p === RGBAFormat) return gl.RGBA;
  13143. if (p === LuminanceFormat) return gl.LUMINANCE;
  13144. if (p === LuminanceAlphaFormat) return gl.LUMINANCE_ALPHA;
  13145. if (p === DepthFormat) return gl.DEPTH_COMPONENT;
  13146. if (p === DepthStencilFormat) return gl.DEPTH_STENCIL;
  13147. if (p === RedFormat) return gl.RED; // WebGL2 formats.
  13148. if (p === RedIntegerFormat) return gl.RED_INTEGER;
  13149. if (p === RGFormat) return gl.RG;
  13150. if (p === RGIntegerFormat) return gl.RG_INTEGER;
  13151. if (p === RGBIntegerFormat) return gl.RGB_INTEGER;
  13152. if (p === RGBAIntegerFormat) return gl.RGBA_INTEGER;
  13153. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  13154. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  13155. if (extension !== null) {
  13156. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13157. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13158. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13159. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13160. } else {
  13161. return null;
  13162. }
  13163. }
  13164. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  13165. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  13166. if (extension !== null) {
  13167. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  13168. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  13169. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  13170. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  13171. } else {
  13172. return null;
  13173. }
  13174. }
  13175. if (p === RGB_ETC1_Format) {
  13176. extension = extensions.get('WEBGL_compressed_texture_etc1');
  13177. if (extension !== null) {
  13178. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  13179. } else {
  13180. return null;
  13181. }
  13182. }
  13183. if (p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format) {
  13184. extension = extensions.get('WEBGL_compressed_texture_etc');
  13185. if (extension !== null) {
  13186. if (p === RGB_ETC2_Format) return extension.COMPRESSED_RGB8_ETC2;
  13187. if (p === RGBA_ETC2_EAC_Format) return extension.COMPRESSED_RGBA8_ETC2_EAC;
  13188. }
  13189. }
  13190. 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) {
  13191. extension = extensions.get('WEBGL_compressed_texture_astc');
  13192. if (extension !== null) {
  13193. // TODO Complete?
  13194. return p;
  13195. } else {
  13196. return null;
  13197. }
  13198. }
  13199. if (p === RGBA_BPTC_Format) {
  13200. extension = extensions.get('EXT_texture_compression_bptc');
  13201. if (extension !== null) {
  13202. // TODO Complete?
  13203. return p;
  13204. } else {
  13205. return null;
  13206. }
  13207. }
  13208. if (p === UnsignedInt248Type) {
  13209. if (isWebGL2) return gl.UNSIGNED_INT_24_8;
  13210. extension = extensions.get('WEBGL_depth_texture');
  13211. if (extension !== null) {
  13212. return extension.UNSIGNED_INT_24_8_WEBGL;
  13213. } else {
  13214. return null;
  13215. }
  13216. }
  13217. }
  13218. return {
  13219. convert: convert
  13220. };
  13221. }
  13222. class ArrayCamera extends PerspectiveCamera {
  13223. constructor(array = []) {
  13224. super();
  13225. this.cameras = array;
  13226. }
  13227. }
  13228. ArrayCamera.prototype.isArrayCamera = true;
  13229. class Group extends Object3D {
  13230. constructor() {
  13231. super();
  13232. this.type = 'Group';
  13233. }
  13234. }
  13235. Group.prototype.isGroup = true;
  13236. const _moveEvent = {
  13237. type: 'move'
  13238. };
  13239. class WebXRController {
  13240. constructor() {
  13241. this._targetRay = null;
  13242. this._grip = null;
  13243. this._hand = null;
  13244. }
  13245. getHandSpace() {
  13246. if (this._hand === null) {
  13247. this._hand = new Group();
  13248. this._hand.matrixAutoUpdate = false;
  13249. this._hand.visible = false;
  13250. this._hand.joints = {};
  13251. this._hand.inputState = {
  13252. pinching: false
  13253. };
  13254. }
  13255. return this._hand;
  13256. }
  13257. getTargetRaySpace() {
  13258. if (this._targetRay === null) {
  13259. this._targetRay = new Group();
  13260. this._targetRay.matrixAutoUpdate = false;
  13261. this._targetRay.visible = false;
  13262. this._targetRay.hasLinearVelocity = false;
  13263. this._targetRay.linearVelocity = new Vector3();
  13264. this._targetRay.hasAngularVelocity = false;
  13265. this._targetRay.angularVelocity = new Vector3();
  13266. }
  13267. return this._targetRay;
  13268. }
  13269. getGripSpace() {
  13270. if (this._grip === null) {
  13271. this._grip = new Group();
  13272. this._grip.matrixAutoUpdate = false;
  13273. this._grip.visible = false;
  13274. this._grip.hasLinearVelocity = false;
  13275. this._grip.linearVelocity = new Vector3();
  13276. this._grip.hasAngularVelocity = false;
  13277. this._grip.angularVelocity = new Vector3();
  13278. }
  13279. return this._grip;
  13280. }
  13281. dispatchEvent(event) {
  13282. if (this._targetRay !== null) {
  13283. this._targetRay.dispatchEvent(event);
  13284. }
  13285. if (this._grip !== null) {
  13286. this._grip.dispatchEvent(event);
  13287. }
  13288. if (this._hand !== null) {
  13289. this._hand.dispatchEvent(event);
  13290. }
  13291. return this;
  13292. }
  13293. disconnect(inputSource) {
  13294. this.dispatchEvent({
  13295. type: 'disconnected',
  13296. data: inputSource
  13297. });
  13298. if (this._targetRay !== null) {
  13299. this._targetRay.visible = false;
  13300. }
  13301. if (this._grip !== null) {
  13302. this._grip.visible = false;
  13303. }
  13304. if (this._hand !== null) {
  13305. this._hand.visible = false;
  13306. }
  13307. return this;
  13308. }
  13309. update(inputSource, frame, referenceSpace) {
  13310. let inputPose = null;
  13311. let gripPose = null;
  13312. let handPose = null;
  13313. const targetRay = this._targetRay;
  13314. const grip = this._grip;
  13315. const hand = this._hand;
  13316. if (inputSource && frame.session.visibilityState !== 'visible-blurred') {
  13317. if (targetRay !== null) {
  13318. inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace);
  13319. if (inputPose !== null) {
  13320. targetRay.matrix.fromArray(inputPose.transform.matrix);
  13321. targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale);
  13322. if (inputPose.linearVelocity) {
  13323. targetRay.hasLinearVelocity = true;
  13324. targetRay.linearVelocity.copy(inputPose.linearVelocity);
  13325. } else {
  13326. targetRay.hasLinearVelocity = false;
  13327. }
  13328. if (inputPose.angularVelocity) {
  13329. targetRay.hasAngularVelocity = true;
  13330. targetRay.angularVelocity.copy(inputPose.angularVelocity);
  13331. } else {
  13332. targetRay.hasAngularVelocity = false;
  13333. }
  13334. this.dispatchEvent(_moveEvent);
  13335. }
  13336. }
  13337. if (hand && inputSource.hand) {
  13338. handPose = true;
  13339. for (const inputjoint of inputSource.hand.values()) {
  13340. // Update the joints groups with the XRJoint poses
  13341. const jointPose = frame.getJointPose(inputjoint, referenceSpace);
  13342. if (hand.joints[inputjoint.jointName] === undefined) {
  13343. // The transform of this joint will be updated with the joint pose on each frame
  13344. const joint = new Group();
  13345. joint.matrixAutoUpdate = false;
  13346. joint.visible = false;
  13347. hand.joints[inputjoint.jointName] = joint; // ??
  13348. hand.add(joint);
  13349. }
  13350. const joint = hand.joints[inputjoint.jointName];
  13351. if (jointPose !== null) {
  13352. joint.matrix.fromArray(jointPose.transform.matrix);
  13353. joint.matrix.decompose(joint.position, joint.rotation, joint.scale);
  13354. joint.jointRadius = jointPose.radius;
  13355. }
  13356. joint.visible = jointPose !== null;
  13357. } // Custom events
  13358. // Check pinchz
  13359. const indexTip = hand.joints['index-finger-tip'];
  13360. const thumbTip = hand.joints['thumb-tip'];
  13361. const distance = indexTip.position.distanceTo(thumbTip.position);
  13362. const distanceToPinch = 0.02;
  13363. const threshold = 0.005;
  13364. if (hand.inputState.pinching && distance > distanceToPinch + threshold) {
  13365. hand.inputState.pinching = false;
  13366. this.dispatchEvent({
  13367. type: 'pinchend',
  13368. handedness: inputSource.handedness,
  13369. target: this
  13370. });
  13371. } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) {
  13372. hand.inputState.pinching = true;
  13373. this.dispatchEvent({
  13374. type: 'pinchstart',
  13375. handedness: inputSource.handedness,
  13376. target: this
  13377. });
  13378. }
  13379. } else {
  13380. if (grip !== null && inputSource.gripSpace) {
  13381. gripPose = frame.getPose(inputSource.gripSpace, referenceSpace);
  13382. if (gripPose !== null) {
  13383. grip.matrix.fromArray(gripPose.transform.matrix);
  13384. grip.matrix.decompose(grip.position, grip.rotation, grip.scale);
  13385. if (gripPose.linearVelocity) {
  13386. grip.hasLinearVelocity = true;
  13387. grip.linearVelocity.copy(gripPose.linearVelocity);
  13388. } else {
  13389. grip.hasLinearVelocity = false;
  13390. }
  13391. if (gripPose.angularVelocity) {
  13392. grip.hasAngularVelocity = true;
  13393. grip.angularVelocity.copy(gripPose.angularVelocity);
  13394. } else {
  13395. grip.hasAngularVelocity = false;
  13396. }
  13397. }
  13398. }
  13399. }
  13400. }
  13401. if (targetRay !== null) {
  13402. targetRay.visible = inputPose !== null;
  13403. }
  13404. if (grip !== null) {
  13405. grip.visible = gripPose !== null;
  13406. }
  13407. if (hand !== null) {
  13408. hand.visible = handPose !== null;
  13409. }
  13410. return this;
  13411. }
  13412. }
  13413. class WebXRManager extends EventDispatcher {
  13414. constructor(renderer, gl) {
  13415. super();
  13416. const scope = this;
  13417. const state = renderer.state;
  13418. let session = null;
  13419. let framebufferScaleFactor = 1.0;
  13420. let referenceSpace = null;
  13421. let referenceSpaceType = 'local-floor';
  13422. let pose = null;
  13423. const controllers = [];
  13424. const inputSourcesMap = new Map(); //
  13425. const cameraL = new PerspectiveCamera();
  13426. cameraL.layers.enable(1);
  13427. cameraL.viewport = new Vector4();
  13428. const cameraR = new PerspectiveCamera();
  13429. cameraR.layers.enable(2);
  13430. cameraR.viewport = new Vector4();
  13431. const cameras = [cameraL, cameraR];
  13432. const cameraVR = new ArrayCamera();
  13433. cameraVR.layers.enable(1);
  13434. cameraVR.layers.enable(2);
  13435. let _currentDepthNear = null;
  13436. let _currentDepthFar = null; //
  13437. this.enabled = false;
  13438. this.isPresenting = false;
  13439. this.getController = function (index) {
  13440. let controller = controllers[index];
  13441. if (controller === undefined) {
  13442. controller = new WebXRController();
  13443. controllers[index] = controller;
  13444. }
  13445. return controller.getTargetRaySpace();
  13446. };
  13447. this.getControllerGrip = function (index) {
  13448. let controller = controllers[index];
  13449. if (controller === undefined) {
  13450. controller = new WebXRController();
  13451. controllers[index] = controller;
  13452. }
  13453. return controller.getGripSpace();
  13454. };
  13455. this.getHand = function (index) {
  13456. let controller = controllers[index];
  13457. if (controller === undefined) {
  13458. controller = new WebXRController();
  13459. controllers[index] = controller;
  13460. }
  13461. return controller.getHandSpace();
  13462. }; //
  13463. function onSessionEvent(event) {
  13464. const controller = inputSourcesMap.get(event.inputSource);
  13465. if (controller) {
  13466. controller.dispatchEvent({
  13467. type: event.type,
  13468. data: event.inputSource
  13469. });
  13470. }
  13471. }
  13472. function onSessionEnd() {
  13473. inputSourcesMap.forEach(function (controller, inputSource) {
  13474. controller.disconnect(inputSource);
  13475. });
  13476. inputSourcesMap.clear();
  13477. _currentDepthNear = null;
  13478. _currentDepthFar = null; // restore framebuffer/rendering state
  13479. state.bindXRFramebuffer(null);
  13480. renderer.setRenderTarget(renderer.getRenderTarget()); //
  13481. animation.stop();
  13482. scope.isPresenting = false;
  13483. scope.dispatchEvent({
  13484. type: 'sessionend'
  13485. });
  13486. }
  13487. this.setFramebufferScaleFactor = function (value) {
  13488. framebufferScaleFactor = value;
  13489. if (scope.isPresenting === true) {
  13490. console.warn('THREE.WebXRManager: Cannot change framebuffer scale while presenting.');
  13491. }
  13492. };
  13493. this.setReferenceSpaceType = function (value) {
  13494. referenceSpaceType = value;
  13495. if (scope.isPresenting === true) {
  13496. console.warn('THREE.WebXRManager: Cannot change reference space type while presenting.');
  13497. }
  13498. };
  13499. this.getReferenceSpace = function () {
  13500. return referenceSpace;
  13501. };
  13502. this.getSession = function () {
  13503. return session;
  13504. };
  13505. this.setSession = async function (value) {
  13506. session = value;
  13507. if (session !== null) {
  13508. session.addEventListener('select', onSessionEvent);
  13509. session.addEventListener('selectstart', onSessionEvent);
  13510. session.addEventListener('selectend', onSessionEvent);
  13511. session.addEventListener('squeeze', onSessionEvent);
  13512. session.addEventListener('squeezestart', onSessionEvent);
  13513. session.addEventListener('squeezeend', onSessionEvent);
  13514. session.addEventListener('end', onSessionEnd);
  13515. session.addEventListener('inputsourceschange', onInputSourcesChange);
  13516. const attributes = gl.getContextAttributes();
  13517. if (attributes.xrCompatible !== true) {
  13518. await gl.makeXRCompatible();
  13519. }
  13520. const layerInit = {
  13521. antialias: attributes.antialias,
  13522. alpha: attributes.alpha,
  13523. depth: attributes.depth,
  13524. stencil: attributes.stencil,
  13525. framebufferScaleFactor: framebufferScaleFactor
  13526. }; // eslint-disable-next-line no-undef
  13527. const baseLayer = new XRWebGLLayer(session, gl, layerInit);
  13528. session.updateRenderState({
  13529. baseLayer: baseLayer
  13530. });
  13531. referenceSpace = await session.requestReferenceSpace(referenceSpaceType);
  13532. animation.setContext(session);
  13533. animation.start();
  13534. scope.isPresenting = true;
  13535. scope.dispatchEvent({
  13536. type: 'sessionstart'
  13537. });
  13538. }
  13539. };
  13540. function onInputSourcesChange(event) {
  13541. const inputSources = session.inputSources; // Assign inputSources to available controllers
  13542. for (let i = 0; i < controllers.length; i++) {
  13543. inputSourcesMap.set(inputSources[i], controllers[i]);
  13544. } // Notify disconnected
  13545. for (let i = 0; i < event.removed.length; i++) {
  13546. const inputSource = event.removed[i];
  13547. const controller = inputSourcesMap.get(inputSource);
  13548. if (controller) {
  13549. controller.dispatchEvent({
  13550. type: 'disconnected',
  13551. data: inputSource
  13552. });
  13553. inputSourcesMap.delete(inputSource);
  13554. }
  13555. } // Notify connected
  13556. for (let i = 0; i < event.added.length; i++) {
  13557. const inputSource = event.added[i];
  13558. const controller = inputSourcesMap.get(inputSource);
  13559. if (controller) {
  13560. controller.dispatchEvent({
  13561. type: 'connected',
  13562. data: inputSource
  13563. });
  13564. }
  13565. }
  13566. } //
  13567. const cameraLPos = new Vector3();
  13568. const cameraRPos = new Vector3();
  13569. /**
  13570. * Assumes 2 cameras that are parallel and share an X-axis, and that
  13571. * the cameras' projection and world matrices have already been set.
  13572. * And that near and far planes are identical for both cameras.
  13573. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  13574. */
  13575. function setProjectionFromUnion(camera, cameraL, cameraR) {
  13576. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  13577. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  13578. const ipd = cameraLPos.distanceTo(cameraRPos);
  13579. const projL = cameraL.projectionMatrix.elements;
  13580. const projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
  13581. // most likely identical top and bottom frustum extents.
  13582. // Use the left camera for these values.
  13583. const near = projL[14] / (projL[10] - 1);
  13584. const far = projL[14] / (projL[10] + 1);
  13585. const topFov = (projL[9] + 1) / projL[5];
  13586. const bottomFov = (projL[9] - 1) / projL[5];
  13587. const leftFov = (projL[8] - 1) / projL[0];
  13588. const rightFov = (projR[8] + 1) / projR[0];
  13589. const left = near * leftFov;
  13590. const right = near * rightFov; // Calculate the new camera's position offset from the
  13591. // left camera. xOffset should be roughly half `ipd`.
  13592. const zOffset = ipd / (-leftFov + rightFov);
  13593. const xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
  13594. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  13595. camera.translateX(xOffset);
  13596. camera.translateZ(zOffset);
  13597. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  13598. camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); // Find the union of the frustum values of the cameras and scale
  13599. // the values so that the near plane's position does not change in world space,
  13600. // although must now be relative to the new union camera.
  13601. const near2 = near + zOffset;
  13602. const far2 = far + zOffset;
  13603. const left2 = left - xOffset;
  13604. const right2 = right + (ipd - xOffset);
  13605. const top2 = topFov * far / far2 * near2;
  13606. const bottom2 = bottomFov * far / far2 * near2;
  13607. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  13608. }
  13609. function updateCamera(camera, parent) {
  13610. if (parent === null) {
  13611. camera.matrixWorld.copy(camera.matrix);
  13612. } else {
  13613. camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
  13614. }
  13615. camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  13616. }
  13617. this.getCamera = function (camera) {
  13618. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  13619. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  13620. if (_currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far) {
  13621. // Note that the new renderState won't apply until the next frame. See #18320
  13622. session.updateRenderState({
  13623. depthNear: cameraVR.near,
  13624. depthFar: cameraVR.far
  13625. });
  13626. _currentDepthNear = cameraVR.near;
  13627. _currentDepthFar = cameraVR.far;
  13628. }
  13629. const parent = camera.parent;
  13630. const cameras = cameraVR.cameras;
  13631. updateCamera(cameraVR, parent);
  13632. for (let i = 0; i < cameras.length; i++) {
  13633. updateCamera(cameras[i], parent);
  13634. } // update camera and its children
  13635. camera.matrixWorld.copy(cameraVR.matrixWorld);
  13636. camera.matrix.copy(cameraVR.matrix);
  13637. camera.matrix.decompose(camera.position, camera.quaternion, camera.scale);
  13638. const children = camera.children;
  13639. for (let i = 0, l = children.length; i < l; i++) {
  13640. children[i].updateMatrixWorld(true);
  13641. } // update projection matrix for proper view frustum culling
  13642. if (cameras.length === 2) {
  13643. setProjectionFromUnion(cameraVR, cameraL, cameraR);
  13644. } else {
  13645. // assume single camera setup (AR)
  13646. cameraVR.projectionMatrix.copy(cameraL.projectionMatrix);
  13647. }
  13648. return cameraVR;
  13649. }; // Animation Loop
  13650. let onAnimationFrameCallback = null;
  13651. function onAnimationFrame(time, frame) {
  13652. pose = frame.getViewerPose(referenceSpace);
  13653. if (pose !== null) {
  13654. const views = pose.views;
  13655. const baseLayer = session.renderState.baseLayer;
  13656. state.bindXRFramebuffer(baseLayer.framebuffer);
  13657. let cameraVRNeedsUpdate = false; // check if it's necessary to rebuild cameraVR's camera list
  13658. if (views.length !== cameraVR.cameras.length) {
  13659. cameraVR.cameras.length = 0;
  13660. cameraVRNeedsUpdate = true;
  13661. }
  13662. for (let i = 0; i < views.length; i++) {
  13663. const view = views[i];
  13664. const viewport = baseLayer.getViewport(view);
  13665. const camera = cameras[i];
  13666. camera.matrix.fromArray(view.transform.matrix);
  13667. camera.projectionMatrix.fromArray(view.projectionMatrix);
  13668. camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
  13669. if (i === 0) {
  13670. cameraVR.matrix.copy(camera.matrix);
  13671. }
  13672. if (cameraVRNeedsUpdate === true) {
  13673. cameraVR.cameras.push(camera);
  13674. }
  13675. }
  13676. } //
  13677. const inputSources = session.inputSources;
  13678. for (let i = 0; i < controllers.length; i++) {
  13679. const controller = controllers[i];
  13680. const inputSource = inputSources[i];
  13681. controller.update(inputSource, frame, referenceSpace);
  13682. }
  13683. if (onAnimationFrameCallback) onAnimationFrameCallback(time, frame);
  13684. }
  13685. const animation = new WebGLAnimation();
  13686. animation.setAnimationLoop(onAnimationFrame);
  13687. this.setAnimationLoop = function (callback) {
  13688. onAnimationFrameCallback = callback;
  13689. };
  13690. this.dispose = function () {};
  13691. }
  13692. }
  13693. function WebGLMaterials(properties) {
  13694. function refreshFogUniforms(uniforms, fog) {
  13695. uniforms.fogColor.value.copy(fog.color);
  13696. if (fog.isFog) {
  13697. uniforms.fogNear.value = fog.near;
  13698. uniforms.fogFar.value = fog.far;
  13699. } else if (fog.isFogExp2) {
  13700. uniforms.fogDensity.value = fog.density;
  13701. }
  13702. }
  13703. function refreshMaterialUniforms(uniforms, material, pixelRatio, height) {
  13704. if (material.isMeshBasicMaterial) {
  13705. refreshUniformsCommon(uniforms, material);
  13706. } else if (material.isMeshLambertMaterial) {
  13707. refreshUniformsCommon(uniforms, material);
  13708. refreshUniformsLambert(uniforms, material);
  13709. } else if (material.isMeshToonMaterial) {
  13710. refreshUniformsCommon(uniforms, material);
  13711. refreshUniformsToon(uniforms, material);
  13712. } else if (material.isMeshPhongMaterial) {
  13713. refreshUniformsCommon(uniforms, material);
  13714. refreshUniformsPhong(uniforms, material);
  13715. } else if (material.isMeshStandardMaterial) {
  13716. refreshUniformsCommon(uniforms, material);
  13717. if (material.isMeshPhysicalMaterial) {
  13718. refreshUniformsPhysical(uniforms, material);
  13719. } else {
  13720. refreshUniformsStandard(uniforms, material);
  13721. }
  13722. } else if (material.isMeshMatcapMaterial) {
  13723. refreshUniformsCommon(uniforms, material);
  13724. refreshUniformsMatcap(uniforms, material);
  13725. } else if (material.isMeshDepthMaterial) {
  13726. refreshUniformsCommon(uniforms, material);
  13727. refreshUniformsDepth(uniforms, material);
  13728. } else if (material.isMeshDistanceMaterial) {
  13729. refreshUniformsCommon(uniforms, material);
  13730. refreshUniformsDistance(uniforms, material);
  13731. } else if (material.isMeshNormalMaterial) {
  13732. refreshUniformsCommon(uniforms, material);
  13733. refreshUniformsNormal(uniforms, material);
  13734. } else if (material.isLineBasicMaterial) {
  13735. refreshUniformsLine(uniforms, material);
  13736. if (material.isLineDashedMaterial) {
  13737. refreshUniformsDash(uniforms, material);
  13738. }
  13739. } else if (material.isPointsMaterial) {
  13740. refreshUniformsPoints(uniforms, material, pixelRatio, height);
  13741. } else if (material.isSpriteMaterial) {
  13742. refreshUniformsSprites(uniforms, material);
  13743. } else if (material.isShadowMaterial) {
  13744. uniforms.color.value.copy(material.color);
  13745. uniforms.opacity.value = material.opacity;
  13746. } else if (material.isShaderMaterial) {
  13747. material.uniformsNeedUpdate = false; // #15581
  13748. }
  13749. }
  13750. function refreshUniformsCommon(uniforms, material) {
  13751. uniforms.opacity.value = material.opacity;
  13752. if (material.color) {
  13753. uniforms.diffuse.value.copy(material.color);
  13754. }
  13755. if (material.emissive) {
  13756. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  13757. }
  13758. if (material.map) {
  13759. uniforms.map.value = material.map;
  13760. }
  13761. if (material.alphaMap) {
  13762. uniforms.alphaMap.value = material.alphaMap;
  13763. }
  13764. if (material.specularMap) {
  13765. uniforms.specularMap.value = material.specularMap;
  13766. }
  13767. const envMap = properties.get(material).envMap;
  13768. if (envMap) {
  13769. uniforms.envMap.value = envMap;
  13770. uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap._needsFlipEnvMap ? -1 : 1;
  13771. uniforms.reflectivity.value = material.reflectivity;
  13772. uniforms.refractionRatio.value = material.refractionRatio;
  13773. const maxMipLevel = properties.get(envMap).__maxMipLevel;
  13774. if (maxMipLevel !== undefined) {
  13775. uniforms.maxMipLevel.value = maxMipLevel;
  13776. }
  13777. }
  13778. if (material.lightMap) {
  13779. uniforms.lightMap.value = material.lightMap;
  13780. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  13781. }
  13782. if (material.aoMap) {
  13783. uniforms.aoMap.value = material.aoMap;
  13784. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  13785. } // uv repeat and offset setting priorities
  13786. // 1. color map
  13787. // 2. specular map
  13788. // 3. displacementMap map
  13789. // 4. normal map
  13790. // 5. bump map
  13791. // 6. roughnessMap map
  13792. // 7. metalnessMap map
  13793. // 8. alphaMap map
  13794. // 9. emissiveMap map
  13795. // 10. clearcoat map
  13796. // 11. clearcoat normal map
  13797. // 12. clearcoat roughnessMap map
  13798. let uvScaleMap;
  13799. if (material.map) {
  13800. uvScaleMap = material.map;
  13801. } else if (material.specularMap) {
  13802. uvScaleMap = material.specularMap;
  13803. } else if (material.displacementMap) {
  13804. uvScaleMap = material.displacementMap;
  13805. } else if (material.normalMap) {
  13806. uvScaleMap = material.normalMap;
  13807. } else if (material.bumpMap) {
  13808. uvScaleMap = material.bumpMap;
  13809. } else if (material.roughnessMap) {
  13810. uvScaleMap = material.roughnessMap;
  13811. } else if (material.metalnessMap) {
  13812. uvScaleMap = material.metalnessMap;
  13813. } else if (material.alphaMap) {
  13814. uvScaleMap = material.alphaMap;
  13815. } else if (material.emissiveMap) {
  13816. uvScaleMap = material.emissiveMap;
  13817. } else if (material.clearcoatMap) {
  13818. uvScaleMap = material.clearcoatMap;
  13819. } else if (material.clearcoatNormalMap) {
  13820. uvScaleMap = material.clearcoatNormalMap;
  13821. } else if (material.clearcoatRoughnessMap) {
  13822. uvScaleMap = material.clearcoatRoughnessMap;
  13823. }
  13824. if (uvScaleMap !== undefined) {
  13825. // backwards compatibility
  13826. if (uvScaleMap.isWebGLRenderTarget) {
  13827. uvScaleMap = uvScaleMap.texture;
  13828. }
  13829. if (uvScaleMap.matrixAutoUpdate === true) {
  13830. uvScaleMap.updateMatrix();
  13831. }
  13832. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  13833. } // uv repeat and offset setting priorities for uv2
  13834. // 1. ao map
  13835. // 2. light map
  13836. let uv2ScaleMap;
  13837. if (material.aoMap) {
  13838. uv2ScaleMap = material.aoMap;
  13839. } else if (material.lightMap) {
  13840. uv2ScaleMap = material.lightMap;
  13841. }
  13842. if (uv2ScaleMap !== undefined) {
  13843. // backwards compatibility
  13844. if (uv2ScaleMap.isWebGLRenderTarget) {
  13845. uv2ScaleMap = uv2ScaleMap.texture;
  13846. }
  13847. if (uv2ScaleMap.matrixAutoUpdate === true) {
  13848. uv2ScaleMap.updateMatrix();
  13849. }
  13850. uniforms.uv2Transform.value.copy(uv2ScaleMap.matrix);
  13851. }
  13852. }
  13853. function refreshUniformsLine(uniforms, material) {
  13854. uniforms.diffuse.value.copy(material.color);
  13855. uniforms.opacity.value = material.opacity;
  13856. }
  13857. function refreshUniformsDash(uniforms, material) {
  13858. uniforms.dashSize.value = material.dashSize;
  13859. uniforms.totalSize.value = material.dashSize + material.gapSize;
  13860. uniforms.scale.value = material.scale;
  13861. }
  13862. function refreshUniformsPoints(uniforms, material, pixelRatio, height) {
  13863. uniforms.diffuse.value.copy(material.color);
  13864. uniforms.opacity.value = material.opacity;
  13865. uniforms.size.value = material.size * pixelRatio;
  13866. uniforms.scale.value = height * 0.5;
  13867. if (material.map) {
  13868. uniforms.map.value = material.map;
  13869. }
  13870. if (material.alphaMap) {
  13871. uniforms.alphaMap.value = material.alphaMap;
  13872. } // uv repeat and offset setting priorities
  13873. // 1. color map
  13874. // 2. alpha map
  13875. let uvScaleMap;
  13876. if (material.map) {
  13877. uvScaleMap = material.map;
  13878. } else if (material.alphaMap) {
  13879. uvScaleMap = material.alphaMap;
  13880. }
  13881. if (uvScaleMap !== undefined) {
  13882. if (uvScaleMap.matrixAutoUpdate === true) {
  13883. uvScaleMap.updateMatrix();
  13884. }
  13885. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  13886. }
  13887. }
  13888. function refreshUniformsSprites(uniforms, material) {
  13889. uniforms.diffuse.value.copy(material.color);
  13890. uniforms.opacity.value = material.opacity;
  13891. uniforms.rotation.value = material.rotation;
  13892. if (material.map) {
  13893. uniforms.map.value = material.map;
  13894. }
  13895. if (material.alphaMap) {
  13896. uniforms.alphaMap.value = material.alphaMap;
  13897. } // uv repeat and offset setting priorities
  13898. // 1. color map
  13899. // 2. alpha map
  13900. let uvScaleMap;
  13901. if (material.map) {
  13902. uvScaleMap = material.map;
  13903. } else if (material.alphaMap) {
  13904. uvScaleMap = material.alphaMap;
  13905. }
  13906. if (uvScaleMap !== undefined) {
  13907. if (uvScaleMap.matrixAutoUpdate === true) {
  13908. uvScaleMap.updateMatrix();
  13909. }
  13910. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  13911. }
  13912. }
  13913. function refreshUniformsLambert(uniforms, material) {
  13914. if (material.emissiveMap) {
  13915. uniforms.emissiveMap.value = material.emissiveMap;
  13916. }
  13917. }
  13918. function refreshUniformsPhong(uniforms, material) {
  13919. uniforms.specular.value.copy(material.specular);
  13920. uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
  13921. if (material.emissiveMap) {
  13922. uniforms.emissiveMap.value = material.emissiveMap;
  13923. }
  13924. if (material.bumpMap) {
  13925. uniforms.bumpMap.value = material.bumpMap;
  13926. uniforms.bumpScale.value = material.bumpScale;
  13927. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  13928. }
  13929. if (material.normalMap) {
  13930. uniforms.normalMap.value = material.normalMap;
  13931. uniforms.normalScale.value.copy(material.normalScale);
  13932. if (material.side === BackSide) uniforms.normalScale.value.negate();
  13933. }
  13934. if (material.displacementMap) {
  13935. uniforms.displacementMap.value = material.displacementMap;
  13936. uniforms.displacementScale.value = material.displacementScale;
  13937. uniforms.displacementBias.value = material.displacementBias;
  13938. }
  13939. }
  13940. function refreshUniformsToon(uniforms, material) {
  13941. if (material.gradientMap) {
  13942. uniforms.gradientMap.value = material.gradientMap;
  13943. }
  13944. if (material.emissiveMap) {
  13945. uniforms.emissiveMap.value = material.emissiveMap;
  13946. }
  13947. if (material.bumpMap) {
  13948. uniforms.bumpMap.value = material.bumpMap;
  13949. uniforms.bumpScale.value = material.bumpScale;
  13950. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  13951. }
  13952. if (material.normalMap) {
  13953. uniforms.normalMap.value = material.normalMap;
  13954. uniforms.normalScale.value.copy(material.normalScale);
  13955. if (material.side === BackSide) uniforms.normalScale.value.negate();
  13956. }
  13957. if (material.displacementMap) {
  13958. uniforms.displacementMap.value = material.displacementMap;
  13959. uniforms.displacementScale.value = material.displacementScale;
  13960. uniforms.displacementBias.value = material.displacementBias;
  13961. }
  13962. }
  13963. function refreshUniformsStandard(uniforms, material) {
  13964. uniforms.roughness.value = material.roughness;
  13965. uniforms.metalness.value = material.metalness;
  13966. if (material.roughnessMap) {
  13967. uniforms.roughnessMap.value = material.roughnessMap;
  13968. }
  13969. if (material.metalnessMap) {
  13970. uniforms.metalnessMap.value = material.metalnessMap;
  13971. }
  13972. if (material.emissiveMap) {
  13973. uniforms.emissiveMap.value = material.emissiveMap;
  13974. }
  13975. if (material.bumpMap) {
  13976. uniforms.bumpMap.value = material.bumpMap;
  13977. uniforms.bumpScale.value = material.bumpScale;
  13978. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  13979. }
  13980. if (material.normalMap) {
  13981. uniforms.normalMap.value = material.normalMap;
  13982. uniforms.normalScale.value.copy(material.normalScale);
  13983. if (material.side === BackSide) uniforms.normalScale.value.negate();
  13984. }
  13985. if (material.displacementMap) {
  13986. uniforms.displacementMap.value = material.displacementMap;
  13987. uniforms.displacementScale.value = material.displacementScale;
  13988. uniforms.displacementBias.value = material.displacementBias;
  13989. }
  13990. const envMap = properties.get(material).envMap;
  13991. if (envMap) {
  13992. //uniforms.envMap.value = material.envMap; // part of uniforms common
  13993. uniforms.envMapIntensity.value = material.envMapIntensity;
  13994. }
  13995. }
  13996. function refreshUniformsPhysical(uniforms, material) {
  13997. refreshUniformsStandard(uniforms, material);
  13998. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  13999. uniforms.clearcoat.value = material.clearcoat;
  14000. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  14001. if (material.sheen) uniforms.sheen.value.copy(material.sheen);
  14002. if (material.clearcoatMap) {
  14003. uniforms.clearcoatMap.value = material.clearcoatMap;
  14004. }
  14005. if (material.clearcoatRoughnessMap) {
  14006. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  14007. }
  14008. if (material.clearcoatNormalMap) {
  14009. uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
  14010. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  14011. if (material.side === BackSide) {
  14012. uniforms.clearcoatNormalScale.value.negate();
  14013. }
  14014. }
  14015. uniforms.transmission.value = material.transmission;
  14016. if (material.transmissionMap) {
  14017. uniforms.transmissionMap.value = material.transmissionMap;
  14018. }
  14019. }
  14020. function refreshUniformsMatcap(uniforms, material) {
  14021. if (material.matcap) {
  14022. uniforms.matcap.value = material.matcap;
  14023. }
  14024. if (material.bumpMap) {
  14025. uniforms.bumpMap.value = material.bumpMap;
  14026. uniforms.bumpScale.value = material.bumpScale;
  14027. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14028. }
  14029. if (material.normalMap) {
  14030. uniforms.normalMap.value = material.normalMap;
  14031. uniforms.normalScale.value.copy(material.normalScale);
  14032. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14033. }
  14034. if (material.displacementMap) {
  14035. uniforms.displacementMap.value = material.displacementMap;
  14036. uniforms.displacementScale.value = material.displacementScale;
  14037. uniforms.displacementBias.value = material.displacementBias;
  14038. }
  14039. }
  14040. function refreshUniformsDepth(uniforms, material) {
  14041. if (material.displacementMap) {
  14042. uniforms.displacementMap.value = material.displacementMap;
  14043. uniforms.displacementScale.value = material.displacementScale;
  14044. uniforms.displacementBias.value = material.displacementBias;
  14045. }
  14046. }
  14047. function refreshUniformsDistance(uniforms, material) {
  14048. if (material.displacementMap) {
  14049. uniforms.displacementMap.value = material.displacementMap;
  14050. uniforms.displacementScale.value = material.displacementScale;
  14051. uniforms.displacementBias.value = material.displacementBias;
  14052. }
  14053. uniforms.referencePosition.value.copy(material.referencePosition);
  14054. uniforms.nearDistance.value = material.nearDistance;
  14055. uniforms.farDistance.value = material.farDistance;
  14056. }
  14057. function refreshUniformsNormal(uniforms, material) {
  14058. if (material.bumpMap) {
  14059. uniforms.bumpMap.value = material.bumpMap;
  14060. uniforms.bumpScale.value = material.bumpScale;
  14061. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14062. }
  14063. if (material.normalMap) {
  14064. uniforms.normalMap.value = material.normalMap;
  14065. uniforms.normalScale.value.copy(material.normalScale);
  14066. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14067. }
  14068. if (material.displacementMap) {
  14069. uniforms.displacementMap.value = material.displacementMap;
  14070. uniforms.displacementScale.value = material.displacementScale;
  14071. uniforms.displacementBias.value = material.displacementBias;
  14072. }
  14073. }
  14074. return {
  14075. refreshFogUniforms: refreshFogUniforms,
  14076. refreshMaterialUniforms: refreshMaterialUniforms
  14077. };
  14078. }
  14079. function createCanvasElement() {
  14080. const canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  14081. canvas.style.display = 'block';
  14082. return canvas;
  14083. }
  14084. function WebGLRenderer(parameters) {
  14085. parameters = parameters || {};
  14086. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  14087. _context = parameters.context !== undefined ? parameters.context : null,
  14088. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  14089. _depth = parameters.depth !== undefined ? parameters.depth : true,
  14090. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  14091. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  14092. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  14093. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  14094. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  14095. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  14096. let currentRenderList = null;
  14097. let currentRenderState = null; // render() can be called from within a callback triggered by another render.
  14098. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  14099. const renderListStack = [];
  14100. const renderStateStack = []; // public properties
  14101. this.domElement = _canvas; // Debug configuration container
  14102. this.debug = {
  14103. /**
  14104. * Enables error checking and reporting when shader programs are being compiled
  14105. * @type {boolean}
  14106. */
  14107. checkShaderErrors: true
  14108. }; // clearing
  14109. this.autoClear = true;
  14110. this.autoClearColor = true;
  14111. this.autoClearDepth = true;
  14112. this.autoClearStencil = true; // scene graph
  14113. this.sortObjects = true; // user-defined clipping
  14114. this.clippingPlanes = [];
  14115. this.localClippingEnabled = false; // physically based shading
  14116. this.gammaFactor = 2.0; // for backwards compatibility
  14117. this.outputEncoding = LinearEncoding; // physical lights
  14118. this.physicallyCorrectLights = false; // tone mapping
  14119. this.toneMapping = NoToneMapping;
  14120. this.toneMappingExposure = 1.0; // internal properties
  14121. const _this = this;
  14122. let _isContextLost = false; // internal state cache
  14123. let _currentActiveCubeFace = 0;
  14124. let _currentActiveMipmapLevel = 0;
  14125. let _currentRenderTarget = null;
  14126. let _currentMaterialId = -1;
  14127. let _currentCamera = null;
  14128. const _currentViewport = new Vector4();
  14129. const _currentScissor = new Vector4();
  14130. let _currentScissorTest = null; //
  14131. let _width = _canvas.width;
  14132. let _height = _canvas.height;
  14133. let _pixelRatio = 1;
  14134. let _opaqueSort = null;
  14135. let _transparentSort = null;
  14136. const _viewport = new Vector4(0, 0, _width, _height);
  14137. const _scissor = new Vector4(0, 0, _width, _height);
  14138. let _scissorTest = false; //
  14139. const _currentDrawBuffers = []; // frustum
  14140. const _frustum = new Frustum(); // clipping
  14141. let _clippingEnabled = false;
  14142. let _localClippingEnabled = false; // camera matrices cache
  14143. const _projScreenMatrix = new Matrix4();
  14144. const _vector3 = new Vector3();
  14145. const _emptyScene = {
  14146. background: null,
  14147. fog: null,
  14148. environment: null,
  14149. overrideMaterial: null,
  14150. isScene: true
  14151. };
  14152. function getTargetPixelRatio() {
  14153. return _currentRenderTarget === null ? _pixelRatio : 1;
  14154. } // initialize
  14155. let _gl = _context;
  14156. function getContext(contextNames, contextAttributes) {
  14157. for (let i = 0; i < contextNames.length; i++) {
  14158. const contextName = contextNames[i];
  14159. const context = _canvas.getContext(contextName, contextAttributes);
  14160. if (context !== null) return context;
  14161. }
  14162. return null;
  14163. }
  14164. try {
  14165. const contextAttributes = {
  14166. alpha: _alpha,
  14167. depth: _depth,
  14168. stencil: _stencil,
  14169. antialias: _antialias,
  14170. premultipliedAlpha: _premultipliedAlpha,
  14171. preserveDrawingBuffer: _preserveDrawingBuffer,
  14172. powerPreference: _powerPreference,
  14173. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  14174. }; // event listeners must be registered before WebGL context is created, see #12753
  14175. _canvas.addEventListener('webglcontextlost', onContextLost, false);
  14176. _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
  14177. if (_gl === null) {
  14178. const contextNames = ['webgl2', 'webgl', 'experimental-webgl'];
  14179. if (_this.isWebGL1Renderer === true) {
  14180. contextNames.shift();
  14181. }
  14182. _gl = getContext(contextNames, contextAttributes);
  14183. if (_gl === null) {
  14184. if (getContext(contextNames)) {
  14185. throw new Error('Error creating WebGL context with your selected attributes.');
  14186. } else {
  14187. throw new Error('Error creating WebGL context.');
  14188. }
  14189. }
  14190. } // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  14191. if (_gl.getShaderPrecisionFormat === undefined) {
  14192. _gl.getShaderPrecisionFormat = function () {
  14193. return {
  14194. 'rangeMin': 1,
  14195. 'rangeMax': 1,
  14196. 'precision': 1
  14197. };
  14198. };
  14199. }
  14200. } catch (error) {
  14201. console.error('THREE.WebGLRenderer: ' + error.message);
  14202. throw error;
  14203. }
  14204. let extensions, capabilities, state, info;
  14205. let properties, textures, cubemaps, attributes, geometries, objects;
  14206. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  14207. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  14208. let utils, bindingStates;
  14209. function initGLContext() {
  14210. extensions = new WebGLExtensions(_gl);
  14211. capabilities = new WebGLCapabilities(_gl, extensions, parameters);
  14212. extensions.init(capabilities);
  14213. utils = new WebGLUtils(_gl, extensions, capabilities);
  14214. state = new WebGLState(_gl, extensions, capabilities);
  14215. _currentDrawBuffers[0] = _gl.BACK;
  14216. info = new WebGLInfo(_gl);
  14217. properties = new WebGLProperties();
  14218. textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
  14219. cubemaps = new WebGLCubeMaps(_this);
  14220. attributes = new WebGLAttributes(_gl, capabilities);
  14221. bindingStates = new WebGLBindingStates(_gl, extensions, attributes, capabilities);
  14222. geometries = new WebGLGeometries(_gl, attributes, info, bindingStates);
  14223. objects = new WebGLObjects(_gl, geometries, attributes, info);
  14224. morphtargets = new WebGLMorphtargets(_gl);
  14225. clipping = new WebGLClipping(properties);
  14226. programCache = new WebGLPrograms(_this, cubemaps, extensions, capabilities, bindingStates, clipping);
  14227. materials = new WebGLMaterials(properties);
  14228. renderLists = new WebGLRenderLists(properties);
  14229. renderStates = new WebGLRenderStates(extensions, capabilities);
  14230. background = new WebGLBackground(_this, cubemaps, state, objects, _premultipliedAlpha);
  14231. shadowMap = new WebGLShadowMap(_this, objects, capabilities);
  14232. bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
  14233. indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
  14234. info.programs = programCache.programs;
  14235. _this.capabilities = capabilities;
  14236. _this.extensions = extensions;
  14237. _this.properties = properties;
  14238. _this.renderLists = renderLists;
  14239. _this.shadowMap = shadowMap;
  14240. _this.state = state;
  14241. _this.info = info;
  14242. }
  14243. initGLContext(); // xr
  14244. const xr = new WebXRManager(_this, _gl);
  14245. this.xr = xr; // API
  14246. this.getContext = function () {
  14247. return _gl;
  14248. };
  14249. this.getContextAttributes = function () {
  14250. return _gl.getContextAttributes();
  14251. };
  14252. this.forceContextLoss = function () {
  14253. const extension = extensions.get('WEBGL_lose_context');
  14254. if (extension) extension.loseContext();
  14255. };
  14256. this.forceContextRestore = function () {
  14257. const extension = extensions.get('WEBGL_lose_context');
  14258. if (extension) extension.restoreContext();
  14259. };
  14260. this.getPixelRatio = function () {
  14261. return _pixelRatio;
  14262. };
  14263. this.setPixelRatio = function (value) {
  14264. if (value === undefined) return;
  14265. _pixelRatio = value;
  14266. this.setSize(_width, _height, false);
  14267. };
  14268. this.getSize = function (target) {
  14269. if (target === undefined) {
  14270. console.warn('WebGLRenderer: .getsize() now requires a Vector2 as an argument');
  14271. target = new Vector2();
  14272. }
  14273. return target.set(_width, _height);
  14274. };
  14275. this.setSize = function (width, height, updateStyle) {
  14276. if (xr.isPresenting) {
  14277. console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');
  14278. return;
  14279. }
  14280. _width = width;
  14281. _height = height;
  14282. _canvas.width = Math.floor(width * _pixelRatio);
  14283. _canvas.height = Math.floor(height * _pixelRatio);
  14284. if (updateStyle !== false) {
  14285. _canvas.style.width = width + 'px';
  14286. _canvas.style.height = height + 'px';
  14287. }
  14288. this.setViewport(0, 0, width, height);
  14289. };
  14290. this.getDrawingBufferSize = function (target) {
  14291. if (target === undefined) {
  14292. console.warn('WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument');
  14293. target = new Vector2();
  14294. }
  14295. return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();
  14296. };
  14297. this.setDrawingBufferSize = function (width, height, pixelRatio) {
  14298. _width = width;
  14299. _height = height;
  14300. _pixelRatio = pixelRatio;
  14301. _canvas.width = Math.floor(width * pixelRatio);
  14302. _canvas.height = Math.floor(height * pixelRatio);
  14303. this.setViewport(0, 0, width, height);
  14304. };
  14305. this.getCurrentViewport = function (target) {
  14306. if (target === undefined) {
  14307. console.warn('WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument');
  14308. target = new Vector4();
  14309. }
  14310. return target.copy(_currentViewport);
  14311. };
  14312. this.getViewport = function (target) {
  14313. return target.copy(_viewport);
  14314. };
  14315. this.setViewport = function (x, y, width, height) {
  14316. if (x.isVector4) {
  14317. _viewport.set(x.x, x.y, x.z, x.w);
  14318. } else {
  14319. _viewport.set(x, y, width, height);
  14320. }
  14321. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  14322. };
  14323. this.getScissor = function (target) {
  14324. return target.copy(_scissor);
  14325. };
  14326. this.setScissor = function (x, y, width, height) {
  14327. if (x.isVector4) {
  14328. _scissor.set(x.x, x.y, x.z, x.w);
  14329. } else {
  14330. _scissor.set(x, y, width, height);
  14331. }
  14332. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  14333. };
  14334. this.getScissorTest = function () {
  14335. return _scissorTest;
  14336. };
  14337. this.setScissorTest = function (boolean) {
  14338. state.setScissorTest(_scissorTest = boolean);
  14339. };
  14340. this.setOpaqueSort = function (method) {
  14341. _opaqueSort = method;
  14342. };
  14343. this.setTransparentSort = function (method) {
  14344. _transparentSort = method;
  14345. }; // Clearing
  14346. this.getClearColor = function (target) {
  14347. if (target === undefined) {
  14348. console.warn('WebGLRenderer: .getClearColor() now requires a Color as an argument');
  14349. target = new Color();
  14350. }
  14351. return target.copy(background.getClearColor());
  14352. };
  14353. this.setClearColor = function () {
  14354. background.setClearColor.apply(background, arguments);
  14355. };
  14356. this.getClearAlpha = function () {
  14357. return background.getClearAlpha();
  14358. };
  14359. this.setClearAlpha = function () {
  14360. background.setClearAlpha.apply(background, arguments);
  14361. };
  14362. this.clear = function (color, depth, stencil) {
  14363. let bits = 0;
  14364. if (color === undefined || color) bits |= _gl.COLOR_BUFFER_BIT;
  14365. if (depth === undefined || depth) bits |= _gl.DEPTH_BUFFER_BIT;
  14366. if (stencil === undefined || stencil) bits |= _gl.STENCIL_BUFFER_BIT;
  14367. _gl.clear(bits);
  14368. };
  14369. this.clearColor = function () {
  14370. this.clear(true, false, false);
  14371. };
  14372. this.clearDepth = function () {
  14373. this.clear(false, true, false);
  14374. };
  14375. this.clearStencil = function () {
  14376. this.clear(false, false, true);
  14377. }; //
  14378. this.dispose = function () {
  14379. _canvas.removeEventListener('webglcontextlost', onContextLost, false);
  14380. _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);
  14381. renderLists.dispose();
  14382. renderStates.dispose();
  14383. properties.dispose();
  14384. cubemaps.dispose();
  14385. objects.dispose();
  14386. bindingStates.dispose();
  14387. xr.dispose();
  14388. xr.removeEventListener('sessionstart', onXRSessionStart);
  14389. xr.removeEventListener('sessionend', onXRSessionEnd);
  14390. animation.stop();
  14391. }; // Events
  14392. function onContextLost(event) {
  14393. event.preventDefault();
  14394. console.log('THREE.WebGLRenderer: Context Lost.');
  14395. _isContextLost = true;
  14396. }
  14397. function onContextRestore()
  14398. /* event */
  14399. {
  14400. console.log('THREE.WebGLRenderer: Context Restored.');
  14401. _isContextLost = false;
  14402. const infoAutoReset = info.autoReset;
  14403. const shadowMapEnabled = shadowMap.enabled;
  14404. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  14405. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  14406. const shadowMapType = shadowMap.type;
  14407. initGLContext();
  14408. info.autoReset = infoAutoReset;
  14409. shadowMap.enabled = shadowMapEnabled;
  14410. shadowMap.autoUpdate = shadowMapAutoUpdate;
  14411. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  14412. shadowMap.type = shadowMapType;
  14413. }
  14414. function onMaterialDispose(event) {
  14415. const material = event.target;
  14416. material.removeEventListener('dispose', onMaterialDispose);
  14417. deallocateMaterial(material);
  14418. } // Buffer deallocation
  14419. function deallocateMaterial(material) {
  14420. releaseMaterialProgramReferences(material);
  14421. properties.remove(material);
  14422. }
  14423. function releaseMaterialProgramReferences(material) {
  14424. const programs = properties.get(material).programs;
  14425. if (programs !== undefined) {
  14426. programs.forEach(function (program) {
  14427. programCache.releaseProgram(program);
  14428. });
  14429. }
  14430. } // Buffer rendering
  14431. function renderObjectImmediate(object, program) {
  14432. object.render(function (object) {
  14433. _this.renderBufferImmediate(object, program);
  14434. });
  14435. }
  14436. this.renderBufferImmediate = function (object, program) {
  14437. bindingStates.initAttributes();
  14438. const buffers = properties.get(object);
  14439. if (object.hasPositions && !buffers.position) buffers.position = _gl.createBuffer();
  14440. if (object.hasNormals && !buffers.normal) buffers.normal = _gl.createBuffer();
  14441. if (object.hasUvs && !buffers.uv) buffers.uv = _gl.createBuffer();
  14442. if (object.hasColors && !buffers.color) buffers.color = _gl.createBuffer();
  14443. const programAttributes = program.getAttributes();
  14444. if (object.hasPositions) {
  14445. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.position);
  14446. _gl.bufferData(_gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW);
  14447. bindingStates.enableAttribute(programAttributes.position);
  14448. _gl.vertexAttribPointer(programAttributes.position, 3, _gl.FLOAT, false, 0, 0);
  14449. }
  14450. if (object.hasNormals) {
  14451. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.normal);
  14452. _gl.bufferData(_gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW);
  14453. bindingStates.enableAttribute(programAttributes.normal);
  14454. _gl.vertexAttribPointer(programAttributes.normal, 3, _gl.FLOAT, false, 0, 0);
  14455. }
  14456. if (object.hasUvs) {
  14457. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.uv);
  14458. _gl.bufferData(_gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW);
  14459. bindingStates.enableAttribute(programAttributes.uv);
  14460. _gl.vertexAttribPointer(programAttributes.uv, 2, _gl.FLOAT, false, 0, 0);
  14461. }
  14462. if (object.hasColors) {
  14463. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.color);
  14464. _gl.bufferData(_gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW);
  14465. bindingStates.enableAttribute(programAttributes.color);
  14466. _gl.vertexAttribPointer(programAttributes.color, 3, _gl.FLOAT, false, 0, 0);
  14467. }
  14468. bindingStates.disableUnusedAttributes();
  14469. _gl.drawArrays(_gl.TRIANGLES, 0, object.count);
  14470. object.count = 0;
  14471. };
  14472. this.renderBufferDirect = function (camera, scene, geometry, material, object, group) {
  14473. if (scene === null) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  14474. const frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
  14475. const program = setProgram(camera, scene, material, object);
  14476. state.setMaterial(material, frontFaceCW); //
  14477. let index = geometry.index;
  14478. const position = geometry.attributes.position; //
  14479. if (index === null) {
  14480. if (position === undefined || position.count === 0) return;
  14481. } else if (index.count === 0) {
  14482. return;
  14483. } //
  14484. let rangeFactor = 1;
  14485. if (material.wireframe === true) {
  14486. index = geometries.getWireframeAttribute(geometry);
  14487. rangeFactor = 2;
  14488. }
  14489. if (material.morphTargets || material.morphNormals) {
  14490. morphtargets.update(object, geometry, material, program);
  14491. }
  14492. bindingStates.setup(object, material, program, geometry, index);
  14493. let attribute;
  14494. let renderer = bufferRenderer;
  14495. if (index !== null) {
  14496. attribute = attributes.get(index);
  14497. renderer = indexedBufferRenderer;
  14498. renderer.setIndex(attribute);
  14499. } //
  14500. const dataCount = index !== null ? index.count : position.count;
  14501. const rangeStart = geometry.drawRange.start * rangeFactor;
  14502. const rangeCount = geometry.drawRange.count * rangeFactor;
  14503. const groupStart = group !== null ? group.start * rangeFactor : 0;
  14504. const groupCount = group !== null ? group.count * rangeFactor : Infinity;
  14505. const drawStart = Math.max(rangeStart, groupStart);
  14506. const drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1;
  14507. const drawCount = Math.max(0, drawEnd - drawStart + 1);
  14508. if (drawCount === 0) return; //
  14509. if (object.isMesh) {
  14510. if (material.wireframe === true) {
  14511. state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());
  14512. renderer.setMode(_gl.LINES);
  14513. } else {
  14514. renderer.setMode(_gl.TRIANGLES);
  14515. }
  14516. } else if (object.isLine) {
  14517. let lineWidth = material.linewidth;
  14518. if (lineWidth === undefined) lineWidth = 1; // Not using Line*Material
  14519. state.setLineWidth(lineWidth * getTargetPixelRatio());
  14520. if (object.isLineSegments) {
  14521. renderer.setMode(_gl.LINES);
  14522. } else if (object.isLineLoop) {
  14523. renderer.setMode(_gl.LINE_LOOP);
  14524. } else {
  14525. renderer.setMode(_gl.LINE_STRIP);
  14526. }
  14527. } else if (object.isPoints) {
  14528. renderer.setMode(_gl.POINTS);
  14529. } else if (object.isSprite) {
  14530. renderer.setMode(_gl.TRIANGLES);
  14531. }
  14532. if (object.isInstancedMesh) {
  14533. renderer.renderInstances(drawStart, drawCount, object.count);
  14534. } else if (geometry.isInstancedBufferGeometry) {
  14535. const instanceCount = Math.min(geometry.instanceCount, geometry._maxInstanceCount);
  14536. renderer.renderInstances(drawStart, drawCount, instanceCount);
  14537. } else {
  14538. renderer.render(drawStart, drawCount);
  14539. }
  14540. }; // Compile
  14541. this.compile = function (scene, camera) {
  14542. currentRenderState = renderStates.get(scene);
  14543. currentRenderState.init();
  14544. scene.traverseVisible(function (object) {
  14545. if (object.isLight && object.layers.test(camera.layers)) {
  14546. currentRenderState.pushLight(object);
  14547. if (object.castShadow) {
  14548. currentRenderState.pushShadow(object);
  14549. }
  14550. }
  14551. });
  14552. currentRenderState.setupLights();
  14553. scene.traverse(function (object) {
  14554. const material = object.material;
  14555. if (material) {
  14556. if (Array.isArray(material)) {
  14557. for (let i = 0; i < material.length; i++) {
  14558. const material2 = material[i];
  14559. getProgram(material2, scene, object);
  14560. }
  14561. } else {
  14562. getProgram(material, scene, object);
  14563. }
  14564. }
  14565. });
  14566. }; // Animation Loop
  14567. let onAnimationFrameCallback = null;
  14568. function onAnimationFrame(time) {
  14569. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  14570. }
  14571. function onXRSessionStart() {
  14572. animation.stop();
  14573. }
  14574. function onXRSessionEnd() {
  14575. animation.start();
  14576. }
  14577. const animation = new WebGLAnimation();
  14578. animation.setAnimationLoop(onAnimationFrame);
  14579. if (typeof window !== 'undefined') animation.setContext(window);
  14580. this.setAnimationLoop = function (callback) {
  14581. onAnimationFrameCallback = callback;
  14582. xr.setAnimationLoop(callback);
  14583. callback === null ? animation.stop() : animation.start();
  14584. };
  14585. xr.addEventListener('sessionstart', onXRSessionStart);
  14586. xr.addEventListener('sessionend', onXRSessionEnd); // Rendering
  14587. this.render = function (scene, camera) {
  14588. if (camera !== undefined && camera.isCamera !== true) {
  14589. console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');
  14590. return;
  14591. }
  14592. if (_isContextLost === true) return; // update scene graph
  14593. if (scene.autoUpdate === true) scene.updateMatrixWorld(); // update camera matrices and frustum
  14594. if (camera.parent === null) camera.updateMatrixWorld();
  14595. if (xr.enabled === true && xr.isPresenting === true) {
  14596. camera = xr.getCamera(camera);
  14597. } //
  14598. if (scene.isScene === true) scene.onBeforeRender(_this, scene, camera, _currentRenderTarget);
  14599. currentRenderState = renderStates.get(scene, renderStateStack.length);
  14600. currentRenderState.init();
  14601. renderStateStack.push(currentRenderState);
  14602. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  14603. _frustum.setFromProjectionMatrix(_projScreenMatrix);
  14604. _localClippingEnabled = this.localClippingEnabled;
  14605. _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled, camera);
  14606. currentRenderList = renderLists.get(scene, renderListStack.length);
  14607. currentRenderList.init();
  14608. renderListStack.push(currentRenderList);
  14609. projectObject(scene, camera, 0, _this.sortObjects);
  14610. currentRenderList.finish();
  14611. if (_this.sortObjects === true) {
  14612. currentRenderList.sort(_opaqueSort, _transparentSort);
  14613. } //
  14614. if (_clippingEnabled === true) clipping.beginShadows();
  14615. const shadowsArray = currentRenderState.state.shadowsArray;
  14616. shadowMap.render(shadowsArray, scene, camera);
  14617. currentRenderState.setupLights();
  14618. currentRenderState.setupLightsView(camera);
  14619. if (_clippingEnabled === true) clipping.endShadows(); //
  14620. if (this.info.autoReset === true) this.info.reset(); //
  14621. background.render(currentRenderList, scene); // render scene
  14622. const opaqueObjects = currentRenderList.opaque;
  14623. const transparentObjects = currentRenderList.transparent;
  14624. if (opaqueObjects.length > 0) renderObjects(opaqueObjects, scene, camera);
  14625. if (transparentObjects.length > 0) renderObjects(transparentObjects, scene, camera); //
  14626. if (_currentRenderTarget !== null) {
  14627. // Generate mipmap if we're using any kind of mipmap filtering
  14628. textures.updateRenderTargetMipmap(_currentRenderTarget); // resolve multisample renderbuffers to a single-sample texture if necessary
  14629. textures.updateMultisampleRenderTarget(_currentRenderTarget);
  14630. } //
  14631. if (scene.isScene === true) scene.onAfterRender(_this, scene, camera); // Ensure depth buffer writing is enabled so it can be cleared on next render
  14632. state.buffers.depth.setTest(true);
  14633. state.buffers.depth.setMask(true);
  14634. state.buffers.color.setMask(true);
  14635. state.setPolygonOffset(false); // _gl.finish();
  14636. bindingStates.resetDefaultState();
  14637. _currentMaterialId = -1;
  14638. _currentCamera = null;
  14639. renderStateStack.pop();
  14640. if (renderStateStack.length > 0) {
  14641. currentRenderState = renderStateStack[renderStateStack.length - 1];
  14642. } else {
  14643. currentRenderState = null;
  14644. }
  14645. renderListStack.pop();
  14646. if (renderListStack.length > 0) {
  14647. currentRenderList = renderListStack[renderListStack.length - 1];
  14648. } else {
  14649. currentRenderList = null;
  14650. }
  14651. };
  14652. function projectObject(object, camera, groupOrder, sortObjects) {
  14653. if (object.visible === false) return;
  14654. const visible = object.layers.test(camera.layers);
  14655. if (visible) {
  14656. if (object.isGroup) {
  14657. groupOrder = object.renderOrder;
  14658. } else if (object.isLOD) {
  14659. if (object.autoUpdate === true) object.update(camera);
  14660. } else if (object.isLight) {
  14661. currentRenderState.pushLight(object);
  14662. if (object.castShadow) {
  14663. currentRenderState.pushShadow(object);
  14664. }
  14665. } else if (object.isSprite) {
  14666. if (!object.frustumCulled || _frustum.intersectsSprite(object)) {
  14667. if (sortObjects) {
  14668. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  14669. }
  14670. const geometry = objects.update(object);
  14671. const material = object.material;
  14672. if (material.visible) {
  14673. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  14674. }
  14675. }
  14676. } else if (object.isImmediateRenderObject) {
  14677. if (sortObjects) {
  14678. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  14679. }
  14680. currentRenderList.push(object, null, object.material, groupOrder, _vector3.z, null);
  14681. } else if (object.isMesh || object.isLine || object.isPoints) {
  14682. if (object.isSkinnedMesh) {
  14683. // update skeleton only once in a frame
  14684. if (object.skeleton.frame !== info.render.frame) {
  14685. object.skeleton.update();
  14686. object.skeleton.frame = info.render.frame;
  14687. }
  14688. }
  14689. if (!object.frustumCulled || _frustum.intersectsObject(object)) {
  14690. if (sortObjects) {
  14691. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  14692. }
  14693. const geometry = objects.update(object);
  14694. const material = object.material;
  14695. if (Array.isArray(material)) {
  14696. const groups = geometry.groups;
  14697. for (let i = 0, l = groups.length; i < l; i++) {
  14698. const group = groups[i];
  14699. const groupMaterial = material[group.materialIndex];
  14700. if (groupMaterial && groupMaterial.visible) {
  14701. currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector3.z, group);
  14702. }
  14703. }
  14704. } else if (material.visible) {
  14705. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  14706. }
  14707. }
  14708. }
  14709. }
  14710. const children = object.children;
  14711. for (let i = 0, l = children.length; i < l; i++) {
  14712. projectObject(children[i], camera, groupOrder, sortObjects);
  14713. }
  14714. }
  14715. function renderObjects(renderList, scene, camera) {
  14716. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  14717. for (let i = 0, l = renderList.length; i < l; i++) {
  14718. const renderItem = renderList[i];
  14719. const object = renderItem.object;
  14720. const geometry = renderItem.geometry;
  14721. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  14722. const group = renderItem.group;
  14723. if (camera.isArrayCamera) {
  14724. const cameras = camera.cameras;
  14725. for (let j = 0, jl = cameras.length; j < jl; j++) {
  14726. const camera2 = cameras[j];
  14727. if (object.layers.test(camera2.layers)) {
  14728. state.viewport(_currentViewport.copy(camera2.viewport));
  14729. currentRenderState.setupLightsView(camera2);
  14730. renderObject(object, scene, camera2, geometry, material, group);
  14731. }
  14732. }
  14733. } else {
  14734. renderObject(object, scene, camera, geometry, material, group);
  14735. }
  14736. }
  14737. }
  14738. function renderObject(object, scene, camera, geometry, material, group) {
  14739. object.onBeforeRender(_this, scene, camera, geometry, material, group);
  14740. object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
  14741. object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
  14742. if (object.isImmediateRenderObject) {
  14743. const program = setProgram(camera, scene, material, object);
  14744. state.setMaterial(material);
  14745. bindingStates.reset();
  14746. renderObjectImmediate(object, program);
  14747. } else {
  14748. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  14749. }
  14750. object.onAfterRender(_this, scene, camera, geometry, material, group);
  14751. }
  14752. function getProgram(material, scene, object) {
  14753. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  14754. const materialProperties = properties.get(material);
  14755. const lights = currentRenderState.state.lights;
  14756. const shadowsArray = currentRenderState.state.shadowsArray;
  14757. const lightsStateVersion = lights.state.version;
  14758. const parameters = programCache.getParameters(material, lights.state, shadowsArray, scene, object);
  14759. const programCacheKey = programCache.getProgramCacheKey(parameters);
  14760. 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
  14761. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  14762. materialProperties.fog = scene.fog;
  14763. materialProperties.envMap = cubemaps.get(material.envMap || materialProperties.environment);
  14764. if (programs === undefined) {
  14765. // new material
  14766. material.addEventListener('dispose', onMaterialDispose);
  14767. programs = new Map();
  14768. materialProperties.programs = programs;
  14769. }
  14770. let program = programs.get(programCacheKey);
  14771. if (program !== undefined) {
  14772. // early out if program and light state is identical
  14773. if (materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion) {
  14774. updateCommonMaterialProperties(material, parameters);
  14775. return program;
  14776. }
  14777. } else {
  14778. parameters.uniforms = programCache.getUniforms(material);
  14779. material.onBuild(parameters, _this);
  14780. material.onBeforeCompile(parameters, _this);
  14781. program = programCache.acquireProgram(parameters, programCacheKey);
  14782. programs.set(programCacheKey, program);
  14783. materialProperties.uniforms = parameters.uniforms;
  14784. }
  14785. const uniforms = materialProperties.uniforms;
  14786. if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
  14787. uniforms.clippingPlanes = clipping.uniform;
  14788. }
  14789. updateCommonMaterialProperties(material, parameters); // store the light setup it was created for
  14790. materialProperties.needsLights = materialNeedsLights(material);
  14791. materialProperties.lightsStateVersion = lightsStateVersion;
  14792. if (materialProperties.needsLights) {
  14793. // wire up the material to this renderer's lighting state
  14794. uniforms.ambientLightColor.value = lights.state.ambient;
  14795. uniforms.lightProbe.value = lights.state.probe;
  14796. uniforms.directionalLights.value = lights.state.directional;
  14797. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  14798. uniforms.spotLights.value = lights.state.spot;
  14799. uniforms.spotLightShadows.value = lights.state.spotShadow;
  14800. uniforms.rectAreaLights.value = lights.state.rectArea;
  14801. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  14802. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  14803. uniforms.pointLights.value = lights.state.point;
  14804. uniforms.pointLightShadows.value = lights.state.pointShadow;
  14805. uniforms.hemisphereLights.value = lights.state.hemi;
  14806. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  14807. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  14808. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  14809. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  14810. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  14811. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniforms
  14812. }
  14813. const progUniforms = program.getUniforms();
  14814. const uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);
  14815. materialProperties.currentProgram = program;
  14816. materialProperties.uniformsList = uniformsList;
  14817. return program;
  14818. }
  14819. function updateCommonMaterialProperties(material, parameters) {
  14820. const materialProperties = properties.get(material);
  14821. materialProperties.outputEncoding = parameters.outputEncoding;
  14822. materialProperties.instancing = parameters.instancing;
  14823. materialProperties.skinning = parameters.skinning;
  14824. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  14825. materialProperties.numIntersection = parameters.numClipIntersection;
  14826. materialProperties.vertexAlphas = parameters.vertexAlphas;
  14827. }
  14828. function setProgram(camera, scene, material, object) {
  14829. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  14830. textures.resetTextureUnits();
  14831. const fog = scene.fog;
  14832. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  14833. const encoding = _currentRenderTarget === null ? _this.outputEncoding : _currentRenderTarget.texture.encoding;
  14834. const envMap = cubemaps.get(material.envMap || environment);
  14835. const vertexAlphas = material.vertexColors === true && object.geometry && object.geometry.attributes.color && object.geometry.attributes.color.itemSize === 4;
  14836. const materialProperties = properties.get(material);
  14837. const lights = currentRenderState.state.lights;
  14838. if (_clippingEnabled === true) {
  14839. if (_localClippingEnabled === true || camera !== _currentCamera) {
  14840. const useCache = camera === _currentCamera && material.id === _currentMaterialId; // we might want to call this function with some ClippingGroup
  14841. // object instead of the material, once it becomes feasible
  14842. // (#8465, #8379)
  14843. clipping.setState(material, camera, useCache);
  14844. }
  14845. } //
  14846. let needsProgramChange = false;
  14847. if (material.version === materialProperties.__version) {
  14848. if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) {
  14849. needsProgramChange = true;
  14850. } else if (materialProperties.outputEncoding !== encoding) {
  14851. needsProgramChange = true;
  14852. } else if (object.isInstancedMesh && materialProperties.instancing === false) {
  14853. needsProgramChange = true;
  14854. } else if (!object.isInstancedMesh && materialProperties.instancing === true) {
  14855. needsProgramChange = true;
  14856. } else if (object.isSkinnedMesh && materialProperties.skinning === false) {
  14857. needsProgramChange = true;
  14858. } else if (!object.isSkinnedMesh && materialProperties.skinning === true) {
  14859. needsProgramChange = true;
  14860. } else if (materialProperties.envMap !== envMap) {
  14861. needsProgramChange = true;
  14862. } else if (material.fog && materialProperties.fog !== fog) {
  14863. needsProgramChange = true;
  14864. } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== clipping.numPlanes || materialProperties.numIntersection !== clipping.numIntersection)) {
  14865. needsProgramChange = true;
  14866. } else if (materialProperties.vertexAlphas !== vertexAlphas) {
  14867. needsProgramChange = true;
  14868. }
  14869. } else {
  14870. needsProgramChange = true;
  14871. materialProperties.__version = material.version;
  14872. } //
  14873. let program = materialProperties.currentProgram;
  14874. if (needsProgramChange === true) {
  14875. program = getProgram(material, scene, object);
  14876. }
  14877. let refreshProgram = false;
  14878. let refreshMaterial = false;
  14879. let refreshLights = false;
  14880. const p_uniforms = program.getUniforms(),
  14881. m_uniforms = materialProperties.uniforms;
  14882. if (state.useProgram(program.program)) {
  14883. refreshProgram = true;
  14884. refreshMaterial = true;
  14885. refreshLights = true;
  14886. }
  14887. if (material.id !== _currentMaterialId) {
  14888. _currentMaterialId = material.id;
  14889. refreshMaterial = true;
  14890. }
  14891. if (refreshProgram || _currentCamera !== camera) {
  14892. p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);
  14893. if (capabilities.logarithmicDepthBuffer) {
  14894. p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  14895. }
  14896. if (_currentCamera !== camera) {
  14897. _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update
  14898. // now, in case this material supports lights - or later, when
  14899. // the next material that does gets activated:
  14900. refreshMaterial = true; // set to true on material change
  14901. refreshLights = true; // remains set until update done
  14902. } // load material specific uniforms
  14903. // (shader material also gets them for the sake of genericity)
  14904. if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshStandardMaterial || material.envMap) {
  14905. const uCamPos = p_uniforms.map.cameraPosition;
  14906. if (uCamPos !== undefined) {
  14907. uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));
  14908. }
  14909. }
  14910. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) {
  14911. p_uniforms.setValue(_gl, 'isOrthographic', camera.isOrthographicCamera === true);
  14912. }
  14913. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.isShadowMaterial || object.isSkinnedMesh) {
  14914. p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);
  14915. }
  14916. } // skinning uniforms must be set even if material didn't change
  14917. // auto-setting of texture unit for bone texture must go before other textures
  14918. // otherwise textures used for skinning can take over texture units reserved for other material textures
  14919. if (object.isSkinnedMesh) {
  14920. p_uniforms.setOptional(_gl, object, 'bindMatrix');
  14921. p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');
  14922. const skeleton = object.skeleton;
  14923. if (skeleton) {
  14924. const bones = skeleton.bones;
  14925. if (capabilities.floatVertexTextures) {
  14926. if (skeleton.boneTexture === null) {
  14927. // layout (1 matrix = 4 pixels)
  14928. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  14929. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  14930. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  14931. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  14932. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  14933. let size = Math.sqrt(bones.length * 4); // 4 pixels needed for 1 matrix
  14934. size = ceilPowerOfTwo(size);
  14935. size = Math.max(size, 4);
  14936. const boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
  14937. boneMatrices.set(skeleton.boneMatrices); // copy current values
  14938. const boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
  14939. skeleton.boneMatrices = boneMatrices;
  14940. skeleton.boneTexture = boneTexture;
  14941. skeleton.boneTextureSize = size;
  14942. }
  14943. p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);
  14944. p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);
  14945. } else {
  14946. p_uniforms.setOptional(_gl, skeleton, 'boneMatrices');
  14947. }
  14948. }
  14949. }
  14950. if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
  14951. materialProperties.receiveShadow = object.receiveShadow;
  14952. p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow);
  14953. }
  14954. if (refreshMaterial) {
  14955. p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
  14956. if (materialProperties.needsLights) {
  14957. // the current material requires lighting info
  14958. // note: all lighting uniforms are always set correctly
  14959. // they simply reference the renderer's state for their
  14960. // values
  14961. //
  14962. // use the current material's .needsUpdate flags to set
  14963. // the GL state when required
  14964. markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
  14965. } // refresh uniforms common to several materials
  14966. if (fog && material.fog) {
  14967. materials.refreshFogUniforms(m_uniforms, fog);
  14968. }
  14969. materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height);
  14970. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  14971. }
  14972. if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
  14973. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  14974. material.uniformsNeedUpdate = false;
  14975. }
  14976. if (material.isSpriteMaterial) {
  14977. p_uniforms.setValue(_gl, 'center', object.center);
  14978. } // common matrices
  14979. p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
  14980. p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
  14981. p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld);
  14982. return program;
  14983. } // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  14984. function markUniformsLightsNeedsUpdate(uniforms, value) {
  14985. uniforms.ambientLightColor.needsUpdate = value;
  14986. uniforms.lightProbe.needsUpdate = value;
  14987. uniforms.directionalLights.needsUpdate = value;
  14988. uniforms.directionalLightShadows.needsUpdate = value;
  14989. uniforms.pointLights.needsUpdate = value;
  14990. uniforms.pointLightShadows.needsUpdate = value;
  14991. uniforms.spotLights.needsUpdate = value;
  14992. uniforms.spotLightShadows.needsUpdate = value;
  14993. uniforms.rectAreaLights.needsUpdate = value;
  14994. uniforms.hemisphereLights.needsUpdate = value;
  14995. }
  14996. function materialNeedsLights(material) {
  14997. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
  14998. }
  14999. this.getActiveCubeFace = function () {
  15000. return _currentActiveCubeFace;
  15001. };
  15002. this.getActiveMipmapLevel = function () {
  15003. return _currentActiveMipmapLevel;
  15004. };
  15005. this.getRenderTarget = function () {
  15006. return _currentRenderTarget;
  15007. };
  15008. this.setRenderTarget = function (renderTarget, activeCubeFace = 0, activeMipmapLevel = 0) {
  15009. _currentRenderTarget = renderTarget;
  15010. _currentActiveCubeFace = activeCubeFace;
  15011. _currentActiveMipmapLevel = activeMipmapLevel;
  15012. if (renderTarget && properties.get(renderTarget).__webglFramebuffer === undefined) {
  15013. textures.setupRenderTarget(renderTarget);
  15014. }
  15015. let framebuffer = null;
  15016. let isCube = false;
  15017. let isRenderTarget3D = false;
  15018. if (renderTarget) {
  15019. const texture = renderTarget.texture;
  15020. if (texture.isDataTexture3D || texture.isDataTexture2DArray) {
  15021. isRenderTarget3D = true;
  15022. }
  15023. const __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
  15024. if (renderTarget.isWebGLCubeRenderTarget) {
  15025. framebuffer = __webglFramebuffer[activeCubeFace];
  15026. isCube = true;
  15027. } else if (renderTarget.isWebGLMultisampleRenderTarget) {
  15028. framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
  15029. } else {
  15030. framebuffer = __webglFramebuffer;
  15031. }
  15032. _currentViewport.copy(renderTarget.viewport);
  15033. _currentScissor.copy(renderTarget.scissor);
  15034. _currentScissorTest = renderTarget.scissorTest;
  15035. } else {
  15036. _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();
  15037. _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
  15038. _currentScissorTest = _scissorTest;
  15039. }
  15040. const framebufferBound = state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  15041. if (framebufferBound && capabilities.drawBuffers) {
  15042. let needsUpdate = false;
  15043. if (renderTarget) {
  15044. if (renderTarget.isWebGLMultipleRenderTargets) {
  15045. const textures = renderTarget.texture;
  15046. if (_currentDrawBuffers.length !== textures.length || _currentDrawBuffers[0] !== _gl.COLOR_ATTACHMENT0) {
  15047. for (let i = 0, il = textures.length; i < il; i++) {
  15048. _currentDrawBuffers[i] = _gl.COLOR_ATTACHMENT0 + i;
  15049. }
  15050. _currentDrawBuffers.length = textures.length;
  15051. needsUpdate = true;
  15052. }
  15053. } else {
  15054. if (_currentDrawBuffers.length !== 1 || _currentDrawBuffers[0] !== _gl.COLOR_ATTACHMENT0) {
  15055. _currentDrawBuffers[0] = _gl.COLOR_ATTACHMENT0;
  15056. _currentDrawBuffers.length = 1;
  15057. needsUpdate = true;
  15058. }
  15059. }
  15060. } else {
  15061. if (_currentDrawBuffers.length !== 1 || _currentDrawBuffers[0] !== _gl.BACK) {
  15062. _currentDrawBuffers[0] = _gl.BACK;
  15063. _currentDrawBuffers.length = 1;
  15064. needsUpdate = true;
  15065. }
  15066. }
  15067. if (needsUpdate) {
  15068. if (capabilities.isWebGL2) {
  15069. _gl.drawBuffers(_currentDrawBuffers);
  15070. } else {
  15071. extensions.get('WEBGL_draw_buffers').drawBuffersWEBGL(_currentDrawBuffers);
  15072. }
  15073. }
  15074. }
  15075. state.viewport(_currentViewport);
  15076. state.scissor(_currentScissor);
  15077. state.setScissorTest(_currentScissorTest);
  15078. if (isCube) {
  15079. const textureProperties = properties.get(renderTarget.texture);
  15080. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel);
  15081. } else if (isRenderTarget3D) {
  15082. const textureProperties = properties.get(renderTarget.texture);
  15083. const layer = activeCubeFace || 0;
  15084. _gl.framebufferTextureLayer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer);
  15085. }
  15086. };
  15087. this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
  15088. if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
  15089. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
  15090. return;
  15091. }
  15092. let framebuffer = properties.get(renderTarget).__webglFramebuffer;
  15093. if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) {
  15094. framebuffer = framebuffer[activeCubeFaceIndex];
  15095. }
  15096. if (framebuffer) {
  15097. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  15098. try {
  15099. const texture = renderTarget.texture;
  15100. const textureFormat = texture.format;
  15101. const textureType = texture.type;
  15102. if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_FORMAT)) {
  15103. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
  15104. return;
  15105. }
  15106. const halfFloatSupportedByExt = textureType === HalfFloatType && (extensions.has('EXT_color_buffer_half_float') || capabilities.isWebGL2 && extensions.has('EXT_color_buffer_float'));
  15107. if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_TYPE) && // Edge and Chrome Mac < 52 (#9513)
  15108. !(textureType === FloatType && (capabilities.isWebGL2 || extensions.has('OES_texture_float') || extensions.has('WEBGL_color_buffer_float'))) && // Chrome Mac >= 52 and Firefox
  15109. !halfFloatSupportedByExt) {
  15110. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
  15111. return;
  15112. }
  15113. if (_gl.checkFramebufferStatus(_gl.FRAMEBUFFER) === _gl.FRAMEBUFFER_COMPLETE) {
  15114. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  15115. if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {
  15116. _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
  15117. }
  15118. } else {
  15119. console.error('THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.');
  15120. }
  15121. } finally {
  15122. // restore framebuffer of current render target if necessary
  15123. const framebuffer = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null;
  15124. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  15125. }
  15126. }
  15127. };
  15128. this.copyFramebufferToTexture = function (position, texture, level = 0) {
  15129. const levelScale = Math.pow(2, -level);
  15130. const width = Math.floor(texture.image.width * levelScale);
  15131. const height = Math.floor(texture.image.height * levelScale);
  15132. const glFormat = utils.convert(texture.format);
  15133. textures.setTexture2D(texture, 0);
  15134. _gl.copyTexImage2D(_gl.TEXTURE_2D, level, glFormat, position.x, position.y, width, height, 0);
  15135. state.unbindTexture();
  15136. };
  15137. this.copyTextureToTexture = function (position, srcTexture, dstTexture, level = 0) {
  15138. const width = srcTexture.image.width;
  15139. const height = srcTexture.image.height;
  15140. const glFormat = utils.convert(dstTexture.format);
  15141. const glType = utils.convert(dstTexture.type);
  15142. textures.setTexture2D(dstTexture, 0); // As another texture upload may have changed pixelStorei
  15143. // parameters, make sure they are correct for the dstTexture
  15144. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  15145. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  15146. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  15147. if (srcTexture.isDataTexture) {
  15148. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
  15149. } else {
  15150. if (srcTexture.isCompressedTexture) {
  15151. _gl.compressedTexSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, srcTexture.mipmaps[0].width, srcTexture.mipmaps[0].height, glFormat, srcTexture.mipmaps[0].data);
  15152. } else {
  15153. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image);
  15154. }
  15155. } // Generate mipmaps only when copying level 0
  15156. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(_gl.TEXTURE_2D);
  15157. state.unbindTexture();
  15158. };
  15159. this.copyTextureToTexture3D = function (sourceBox, position, srcTexture, dstTexture, level = 0) {
  15160. if (_this.isWebGL1Renderer) {
  15161. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.');
  15162. return;
  15163. }
  15164. const {
  15165. width,
  15166. height,
  15167. data
  15168. } = srcTexture.image;
  15169. const glFormat = utils.convert(dstTexture.format);
  15170. const glType = utils.convert(dstTexture.type);
  15171. let glTarget;
  15172. if (dstTexture.isDataTexture3D) {
  15173. textures.setTexture3D(dstTexture, 0);
  15174. glTarget = _gl.TEXTURE_3D;
  15175. } else if (dstTexture.isDataTexture2DArray) {
  15176. textures.setTexture2DArray(dstTexture, 0);
  15177. glTarget = _gl.TEXTURE_2D_ARRAY;
  15178. } else {
  15179. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.');
  15180. return;
  15181. }
  15182. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  15183. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  15184. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  15185. const unpackRowLen = _gl.getParameter(_gl.UNPACK_ROW_LENGTH);
  15186. const unpackImageHeight = _gl.getParameter(_gl.UNPACK_IMAGE_HEIGHT);
  15187. const unpackSkipPixels = _gl.getParameter(_gl.UNPACK_SKIP_PIXELS);
  15188. const unpackSkipRows = _gl.getParameter(_gl.UNPACK_SKIP_ROWS);
  15189. const unpackSkipImages = _gl.getParameter(_gl.UNPACK_SKIP_IMAGES);
  15190. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, width);
  15191. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, height);
  15192. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, sourceBox.min.x);
  15193. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, sourceBox.min.y);
  15194. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, sourceBox.min.z);
  15195. _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, sourceBox.max.x - sourceBox.min.x + 1, sourceBox.max.y - sourceBox.min.y + 1, sourceBox.max.z - sourceBox.min.z + 1, glFormat, glType, data);
  15196. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, unpackRowLen);
  15197. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, unpackImageHeight);
  15198. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, unpackSkipPixels);
  15199. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, unpackSkipRows);
  15200. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, unpackSkipImages); // Generate mipmaps only when copying level 0
  15201. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(glTarget);
  15202. state.unbindTexture();
  15203. };
  15204. this.initTexture = function (texture) {
  15205. textures.setTexture2D(texture, 0);
  15206. state.unbindTexture();
  15207. };
  15208. this.resetState = function () {
  15209. _currentActiveCubeFace = 0;
  15210. _currentActiveMipmapLevel = 0;
  15211. _currentRenderTarget = null;
  15212. state.reset();
  15213. bindingStates.reset();
  15214. };
  15215. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  15216. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  15217. detail: this
  15218. })); // eslint-disable-line no-undef
  15219. }
  15220. }
  15221. class WebGL1Renderer extends WebGLRenderer {}
  15222. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  15223. class FogExp2 {
  15224. constructor(color, density = 0.00025) {
  15225. this.name = '';
  15226. this.color = new Color(color);
  15227. this.density = density;
  15228. }
  15229. clone() {
  15230. return new FogExp2(this.color, this.density);
  15231. }
  15232. toJSON()
  15233. /* meta */
  15234. {
  15235. return {
  15236. type: 'FogExp2',
  15237. color: this.color.getHex(),
  15238. density: this.density
  15239. };
  15240. }
  15241. }
  15242. FogExp2.prototype.isFogExp2 = true;
  15243. class Fog {
  15244. constructor(color, near = 1, far = 1000) {
  15245. this.name = '';
  15246. this.color = new Color(color);
  15247. this.near = near;
  15248. this.far = far;
  15249. }
  15250. clone() {
  15251. return new Fog(this.color, this.near, this.far);
  15252. }
  15253. toJSON()
  15254. /* meta */
  15255. {
  15256. return {
  15257. type: 'Fog',
  15258. color: this.color.getHex(),
  15259. near: this.near,
  15260. far: this.far
  15261. };
  15262. }
  15263. }
  15264. Fog.prototype.isFog = true;
  15265. class Scene extends Object3D {
  15266. constructor() {
  15267. super();
  15268. this.type = 'Scene';
  15269. this.background = null;
  15270. this.environment = null;
  15271. this.fog = null;
  15272. this.overrideMaterial = null;
  15273. this.autoUpdate = true; // checked by the renderer
  15274. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  15275. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  15276. detail: this
  15277. })); // eslint-disable-line no-undef
  15278. }
  15279. }
  15280. copy(source, recursive) {
  15281. super.copy(source, recursive);
  15282. if (source.background !== null) this.background = source.background.clone();
  15283. if (source.environment !== null) this.environment = source.environment.clone();
  15284. if (source.fog !== null) this.fog = source.fog.clone();
  15285. if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
  15286. this.autoUpdate = source.autoUpdate;
  15287. this.matrixAutoUpdate = source.matrixAutoUpdate;
  15288. return this;
  15289. }
  15290. toJSON(meta) {
  15291. const data = super.toJSON(meta);
  15292. if (this.background !== null) data.object.background = this.background.toJSON(meta);
  15293. if (this.environment !== null) data.object.environment = this.environment.toJSON(meta);
  15294. if (this.fog !== null) data.object.fog = this.fog.toJSON();
  15295. return data;
  15296. }
  15297. }
  15298. Scene.prototype.isScene = true;
  15299. class InterleavedBuffer {
  15300. constructor(array, stride) {
  15301. this.array = array;
  15302. this.stride = stride;
  15303. this.count = array !== undefined ? array.length / stride : 0;
  15304. this.usage = StaticDrawUsage;
  15305. this.updateRange = {
  15306. offset: 0,
  15307. count: -1
  15308. };
  15309. this.version = 0;
  15310. this.uuid = generateUUID();
  15311. }
  15312. onUploadCallback() {}
  15313. set needsUpdate(value) {
  15314. if (value === true) this.version++;
  15315. }
  15316. setUsage(value) {
  15317. this.usage = value;
  15318. return this;
  15319. }
  15320. copy(source) {
  15321. this.array = new source.array.constructor(source.array);
  15322. this.count = source.count;
  15323. this.stride = source.stride;
  15324. this.usage = source.usage;
  15325. return this;
  15326. }
  15327. copyAt(index1, attribute, index2) {
  15328. index1 *= this.stride;
  15329. index2 *= attribute.stride;
  15330. for (let i = 0, l = this.stride; i < l; i++) {
  15331. this.array[index1 + i] = attribute.array[index2 + i];
  15332. }
  15333. return this;
  15334. }
  15335. set(value, offset = 0) {
  15336. this.array.set(value, offset);
  15337. return this;
  15338. }
  15339. clone(data) {
  15340. if (data.arrayBuffers === undefined) {
  15341. data.arrayBuffers = {};
  15342. }
  15343. if (this.array.buffer._uuid === undefined) {
  15344. this.array.buffer._uuid = generateUUID();
  15345. }
  15346. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  15347. data.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer;
  15348. }
  15349. const array = new this.array.constructor(data.arrayBuffers[this.array.buffer._uuid]);
  15350. const ib = new this.constructor(array, this.stride);
  15351. ib.setUsage(this.usage);
  15352. return ib;
  15353. }
  15354. onUpload(callback) {
  15355. this.onUploadCallback = callback;
  15356. return this;
  15357. }
  15358. toJSON(data) {
  15359. if (data.arrayBuffers === undefined) {
  15360. data.arrayBuffers = {};
  15361. } // generate UUID for array buffer if necessary
  15362. if (this.array.buffer._uuid === undefined) {
  15363. this.array.buffer._uuid = generateUUID();
  15364. }
  15365. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  15366. data.arrayBuffers[this.array.buffer._uuid] = Array.prototype.slice.call(new Uint32Array(this.array.buffer));
  15367. } //
  15368. return {
  15369. uuid: this.uuid,
  15370. buffer: this.array.buffer._uuid,
  15371. type: this.array.constructor.name,
  15372. stride: this.stride
  15373. };
  15374. }
  15375. }
  15376. InterleavedBuffer.prototype.isInterleavedBuffer = true;
  15377. const _vector$6 = /*@__PURE__*/new Vector3();
  15378. class InterleavedBufferAttribute {
  15379. constructor(interleavedBuffer, itemSize, offset, normalized) {
  15380. this.name = '';
  15381. this.data = interleavedBuffer;
  15382. this.itemSize = itemSize;
  15383. this.offset = offset;
  15384. this.normalized = normalized === true;
  15385. }
  15386. get count() {
  15387. return this.data.count;
  15388. }
  15389. get array() {
  15390. return this.data.array;
  15391. }
  15392. set needsUpdate(value) {
  15393. this.data.needsUpdate = value;
  15394. }
  15395. applyMatrix4(m) {
  15396. for (let i = 0, l = this.data.count; i < l; i++) {
  15397. _vector$6.x = this.getX(i);
  15398. _vector$6.y = this.getY(i);
  15399. _vector$6.z = this.getZ(i);
  15400. _vector$6.applyMatrix4(m);
  15401. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  15402. }
  15403. return this;
  15404. }
  15405. applyNormalMatrix(m) {
  15406. for (let i = 0, l = this.count; i < l; i++) {
  15407. _vector$6.x = this.getX(i);
  15408. _vector$6.y = this.getY(i);
  15409. _vector$6.z = this.getZ(i);
  15410. _vector$6.applyNormalMatrix(m);
  15411. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  15412. }
  15413. return this;
  15414. }
  15415. transformDirection(m) {
  15416. for (let i = 0, l = this.count; i < l; i++) {
  15417. _vector$6.x = this.getX(i);
  15418. _vector$6.y = this.getY(i);
  15419. _vector$6.z = this.getZ(i);
  15420. _vector$6.transformDirection(m);
  15421. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  15422. }
  15423. return this;
  15424. }
  15425. setX(index, x) {
  15426. this.data.array[index * this.data.stride + this.offset] = x;
  15427. return this;
  15428. }
  15429. setY(index, y) {
  15430. this.data.array[index * this.data.stride + this.offset + 1] = y;
  15431. return this;
  15432. }
  15433. setZ(index, z) {
  15434. this.data.array[index * this.data.stride + this.offset + 2] = z;
  15435. return this;
  15436. }
  15437. setW(index, w) {
  15438. this.data.array[index * this.data.stride + this.offset + 3] = w;
  15439. return this;
  15440. }
  15441. getX(index) {
  15442. return this.data.array[index * this.data.stride + this.offset];
  15443. }
  15444. getY(index) {
  15445. return this.data.array[index * this.data.stride + this.offset + 1];
  15446. }
  15447. getZ(index) {
  15448. return this.data.array[index * this.data.stride + this.offset + 2];
  15449. }
  15450. getW(index) {
  15451. return this.data.array[index * this.data.stride + this.offset + 3];
  15452. }
  15453. setXY(index, x, y) {
  15454. index = index * this.data.stride + this.offset;
  15455. this.data.array[index + 0] = x;
  15456. this.data.array[index + 1] = y;
  15457. return this;
  15458. }
  15459. setXYZ(index, x, y, z) {
  15460. index = index * this.data.stride + this.offset;
  15461. this.data.array[index + 0] = x;
  15462. this.data.array[index + 1] = y;
  15463. this.data.array[index + 2] = z;
  15464. return this;
  15465. }
  15466. setXYZW(index, x, y, z, w) {
  15467. index = index * this.data.stride + this.offset;
  15468. this.data.array[index + 0] = x;
  15469. this.data.array[index + 1] = y;
  15470. this.data.array[index + 2] = z;
  15471. this.data.array[index + 3] = w;
  15472. return this;
  15473. }
  15474. clone(data) {
  15475. if (data === undefined) {
  15476. console.log('THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.');
  15477. const array = [];
  15478. for (let i = 0; i < this.count; i++) {
  15479. const index = i * this.data.stride + this.offset;
  15480. for (let j = 0; j < this.itemSize; j++) {
  15481. array.push(this.data.array[index + j]);
  15482. }
  15483. }
  15484. return new BufferAttribute(new this.array.constructor(array), this.itemSize, this.normalized);
  15485. } else {
  15486. if (data.interleavedBuffers === undefined) {
  15487. data.interleavedBuffers = {};
  15488. }
  15489. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  15490. data.interleavedBuffers[this.data.uuid] = this.data.clone(data);
  15491. }
  15492. return new InterleavedBufferAttribute(data.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized);
  15493. }
  15494. }
  15495. toJSON(data) {
  15496. if (data === undefined) {
  15497. console.log('THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.');
  15498. const array = [];
  15499. for (let i = 0; i < this.count; i++) {
  15500. const index = i * this.data.stride + this.offset;
  15501. for (let j = 0; j < this.itemSize; j++) {
  15502. array.push(this.data.array[index + j]);
  15503. }
  15504. } // deinterleave data and save it as an ordinary buffer attribute for now
  15505. return {
  15506. itemSize: this.itemSize,
  15507. type: this.array.constructor.name,
  15508. array: array,
  15509. normalized: this.normalized
  15510. };
  15511. } else {
  15512. // save as true interlaved attribtue
  15513. if (data.interleavedBuffers === undefined) {
  15514. data.interleavedBuffers = {};
  15515. }
  15516. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  15517. data.interleavedBuffers[this.data.uuid] = this.data.toJSON(data);
  15518. }
  15519. return {
  15520. isInterleavedBufferAttribute: true,
  15521. itemSize: this.itemSize,
  15522. data: this.data.uuid,
  15523. offset: this.offset,
  15524. normalized: this.normalized
  15525. };
  15526. }
  15527. }
  15528. }
  15529. InterleavedBufferAttribute.prototype.isInterleavedBufferAttribute = true;
  15530. /**
  15531. * parameters = {
  15532. * color: <hex>,
  15533. * map: new THREE.Texture( <Image> ),
  15534. * alphaMap: new THREE.Texture( <Image> ),
  15535. * rotation: <float>,
  15536. * sizeAttenuation: <bool>
  15537. * }
  15538. */
  15539. class SpriteMaterial extends Material {
  15540. constructor(parameters) {
  15541. super();
  15542. this.type = 'SpriteMaterial';
  15543. this.color = new Color(0xffffff);
  15544. this.map = null;
  15545. this.alphaMap = null;
  15546. this.rotation = 0;
  15547. this.sizeAttenuation = true;
  15548. this.transparent = true;
  15549. this.setValues(parameters);
  15550. }
  15551. copy(source) {
  15552. super.copy(source);
  15553. this.color.copy(source.color);
  15554. this.map = source.map;
  15555. this.alphaMap = source.alphaMap;
  15556. this.rotation = source.rotation;
  15557. this.sizeAttenuation = source.sizeAttenuation;
  15558. return this;
  15559. }
  15560. }
  15561. SpriteMaterial.prototype.isSpriteMaterial = true;
  15562. let _geometry;
  15563. const _intersectPoint = /*@__PURE__*/new Vector3();
  15564. const _worldScale = /*@__PURE__*/new Vector3();
  15565. const _mvPosition = /*@__PURE__*/new Vector3();
  15566. const _alignedPosition = /*@__PURE__*/new Vector2();
  15567. const _rotatedPosition = /*@__PURE__*/new Vector2();
  15568. const _viewWorldMatrix = /*@__PURE__*/new Matrix4();
  15569. const _vA = /*@__PURE__*/new Vector3();
  15570. const _vB = /*@__PURE__*/new Vector3();
  15571. const _vC = /*@__PURE__*/new Vector3();
  15572. const _uvA = /*@__PURE__*/new Vector2();
  15573. const _uvB = /*@__PURE__*/new Vector2();
  15574. const _uvC = /*@__PURE__*/new Vector2();
  15575. class Sprite extends Object3D {
  15576. constructor(material) {
  15577. super();
  15578. this.type = 'Sprite';
  15579. if (_geometry === undefined) {
  15580. _geometry = new BufferGeometry();
  15581. 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]);
  15582. const interleavedBuffer = new InterleavedBuffer(float32Array, 5);
  15583. _geometry.setIndex([0, 1, 2, 0, 2, 3]);
  15584. _geometry.setAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
  15585. _geometry.setAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
  15586. }
  15587. this.geometry = _geometry;
  15588. this.material = material !== undefined ? material : new SpriteMaterial();
  15589. this.center = new Vector2(0.5, 0.5);
  15590. }
  15591. raycast(raycaster, intersects) {
  15592. if (raycaster.camera === null) {
  15593. console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
  15594. }
  15595. _worldScale.setFromMatrixScale(this.matrixWorld);
  15596. _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
  15597. this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
  15598. _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
  15599. if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
  15600. _worldScale.multiplyScalar(-_mvPosition.z);
  15601. }
  15602. const rotation = this.material.rotation;
  15603. let sin, cos;
  15604. if (rotation !== 0) {
  15605. cos = Math.cos(rotation);
  15606. sin = Math.sin(rotation);
  15607. }
  15608. const center = this.center;
  15609. transformVertex(_vA.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  15610. transformVertex(_vB.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  15611. transformVertex(_vC.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  15612. _uvA.set(0, 0);
  15613. _uvB.set(1, 0);
  15614. _uvC.set(1, 1); // check first triangle
  15615. let intersect = raycaster.ray.intersectTriangle(_vA, _vB, _vC, false, _intersectPoint);
  15616. if (intersect === null) {
  15617. // check second triangle
  15618. transformVertex(_vB.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  15619. _uvB.set(0, 1);
  15620. intersect = raycaster.ray.intersectTriangle(_vA, _vC, _vB, false, _intersectPoint);
  15621. if (intersect === null) {
  15622. return;
  15623. }
  15624. }
  15625. const distance = raycaster.ray.origin.distanceTo(_intersectPoint);
  15626. if (distance < raycaster.near || distance > raycaster.far) return;
  15627. intersects.push({
  15628. distance: distance,
  15629. point: _intersectPoint.clone(),
  15630. uv: Triangle.getUV(_intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2()),
  15631. face: null,
  15632. object: this
  15633. });
  15634. }
  15635. copy(source) {
  15636. super.copy(source);
  15637. if (source.center !== undefined) this.center.copy(source.center);
  15638. this.material = source.material;
  15639. return this;
  15640. }
  15641. }
  15642. Sprite.prototype.isSprite = true;
  15643. function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
  15644. // compute position in camera space
  15645. _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); // to check if rotation is not zero
  15646. if (sin !== undefined) {
  15647. _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
  15648. _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
  15649. } else {
  15650. _rotatedPosition.copy(_alignedPosition);
  15651. }
  15652. vertexPosition.copy(mvPosition);
  15653. vertexPosition.x += _rotatedPosition.x;
  15654. vertexPosition.y += _rotatedPosition.y; // transform to world space
  15655. vertexPosition.applyMatrix4(_viewWorldMatrix);
  15656. }
  15657. const _v1$2 = /*@__PURE__*/new Vector3();
  15658. const _v2$1 = /*@__PURE__*/new Vector3();
  15659. class LOD extends Object3D {
  15660. constructor() {
  15661. super();
  15662. this._currentLevel = 0;
  15663. this.type = 'LOD';
  15664. Object.defineProperties(this, {
  15665. levels: {
  15666. enumerable: true,
  15667. value: []
  15668. },
  15669. isLOD: {
  15670. value: true
  15671. }
  15672. });
  15673. this.autoUpdate = true;
  15674. }
  15675. copy(source) {
  15676. super.copy(source, false);
  15677. const levels = source.levels;
  15678. for (let i = 0, l = levels.length; i < l; i++) {
  15679. const level = levels[i];
  15680. this.addLevel(level.object.clone(), level.distance);
  15681. }
  15682. this.autoUpdate = source.autoUpdate;
  15683. return this;
  15684. }
  15685. addLevel(object, distance = 0) {
  15686. distance = Math.abs(distance);
  15687. const levels = this.levels;
  15688. let l;
  15689. for (l = 0; l < levels.length; l++) {
  15690. if (distance < levels[l].distance) {
  15691. break;
  15692. }
  15693. }
  15694. levels.splice(l, 0, {
  15695. distance: distance,
  15696. object: object
  15697. });
  15698. this.add(object);
  15699. return this;
  15700. }
  15701. getCurrentLevel() {
  15702. return this._currentLevel;
  15703. }
  15704. getObjectForDistance(distance) {
  15705. const levels = this.levels;
  15706. if (levels.length > 0) {
  15707. let i, l;
  15708. for (i = 1, l = levels.length; i < l; i++) {
  15709. if (distance < levels[i].distance) {
  15710. break;
  15711. }
  15712. }
  15713. return levels[i - 1].object;
  15714. }
  15715. return null;
  15716. }
  15717. raycast(raycaster, intersects) {
  15718. const levels = this.levels;
  15719. if (levels.length > 0) {
  15720. _v1$2.setFromMatrixPosition(this.matrixWorld);
  15721. const distance = raycaster.ray.origin.distanceTo(_v1$2);
  15722. this.getObjectForDistance(distance).raycast(raycaster, intersects);
  15723. }
  15724. }
  15725. update(camera) {
  15726. const levels = this.levels;
  15727. if (levels.length > 1) {
  15728. _v1$2.setFromMatrixPosition(camera.matrixWorld);
  15729. _v2$1.setFromMatrixPosition(this.matrixWorld);
  15730. const distance = _v1$2.distanceTo(_v2$1) / camera.zoom;
  15731. levels[0].object.visible = true;
  15732. let i, l;
  15733. for (i = 1, l = levels.length; i < l; i++) {
  15734. if (distance >= levels[i].distance) {
  15735. levels[i - 1].object.visible = false;
  15736. levels[i].object.visible = true;
  15737. } else {
  15738. break;
  15739. }
  15740. }
  15741. this._currentLevel = i - 1;
  15742. for (; i < l; i++) {
  15743. levels[i].object.visible = false;
  15744. }
  15745. }
  15746. }
  15747. toJSON(meta) {
  15748. const data = super.toJSON(meta);
  15749. if (this.autoUpdate === false) data.object.autoUpdate = false;
  15750. data.object.levels = [];
  15751. const levels = this.levels;
  15752. for (let i = 0, l = levels.length; i < l; i++) {
  15753. const level = levels[i];
  15754. data.object.levels.push({
  15755. object: level.object.uuid,
  15756. distance: level.distance
  15757. });
  15758. }
  15759. return data;
  15760. }
  15761. }
  15762. const _basePosition = /*@__PURE__*/new Vector3();
  15763. const _skinIndex = /*@__PURE__*/new Vector4();
  15764. const _skinWeight = /*@__PURE__*/new Vector4();
  15765. const _vector$5 = /*@__PURE__*/new Vector3();
  15766. const _matrix = /*@__PURE__*/new Matrix4();
  15767. class SkinnedMesh extends Mesh {
  15768. constructor(geometry, material) {
  15769. super(geometry, material);
  15770. this.type = 'SkinnedMesh';
  15771. this.bindMode = 'attached';
  15772. this.bindMatrix = new Matrix4();
  15773. this.bindMatrixInverse = new Matrix4();
  15774. }
  15775. copy(source) {
  15776. super.copy(source);
  15777. this.bindMode = source.bindMode;
  15778. this.bindMatrix.copy(source.bindMatrix);
  15779. this.bindMatrixInverse.copy(source.bindMatrixInverse);
  15780. this.skeleton = source.skeleton;
  15781. return this;
  15782. }
  15783. bind(skeleton, bindMatrix) {
  15784. this.skeleton = skeleton;
  15785. if (bindMatrix === undefined) {
  15786. this.updateMatrixWorld(true);
  15787. this.skeleton.calculateInverses();
  15788. bindMatrix = this.matrixWorld;
  15789. }
  15790. this.bindMatrix.copy(bindMatrix);
  15791. this.bindMatrixInverse.copy(bindMatrix).invert();
  15792. }
  15793. pose() {
  15794. this.skeleton.pose();
  15795. }
  15796. normalizeSkinWeights() {
  15797. const vector = new Vector4();
  15798. const skinWeight = this.geometry.attributes.skinWeight;
  15799. for (let i = 0, l = skinWeight.count; i < l; i++) {
  15800. vector.x = skinWeight.getX(i);
  15801. vector.y = skinWeight.getY(i);
  15802. vector.z = skinWeight.getZ(i);
  15803. vector.w = skinWeight.getW(i);
  15804. const scale = 1.0 / vector.manhattanLength();
  15805. if (scale !== Infinity) {
  15806. vector.multiplyScalar(scale);
  15807. } else {
  15808. vector.set(1, 0, 0, 0); // do something reasonable
  15809. }
  15810. skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
  15811. }
  15812. }
  15813. updateMatrixWorld(force) {
  15814. super.updateMatrixWorld(force);
  15815. if (this.bindMode === 'attached') {
  15816. this.bindMatrixInverse.copy(this.matrixWorld).invert();
  15817. } else if (this.bindMode === 'detached') {
  15818. this.bindMatrixInverse.copy(this.bindMatrix).invert();
  15819. } else {
  15820. console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
  15821. }
  15822. }
  15823. boneTransform(index, target) {
  15824. const skeleton = this.skeleton;
  15825. const geometry = this.geometry;
  15826. _skinIndex.fromBufferAttribute(geometry.attributes.skinIndex, index);
  15827. _skinWeight.fromBufferAttribute(geometry.attributes.skinWeight, index);
  15828. _basePosition.fromBufferAttribute(geometry.attributes.position, index).applyMatrix4(this.bindMatrix);
  15829. target.set(0, 0, 0);
  15830. for (let i = 0; i < 4; i++) {
  15831. const weight = _skinWeight.getComponent(i);
  15832. if (weight !== 0) {
  15833. const boneIndex = _skinIndex.getComponent(i);
  15834. _matrix.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld, skeleton.boneInverses[boneIndex]);
  15835. target.addScaledVector(_vector$5.copy(_basePosition).applyMatrix4(_matrix), weight);
  15836. }
  15837. }
  15838. return target.applyMatrix4(this.bindMatrixInverse);
  15839. }
  15840. }
  15841. SkinnedMesh.prototype.isSkinnedMesh = true;
  15842. class Bone extends Object3D {
  15843. constructor() {
  15844. super();
  15845. this.type = 'Bone';
  15846. }
  15847. }
  15848. Bone.prototype.isBone = true;
  15849. const _offsetMatrix = /*@__PURE__*/new Matrix4();
  15850. const _identityMatrix = /*@__PURE__*/new Matrix4();
  15851. class Skeleton {
  15852. constructor(bones = [], boneInverses = []) {
  15853. this.uuid = generateUUID();
  15854. this.bones = bones.slice(0);
  15855. this.boneInverses = boneInverses;
  15856. this.boneMatrices = null;
  15857. this.boneTexture = null;
  15858. this.boneTextureSize = 0;
  15859. this.frame = -1;
  15860. this.init();
  15861. }
  15862. init() {
  15863. const bones = this.bones;
  15864. const boneInverses = this.boneInverses;
  15865. this.boneMatrices = new Float32Array(bones.length * 16); // calculate inverse bone matrices if necessary
  15866. if (boneInverses.length === 0) {
  15867. this.calculateInverses();
  15868. } else {
  15869. // handle special case
  15870. if (bones.length !== boneInverses.length) {
  15871. console.warn('THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.');
  15872. this.boneInverses = [];
  15873. for (let i = 0, il = this.bones.length; i < il; i++) {
  15874. this.boneInverses.push(new Matrix4());
  15875. }
  15876. }
  15877. }
  15878. }
  15879. calculateInverses() {
  15880. this.boneInverses.length = 0;
  15881. for (let i = 0, il = this.bones.length; i < il; i++) {
  15882. const inverse = new Matrix4();
  15883. if (this.bones[i]) {
  15884. inverse.copy(this.bones[i].matrixWorld).invert();
  15885. }
  15886. this.boneInverses.push(inverse);
  15887. }
  15888. }
  15889. pose() {
  15890. // recover the bind-time world matrices
  15891. for (let i = 0, il = this.bones.length; i < il; i++) {
  15892. const bone = this.bones[i];
  15893. if (bone) {
  15894. bone.matrixWorld.copy(this.boneInverses[i]).invert();
  15895. }
  15896. } // compute the local matrices, positions, rotations and scales
  15897. for (let i = 0, il = this.bones.length; i < il; i++) {
  15898. const bone = this.bones[i];
  15899. if (bone) {
  15900. if (bone.parent && bone.parent.isBone) {
  15901. bone.matrix.copy(bone.parent.matrixWorld).invert();
  15902. bone.matrix.multiply(bone.matrixWorld);
  15903. } else {
  15904. bone.matrix.copy(bone.matrixWorld);
  15905. }
  15906. bone.matrix.decompose(bone.position, bone.quaternion, bone.scale);
  15907. }
  15908. }
  15909. }
  15910. update() {
  15911. const bones = this.bones;
  15912. const boneInverses = this.boneInverses;
  15913. const boneMatrices = this.boneMatrices;
  15914. const boneTexture = this.boneTexture; // flatten bone matrices to array
  15915. for (let i = 0, il = bones.length; i < il; i++) {
  15916. // compute the offset between the current and the original transform
  15917. const matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
  15918. _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
  15919. _offsetMatrix.toArray(boneMatrices, i * 16);
  15920. }
  15921. if (boneTexture !== null) {
  15922. boneTexture.needsUpdate = true;
  15923. }
  15924. }
  15925. clone() {
  15926. return new Skeleton(this.bones, this.boneInverses);
  15927. }
  15928. getBoneByName(name) {
  15929. for (let i = 0, il = this.bones.length; i < il; i++) {
  15930. const bone = this.bones[i];
  15931. if (bone.name === name) {
  15932. return bone;
  15933. }
  15934. }
  15935. return undefined;
  15936. }
  15937. dispose() {
  15938. if (this.boneTexture !== null) {
  15939. this.boneTexture.dispose();
  15940. this.boneTexture = null;
  15941. }
  15942. }
  15943. fromJSON(json, bones) {
  15944. this.uuid = json.uuid;
  15945. for (let i = 0, l = json.bones.length; i < l; i++) {
  15946. const uuid = json.bones[i];
  15947. let bone = bones[uuid];
  15948. if (bone === undefined) {
  15949. console.warn('THREE.Skeleton: No bone found with UUID:', uuid);
  15950. bone = new Bone();
  15951. }
  15952. this.bones.push(bone);
  15953. this.boneInverses.push(new Matrix4().fromArray(json.boneInverses[i]));
  15954. }
  15955. this.init();
  15956. return this;
  15957. }
  15958. toJSON() {
  15959. const data = {
  15960. metadata: {
  15961. version: 4.5,
  15962. type: 'Skeleton',
  15963. generator: 'Skeleton.toJSON'
  15964. },
  15965. bones: [],
  15966. boneInverses: []
  15967. };
  15968. data.uuid = this.uuid;
  15969. const bones = this.bones;
  15970. const boneInverses = this.boneInverses;
  15971. for (let i = 0, l = bones.length; i < l; i++) {
  15972. const bone = bones[i];
  15973. data.bones.push(bone.uuid);
  15974. const boneInverse = boneInverses[i];
  15975. data.boneInverses.push(boneInverse.toArray());
  15976. }
  15977. return data;
  15978. }
  15979. }
  15980. const _instanceLocalMatrix = /*@__PURE__*/new Matrix4();
  15981. const _instanceWorldMatrix = /*@__PURE__*/new Matrix4();
  15982. const _instanceIntersects = [];
  15983. const _mesh = /*@__PURE__*/new Mesh();
  15984. class InstancedMesh extends Mesh {
  15985. constructor(geometry, material, count) {
  15986. super(geometry, material);
  15987. this.instanceMatrix = new BufferAttribute(new Float32Array(count * 16), 16);
  15988. this.instanceColor = null;
  15989. this.count = count;
  15990. this.frustumCulled = false;
  15991. }
  15992. copy(source) {
  15993. super.copy(source);
  15994. this.instanceMatrix.copy(source.instanceMatrix);
  15995. if (source.instanceColor !== null) this.instanceColor = source.instanceColor.clone();
  15996. this.count = source.count;
  15997. return this;
  15998. }
  15999. getColorAt(index, color) {
  16000. color.fromArray(this.instanceColor.array, index * 3);
  16001. }
  16002. getMatrixAt(index, matrix) {
  16003. matrix.fromArray(this.instanceMatrix.array, index * 16);
  16004. }
  16005. raycast(raycaster, intersects) {
  16006. const matrixWorld = this.matrixWorld;
  16007. const raycastTimes = this.count;
  16008. _mesh.geometry = this.geometry;
  16009. _mesh.material = this.material;
  16010. if (_mesh.material === undefined) return;
  16011. for (let instanceId = 0; instanceId < raycastTimes; instanceId++) {
  16012. // calculate the world matrix for each instance
  16013. this.getMatrixAt(instanceId, _instanceLocalMatrix);
  16014. _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix); // the mesh represents this single instance
  16015. _mesh.matrixWorld = _instanceWorldMatrix;
  16016. _mesh.raycast(raycaster, _instanceIntersects); // process the result of raycast
  16017. for (let i = 0, l = _instanceIntersects.length; i < l; i++) {
  16018. const intersect = _instanceIntersects[i];
  16019. intersect.instanceId = instanceId;
  16020. intersect.object = this;
  16021. intersects.push(intersect);
  16022. }
  16023. _instanceIntersects.length = 0;
  16024. }
  16025. }
  16026. setColorAt(index, color) {
  16027. if (this.instanceColor === null) {
  16028. this.instanceColor = new BufferAttribute(new Float32Array(this.count * 3), 3);
  16029. }
  16030. color.toArray(this.instanceColor.array, index * 3);
  16031. }
  16032. setMatrixAt(index, matrix) {
  16033. matrix.toArray(this.instanceMatrix.array, index * 16);
  16034. }
  16035. updateMorphTargets() {}
  16036. dispose() {
  16037. this.dispatchEvent({
  16038. type: 'dispose'
  16039. });
  16040. }
  16041. }
  16042. InstancedMesh.prototype.isInstancedMesh = true;
  16043. /**
  16044. * parameters = {
  16045. * color: <hex>,
  16046. * opacity: <float>,
  16047. *
  16048. * linewidth: <float>,
  16049. * linecap: "round",
  16050. * linejoin: "round"
  16051. * }
  16052. */
  16053. class LineBasicMaterial extends Material {
  16054. constructor(parameters) {
  16055. super();
  16056. this.type = 'LineBasicMaterial';
  16057. this.color = new Color(0xffffff);
  16058. this.linewidth = 1;
  16059. this.linecap = 'round';
  16060. this.linejoin = 'round';
  16061. this.morphTargets = false;
  16062. this.setValues(parameters);
  16063. }
  16064. copy(source) {
  16065. super.copy(source);
  16066. this.color.copy(source.color);
  16067. this.linewidth = source.linewidth;
  16068. this.linecap = source.linecap;
  16069. this.linejoin = source.linejoin;
  16070. this.morphTargets = source.morphTargets;
  16071. return this;
  16072. }
  16073. }
  16074. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  16075. const _start$1 = /*@__PURE__*/new Vector3();
  16076. const _end$1 = /*@__PURE__*/new Vector3();
  16077. const _inverseMatrix$1 = /*@__PURE__*/new Matrix4();
  16078. const _ray$1 = /*@__PURE__*/new Ray();
  16079. const _sphere$1 = /*@__PURE__*/new Sphere();
  16080. class Line extends Object3D {
  16081. constructor(geometry = new BufferGeometry(), material = new LineBasicMaterial()) {
  16082. super();
  16083. this.type = 'Line';
  16084. this.geometry = geometry;
  16085. this.material = material;
  16086. this.updateMorphTargets();
  16087. }
  16088. copy(source) {
  16089. super.copy(source);
  16090. this.material = source.material;
  16091. this.geometry = source.geometry;
  16092. return this;
  16093. }
  16094. computeLineDistances() {
  16095. const geometry = this.geometry;
  16096. if (geometry.isBufferGeometry) {
  16097. // we assume non-indexed geometry
  16098. if (geometry.index === null) {
  16099. const positionAttribute = geometry.attributes.position;
  16100. const lineDistances = [0];
  16101. for (let i = 1, l = positionAttribute.count; i < l; i++) {
  16102. _start$1.fromBufferAttribute(positionAttribute, i - 1);
  16103. _end$1.fromBufferAttribute(positionAttribute, i);
  16104. lineDistances[i] = lineDistances[i - 1];
  16105. lineDistances[i] += _start$1.distanceTo(_end$1);
  16106. }
  16107. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  16108. } else {
  16109. console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  16110. }
  16111. } else if (geometry.isGeometry) {
  16112. console.error('THREE.Line.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16113. }
  16114. return this;
  16115. }
  16116. raycast(raycaster, intersects) {
  16117. const geometry = this.geometry;
  16118. const matrixWorld = this.matrixWorld;
  16119. const threshold = raycaster.params.Line.threshold;
  16120. const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
  16121. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  16122. _sphere$1.copy(geometry.boundingSphere);
  16123. _sphere$1.applyMatrix4(matrixWorld);
  16124. _sphere$1.radius += threshold;
  16125. if (raycaster.ray.intersectsSphere(_sphere$1) === false) return; //
  16126. _inverseMatrix$1.copy(matrixWorld).invert();
  16127. _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
  16128. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  16129. const localThresholdSq = localThreshold * localThreshold;
  16130. const vStart = new Vector3();
  16131. const vEnd = new Vector3();
  16132. const interSegment = new Vector3();
  16133. const interRay = new Vector3();
  16134. const step = this.isLineSegments ? 2 : 1;
  16135. if (geometry.isBufferGeometry) {
  16136. const index = geometry.index;
  16137. const attributes = geometry.attributes;
  16138. const positionAttribute = attributes.position;
  16139. if (index !== null) {
  16140. const start = Math.max(0, drawRange.start);
  16141. const end = Math.min(index.count, drawRange.start + drawRange.count);
  16142. for (let i = start, l = end - 1; i < l; i += step) {
  16143. const a = index.getX(i);
  16144. const b = index.getX(i + 1);
  16145. vStart.fromBufferAttribute(positionAttribute, a);
  16146. vEnd.fromBufferAttribute(positionAttribute, b);
  16147. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  16148. if (distSq > localThresholdSq) continue;
  16149. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  16150. const distance = raycaster.ray.origin.distanceTo(interRay);
  16151. if (distance < raycaster.near || distance > raycaster.far) continue;
  16152. intersects.push({
  16153. distance: distance,
  16154. // What do we want? intersection point on the ray or on the segment??
  16155. // point: raycaster.ray.at( distance ),
  16156. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  16157. index: i,
  16158. face: null,
  16159. faceIndex: null,
  16160. object: this
  16161. });
  16162. }
  16163. } else {
  16164. const start = Math.max(0, drawRange.start);
  16165. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  16166. for (let i = start, l = end - 1; i < l; i += step) {
  16167. vStart.fromBufferAttribute(positionAttribute, i);
  16168. vEnd.fromBufferAttribute(positionAttribute, i + 1);
  16169. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  16170. if (distSq > localThresholdSq) continue;
  16171. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  16172. const distance = raycaster.ray.origin.distanceTo(interRay);
  16173. if (distance < raycaster.near || distance > raycaster.far) continue;
  16174. intersects.push({
  16175. distance: distance,
  16176. // What do we want? intersection point on the ray or on the segment??
  16177. // point: raycaster.ray.at( distance ),
  16178. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  16179. index: i,
  16180. face: null,
  16181. faceIndex: null,
  16182. object: this
  16183. });
  16184. }
  16185. }
  16186. } else if (geometry.isGeometry) {
  16187. console.error('THREE.Line.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16188. }
  16189. }
  16190. updateMorphTargets() {
  16191. const geometry = this.geometry;
  16192. if (geometry.isBufferGeometry) {
  16193. const morphAttributes = geometry.morphAttributes;
  16194. const keys = Object.keys(morphAttributes);
  16195. if (keys.length > 0) {
  16196. const morphAttribute = morphAttributes[keys[0]];
  16197. if (morphAttribute !== undefined) {
  16198. this.morphTargetInfluences = [];
  16199. this.morphTargetDictionary = {};
  16200. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  16201. const name = morphAttribute[m].name || String(m);
  16202. this.morphTargetInfluences.push(0);
  16203. this.morphTargetDictionary[name] = m;
  16204. }
  16205. }
  16206. }
  16207. } else {
  16208. const morphTargets = geometry.morphTargets;
  16209. if (morphTargets !== undefined && morphTargets.length > 0) {
  16210. console.error('THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  16211. }
  16212. }
  16213. }
  16214. }
  16215. Line.prototype.isLine = true;
  16216. const _start = /*@__PURE__*/new Vector3();
  16217. const _end = /*@__PURE__*/new Vector3();
  16218. class LineSegments extends Line {
  16219. constructor(geometry, material) {
  16220. super(geometry, material);
  16221. this.type = 'LineSegments';
  16222. }
  16223. computeLineDistances() {
  16224. const geometry = this.geometry;
  16225. if (geometry.isBufferGeometry) {
  16226. // we assume non-indexed geometry
  16227. if (geometry.index === null) {
  16228. const positionAttribute = geometry.attributes.position;
  16229. const lineDistances = [];
  16230. for (let i = 0, l = positionAttribute.count; i < l; i += 2) {
  16231. _start.fromBufferAttribute(positionAttribute, i);
  16232. _end.fromBufferAttribute(positionAttribute, i + 1);
  16233. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  16234. lineDistances[i + 1] = lineDistances[i] + _start.distanceTo(_end);
  16235. }
  16236. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  16237. } else {
  16238. console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  16239. }
  16240. } else if (geometry.isGeometry) {
  16241. console.error('THREE.LineSegments.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16242. }
  16243. return this;
  16244. }
  16245. }
  16246. LineSegments.prototype.isLineSegments = true;
  16247. class LineLoop extends Line {
  16248. constructor(geometry, material) {
  16249. super(geometry, material);
  16250. this.type = 'LineLoop';
  16251. }
  16252. }
  16253. LineLoop.prototype.isLineLoop = true;
  16254. /**
  16255. * parameters = {
  16256. * color: <hex>,
  16257. * opacity: <float>,
  16258. * map: new THREE.Texture( <Image> ),
  16259. * alphaMap: new THREE.Texture( <Image> ),
  16260. *
  16261. * size: <float>,
  16262. * sizeAttenuation: <bool>
  16263. *
  16264. * morphTargets: <bool>
  16265. * }
  16266. */
  16267. class PointsMaterial extends Material {
  16268. constructor(parameters) {
  16269. super();
  16270. this.type = 'PointsMaterial';
  16271. this.color = new Color(0xffffff);
  16272. this.map = null;
  16273. this.alphaMap = null;
  16274. this.size = 1;
  16275. this.sizeAttenuation = true;
  16276. this.morphTargets = false;
  16277. this.setValues(parameters);
  16278. }
  16279. copy(source) {
  16280. super.copy(source);
  16281. this.color.copy(source.color);
  16282. this.map = source.map;
  16283. this.alphaMap = source.alphaMap;
  16284. this.size = source.size;
  16285. this.sizeAttenuation = source.sizeAttenuation;
  16286. this.morphTargets = source.morphTargets;
  16287. return this;
  16288. }
  16289. }
  16290. PointsMaterial.prototype.isPointsMaterial = true;
  16291. const _inverseMatrix = /*@__PURE__*/new Matrix4();
  16292. const _ray = /*@__PURE__*/new Ray();
  16293. const _sphere = /*@__PURE__*/new Sphere();
  16294. const _position$2 = /*@__PURE__*/new Vector3();
  16295. class Points extends Object3D {
  16296. constructor(geometry = new BufferGeometry(), material = new PointsMaterial()) {
  16297. super();
  16298. this.type = 'Points';
  16299. this.geometry = geometry;
  16300. this.material = material;
  16301. this.updateMorphTargets();
  16302. }
  16303. copy(source) {
  16304. super.copy(source);
  16305. this.material = source.material;
  16306. this.geometry = source.geometry;
  16307. return this;
  16308. }
  16309. raycast(raycaster, intersects) {
  16310. const geometry = this.geometry;
  16311. const matrixWorld = this.matrixWorld;
  16312. const threshold = raycaster.params.Points.threshold;
  16313. const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
  16314. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  16315. _sphere.copy(geometry.boundingSphere);
  16316. _sphere.applyMatrix4(matrixWorld);
  16317. _sphere.radius += threshold;
  16318. if (raycaster.ray.intersectsSphere(_sphere) === false) return; //
  16319. _inverseMatrix.copy(matrixWorld).invert();
  16320. _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix);
  16321. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  16322. const localThresholdSq = localThreshold * localThreshold;
  16323. if (geometry.isBufferGeometry) {
  16324. const index = geometry.index;
  16325. const attributes = geometry.attributes;
  16326. const positionAttribute = attributes.position;
  16327. if (index !== null) {
  16328. const start = Math.max(0, drawRange.start);
  16329. const end = Math.min(index.count, drawRange.start + drawRange.count);
  16330. for (let i = start, il = end; i < il; i++) {
  16331. const a = index.getX(i);
  16332. _position$2.fromBufferAttribute(positionAttribute, a);
  16333. testPoint(_position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this);
  16334. }
  16335. } else {
  16336. const start = Math.max(0, drawRange.start);
  16337. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  16338. for (let i = start, l = end; i < l; i++) {
  16339. _position$2.fromBufferAttribute(positionAttribute, i);
  16340. testPoint(_position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  16341. }
  16342. }
  16343. } else {
  16344. console.error('THREE.Points.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16345. }
  16346. }
  16347. updateMorphTargets() {
  16348. const geometry = this.geometry;
  16349. if (geometry.isBufferGeometry) {
  16350. const morphAttributes = geometry.morphAttributes;
  16351. const keys = Object.keys(morphAttributes);
  16352. if (keys.length > 0) {
  16353. const morphAttribute = morphAttributes[keys[0]];
  16354. if (morphAttribute !== undefined) {
  16355. this.morphTargetInfluences = [];
  16356. this.morphTargetDictionary = {};
  16357. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  16358. const name = morphAttribute[m].name || String(m);
  16359. this.morphTargetInfluences.push(0);
  16360. this.morphTargetDictionary[name] = m;
  16361. }
  16362. }
  16363. }
  16364. } else {
  16365. const morphTargets = geometry.morphTargets;
  16366. if (morphTargets !== undefined && morphTargets.length > 0) {
  16367. console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  16368. }
  16369. }
  16370. }
  16371. }
  16372. Points.prototype.isPoints = true;
  16373. function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
  16374. const rayPointDistanceSq = _ray.distanceSqToPoint(point);
  16375. if (rayPointDistanceSq < localThresholdSq) {
  16376. const intersectPoint = new Vector3();
  16377. _ray.closestPointToPoint(point, intersectPoint);
  16378. intersectPoint.applyMatrix4(matrixWorld);
  16379. const distance = raycaster.ray.origin.distanceTo(intersectPoint);
  16380. if (distance < raycaster.near || distance > raycaster.far) return;
  16381. intersects.push({
  16382. distance: distance,
  16383. distanceToRay: Math.sqrt(rayPointDistanceSq),
  16384. point: intersectPoint,
  16385. index: index,
  16386. face: null,
  16387. object: object
  16388. });
  16389. }
  16390. }
  16391. class VideoTexture extends Texture {
  16392. constructor(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  16393. super(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  16394. this.format = format !== undefined ? format : RGBFormat;
  16395. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  16396. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  16397. this.generateMipmaps = false;
  16398. const scope = this;
  16399. function updateVideo() {
  16400. scope.needsUpdate = true;
  16401. video.requestVideoFrameCallback(updateVideo);
  16402. }
  16403. if ('requestVideoFrameCallback' in video) {
  16404. video.requestVideoFrameCallback(updateVideo);
  16405. }
  16406. }
  16407. clone() {
  16408. return new this.constructor(this.image).copy(this);
  16409. }
  16410. update() {
  16411. const video = this.image;
  16412. const hasVideoFrameCallback = ('requestVideoFrameCallback' in video);
  16413. if (hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA) {
  16414. this.needsUpdate = true;
  16415. }
  16416. }
  16417. }
  16418. VideoTexture.prototype.isVideoTexture = true;
  16419. class CompressedTexture extends Texture {
  16420. constructor(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  16421. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  16422. this.image = {
  16423. width: width,
  16424. height: height
  16425. };
  16426. this.mipmaps = mipmaps; // no flipping for cube textures
  16427. // (also flipping doesn't work for compressed textures )
  16428. this.flipY = false; // can't generate mipmaps for compressed textures
  16429. // mips must be embedded in DDS files
  16430. this.generateMipmaps = false;
  16431. }
  16432. }
  16433. CompressedTexture.prototype.isCompressedTexture = true;
  16434. class CanvasTexture extends Texture {
  16435. constructor(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  16436. super(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  16437. this.needsUpdate = true;
  16438. }
  16439. }
  16440. CanvasTexture.prototype.isCanvasTexture = true;
  16441. class DepthTexture extends Texture {
  16442. constructor(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
  16443. format = format !== undefined ? format : DepthFormat;
  16444. if (format !== DepthFormat && format !== DepthStencilFormat) {
  16445. throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
  16446. }
  16447. if (type === undefined && format === DepthFormat) type = UnsignedShortType;
  16448. if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
  16449. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  16450. this.image = {
  16451. width: width,
  16452. height: height
  16453. };
  16454. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  16455. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  16456. this.flipY = false;
  16457. this.generateMipmaps = false;
  16458. }
  16459. }
  16460. DepthTexture.prototype.isDepthTexture = true;
  16461. class CircleGeometry extends BufferGeometry {
  16462. constructor(radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2) {
  16463. super();
  16464. this.type = 'CircleGeometry';
  16465. this.parameters = {
  16466. radius: radius,
  16467. segments: segments,
  16468. thetaStart: thetaStart,
  16469. thetaLength: thetaLength
  16470. };
  16471. segments = Math.max(3, segments); // buffers
  16472. const indices = [];
  16473. const vertices = [];
  16474. const normals = [];
  16475. const uvs = []; // helper variables
  16476. const vertex = new Vector3();
  16477. const uv = new Vector2(); // center point
  16478. vertices.push(0, 0, 0);
  16479. normals.push(0, 0, 1);
  16480. uvs.push(0.5, 0.5);
  16481. for (let s = 0, i = 3; s <= segments; s++, i += 3) {
  16482. const segment = thetaStart + s / segments * thetaLength; // vertex
  16483. vertex.x = radius * Math.cos(segment);
  16484. vertex.y = radius * Math.sin(segment);
  16485. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  16486. normals.push(0, 0, 1); // uvs
  16487. uv.x = (vertices[i] / radius + 1) / 2;
  16488. uv.y = (vertices[i + 1] / radius + 1) / 2;
  16489. uvs.push(uv.x, uv.y);
  16490. } // indices
  16491. for (let i = 1; i <= segments; i++) {
  16492. indices.push(i, i + 1, 0);
  16493. } // build geometry
  16494. this.setIndex(indices);
  16495. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  16496. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  16497. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  16498. }
  16499. }
  16500. class CylinderGeometry extends BufferGeometry {
  16501. constructor(radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  16502. super();
  16503. this.type = 'CylinderGeometry';
  16504. this.parameters = {
  16505. radiusTop: radiusTop,
  16506. radiusBottom: radiusBottom,
  16507. height: height,
  16508. radialSegments: radialSegments,
  16509. heightSegments: heightSegments,
  16510. openEnded: openEnded,
  16511. thetaStart: thetaStart,
  16512. thetaLength: thetaLength
  16513. };
  16514. const scope = this;
  16515. radialSegments = Math.floor(radialSegments);
  16516. heightSegments = Math.floor(heightSegments); // buffers
  16517. const indices = [];
  16518. const vertices = [];
  16519. const normals = [];
  16520. const uvs = []; // helper variables
  16521. let index = 0;
  16522. const indexArray = [];
  16523. const halfHeight = height / 2;
  16524. let groupStart = 0; // generate geometry
  16525. generateTorso();
  16526. if (openEnded === false) {
  16527. if (radiusTop > 0) generateCap(true);
  16528. if (radiusBottom > 0) generateCap(false);
  16529. } // build geometry
  16530. this.setIndex(indices);
  16531. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  16532. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  16533. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  16534. function generateTorso() {
  16535. const normal = new Vector3();
  16536. const vertex = new Vector3();
  16537. let groupCount = 0; // this will be used to calculate the normal
  16538. const slope = (radiusBottom - radiusTop) / height; // generate vertices, normals and uvs
  16539. for (let y = 0; y <= heightSegments; y++) {
  16540. const indexRow = [];
  16541. const v = y / heightSegments; // calculate the radius of the current row
  16542. const radius = v * (radiusBottom - radiusTop) + radiusTop;
  16543. for (let x = 0; x <= radialSegments; x++) {
  16544. const u = x / radialSegments;
  16545. const theta = u * thetaLength + thetaStart;
  16546. const sinTheta = Math.sin(theta);
  16547. const cosTheta = Math.cos(theta); // vertex
  16548. vertex.x = radius * sinTheta;
  16549. vertex.y = -v * height + halfHeight;
  16550. vertex.z = radius * cosTheta;
  16551. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  16552. normal.set(sinTheta, slope, cosTheta).normalize();
  16553. normals.push(normal.x, normal.y, normal.z); // uv
  16554. uvs.push(u, 1 - v); // save index of vertex in respective row
  16555. indexRow.push(index++);
  16556. } // now save vertices of the row in our index array
  16557. indexArray.push(indexRow);
  16558. } // generate indices
  16559. for (let x = 0; x < radialSegments; x++) {
  16560. for (let y = 0; y < heightSegments; y++) {
  16561. // we use the index array to access the correct indices
  16562. const a = indexArray[y][x];
  16563. const b = indexArray[y + 1][x];
  16564. const c = indexArray[y + 1][x + 1];
  16565. const d = indexArray[y][x + 1]; // faces
  16566. indices.push(a, b, d);
  16567. indices.push(b, c, d); // update group counter
  16568. groupCount += 6;
  16569. }
  16570. } // add a group to the geometry. this will ensure multi material support
  16571. scope.addGroup(groupStart, groupCount, 0); // calculate new start value for groups
  16572. groupStart += groupCount;
  16573. }
  16574. function generateCap(top) {
  16575. // save the index of the first center vertex
  16576. const centerIndexStart = index;
  16577. const uv = new Vector2();
  16578. const vertex = new Vector3();
  16579. let groupCount = 0;
  16580. const radius = top === true ? radiusTop : radiusBottom;
  16581. const sign = top === true ? 1 : -1; // first we generate the center vertex data of the cap.
  16582. // because the geometry needs one set of uvs per face,
  16583. // we must generate a center vertex per face/segment
  16584. for (let x = 1; x <= radialSegments; x++) {
  16585. // vertex
  16586. vertices.push(0, halfHeight * sign, 0); // normal
  16587. normals.push(0, sign, 0); // uv
  16588. uvs.push(0.5, 0.5); // increase index
  16589. index++;
  16590. } // save the index of the last center vertex
  16591. const centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvs
  16592. for (let x = 0; x <= radialSegments; x++) {
  16593. const u = x / radialSegments;
  16594. const theta = u * thetaLength + thetaStart;
  16595. const cosTheta = Math.cos(theta);
  16596. const sinTheta = Math.sin(theta); // vertex
  16597. vertex.x = radius * sinTheta;
  16598. vertex.y = halfHeight * sign;
  16599. vertex.z = radius * cosTheta;
  16600. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  16601. normals.push(0, sign, 0); // uv
  16602. uv.x = cosTheta * 0.5 + 0.5;
  16603. uv.y = sinTheta * 0.5 * sign + 0.5;
  16604. uvs.push(uv.x, uv.y); // increase index
  16605. index++;
  16606. } // generate indices
  16607. for (let x = 0; x < radialSegments; x++) {
  16608. const c = centerIndexStart + x;
  16609. const i = centerIndexEnd + x;
  16610. if (top === true) {
  16611. // face top
  16612. indices.push(i, i + 1, c);
  16613. } else {
  16614. // face bottom
  16615. indices.push(i + 1, i, c);
  16616. }
  16617. groupCount += 3;
  16618. } // add a group to the geometry. this will ensure multi material support
  16619. scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); // calculate new start value for groups
  16620. groupStart += groupCount;
  16621. }
  16622. }
  16623. }
  16624. class ConeGeometry extends CylinderGeometry {
  16625. constructor(radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  16626. super(0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  16627. this.type = 'ConeGeometry';
  16628. this.parameters = {
  16629. radius: radius,
  16630. height: height,
  16631. radialSegments: radialSegments,
  16632. heightSegments: heightSegments,
  16633. openEnded: openEnded,
  16634. thetaStart: thetaStart,
  16635. thetaLength: thetaLength
  16636. };
  16637. }
  16638. }
  16639. class PolyhedronGeometry extends BufferGeometry {
  16640. constructor(vertices, indices, radius = 1, detail = 0) {
  16641. super();
  16642. this.type = 'PolyhedronGeometry';
  16643. this.parameters = {
  16644. vertices: vertices,
  16645. indices: indices,
  16646. radius: radius,
  16647. detail: detail
  16648. }; // default buffer data
  16649. const vertexBuffer = [];
  16650. const uvBuffer = []; // the subdivision creates the vertex buffer data
  16651. subdivide(detail); // all vertices should lie on a conceptual sphere with a given radius
  16652. applyRadius(radius); // finally, create the uv data
  16653. generateUVs(); // build non-indexed geometry
  16654. this.setAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));
  16655. this.setAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));
  16656. this.setAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));
  16657. if (detail === 0) {
  16658. this.computeVertexNormals(); // flat normals
  16659. } else {
  16660. this.normalizeNormals(); // smooth normals
  16661. } // helper functions
  16662. function subdivide(detail) {
  16663. const a = new Vector3();
  16664. const b = new Vector3();
  16665. const c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail value
  16666. for (let i = 0; i < indices.length; i += 3) {
  16667. // get the vertices of the face
  16668. getVertexByIndex(indices[i + 0], a);
  16669. getVertexByIndex(indices[i + 1], b);
  16670. getVertexByIndex(indices[i + 2], c); // perform subdivision
  16671. subdivideFace(a, b, c, detail);
  16672. }
  16673. }
  16674. function subdivideFace(a, b, c, detail) {
  16675. const cols = detail + 1; // we use this multidimensional array as a data structure for creating the subdivision
  16676. const v = []; // construct all of the vertices for this subdivision
  16677. for (let i = 0; i <= cols; i++) {
  16678. v[i] = [];
  16679. const aj = a.clone().lerp(c, i / cols);
  16680. const bj = b.clone().lerp(c, i / cols);
  16681. const rows = cols - i;
  16682. for (let j = 0; j <= rows; j++) {
  16683. if (j === 0 && i === cols) {
  16684. v[i][j] = aj;
  16685. } else {
  16686. v[i][j] = aj.clone().lerp(bj, j / rows);
  16687. }
  16688. }
  16689. } // construct all of the faces
  16690. for (let i = 0; i < cols; i++) {
  16691. for (let j = 0; j < 2 * (cols - i) - 1; j++) {
  16692. const k = Math.floor(j / 2);
  16693. if (j % 2 === 0) {
  16694. pushVertex(v[i][k + 1]);
  16695. pushVertex(v[i + 1][k]);
  16696. pushVertex(v[i][k]);
  16697. } else {
  16698. pushVertex(v[i][k + 1]);
  16699. pushVertex(v[i + 1][k + 1]);
  16700. pushVertex(v[i + 1][k]);
  16701. }
  16702. }
  16703. }
  16704. }
  16705. function applyRadius(radius) {
  16706. const vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertex
  16707. for (let i = 0; i < vertexBuffer.length; i += 3) {
  16708. vertex.x = vertexBuffer[i + 0];
  16709. vertex.y = vertexBuffer[i + 1];
  16710. vertex.z = vertexBuffer[i + 2];
  16711. vertex.normalize().multiplyScalar(radius);
  16712. vertexBuffer[i + 0] = vertex.x;
  16713. vertexBuffer[i + 1] = vertex.y;
  16714. vertexBuffer[i + 2] = vertex.z;
  16715. }
  16716. }
  16717. function generateUVs() {
  16718. const vertex = new Vector3();
  16719. for (let i = 0; i < vertexBuffer.length; i += 3) {
  16720. vertex.x = vertexBuffer[i + 0];
  16721. vertex.y = vertexBuffer[i + 1];
  16722. vertex.z = vertexBuffer[i + 2];
  16723. const u = azimuth(vertex) / 2 / Math.PI + 0.5;
  16724. const v = inclination(vertex) / Math.PI + 0.5;
  16725. uvBuffer.push(u, 1 - v);
  16726. }
  16727. correctUVs();
  16728. correctSeam();
  16729. }
  16730. function correctSeam() {
  16731. // handle case when face straddles the seam, see #3269
  16732. for (let i = 0; i < uvBuffer.length; i += 6) {
  16733. // uv data of a single face
  16734. const x0 = uvBuffer[i + 0];
  16735. const x1 = uvBuffer[i + 2];
  16736. const x2 = uvBuffer[i + 4];
  16737. const max = Math.max(x0, x1, x2);
  16738. const min = Math.min(x0, x1, x2); // 0.9 is somewhat arbitrary
  16739. if (max > 0.9 && min < 0.1) {
  16740. if (x0 < 0.2) uvBuffer[i + 0] += 1;
  16741. if (x1 < 0.2) uvBuffer[i + 2] += 1;
  16742. if (x2 < 0.2) uvBuffer[i + 4] += 1;
  16743. }
  16744. }
  16745. }
  16746. function pushVertex(vertex) {
  16747. vertexBuffer.push(vertex.x, vertex.y, vertex.z);
  16748. }
  16749. function getVertexByIndex(index, vertex) {
  16750. const stride = index * 3;
  16751. vertex.x = vertices[stride + 0];
  16752. vertex.y = vertices[stride + 1];
  16753. vertex.z = vertices[stride + 2];
  16754. }
  16755. function correctUVs() {
  16756. const a = new Vector3();
  16757. const b = new Vector3();
  16758. const c = new Vector3();
  16759. const centroid = new Vector3();
  16760. const uvA = new Vector2();
  16761. const uvB = new Vector2();
  16762. const uvC = new Vector2();
  16763. for (let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {
  16764. a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);
  16765. b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);
  16766. c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);
  16767. uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);
  16768. uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);
  16769. uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);
  16770. centroid.copy(a).add(b).add(c).divideScalar(3);
  16771. const azi = azimuth(centroid);
  16772. correctUV(uvA, j + 0, a, azi);
  16773. correctUV(uvB, j + 2, b, azi);
  16774. correctUV(uvC, j + 4, c, azi);
  16775. }
  16776. }
  16777. function correctUV(uv, stride, vector, azimuth) {
  16778. if (azimuth < 0 && uv.x === 1) {
  16779. uvBuffer[stride] = uv.x - 1;
  16780. }
  16781. if (vector.x === 0 && vector.z === 0) {
  16782. uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
  16783. }
  16784. } // Angle around the Y axis, counter-clockwise when looking from above.
  16785. function azimuth(vector) {
  16786. return Math.atan2(vector.z, -vector.x);
  16787. } // Angle above the XZ plane.
  16788. function inclination(vector) {
  16789. return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
  16790. }
  16791. }
  16792. }
  16793. class DodecahedronGeometry extends PolyhedronGeometry {
  16794. constructor(radius = 1, detail = 0) {
  16795. const t = (1 + Math.sqrt(5)) / 2;
  16796. const r = 1 / t;
  16797. const vertices = [// (±1, ±1, ±1)
  16798. -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/φ, ±φ)
  16799. 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t, // (±1/φ, ±φ, 0)
  16800. -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0, // (±φ, 0, ±1/φ)
  16801. -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];
  16802. 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];
  16803. super(vertices, indices, radius, detail);
  16804. this.type = 'DodecahedronGeometry';
  16805. this.parameters = {
  16806. radius: radius,
  16807. detail: detail
  16808. };
  16809. }
  16810. }
  16811. const _v0 = new Vector3();
  16812. const _v1$1 = new Vector3();
  16813. const _normal = new Vector3();
  16814. const _triangle = new Triangle();
  16815. class EdgesGeometry extends BufferGeometry {
  16816. constructor(geometry, thresholdAngle) {
  16817. super();
  16818. this.type = 'EdgesGeometry';
  16819. this.parameters = {
  16820. thresholdAngle: thresholdAngle
  16821. };
  16822. thresholdAngle = thresholdAngle !== undefined ? thresholdAngle : 1;
  16823. if (geometry.isGeometry === true) {
  16824. console.error('THREE.EdgesGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16825. return;
  16826. }
  16827. const precisionPoints = 4;
  16828. const precision = Math.pow(10, precisionPoints);
  16829. const thresholdDot = Math.cos(DEG2RAD * thresholdAngle);
  16830. const indexAttr = geometry.getIndex();
  16831. const positionAttr = geometry.getAttribute('position');
  16832. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  16833. const indexArr = [0, 0, 0];
  16834. const vertKeys = ['a', 'b', 'c'];
  16835. const hashes = new Array(3);
  16836. const edgeData = {};
  16837. const vertices = [];
  16838. for (let i = 0; i < indexCount; i += 3) {
  16839. if (indexAttr) {
  16840. indexArr[0] = indexAttr.getX(i);
  16841. indexArr[1] = indexAttr.getX(i + 1);
  16842. indexArr[2] = indexAttr.getX(i + 2);
  16843. } else {
  16844. indexArr[0] = i;
  16845. indexArr[1] = i + 1;
  16846. indexArr[2] = i + 2;
  16847. }
  16848. const {
  16849. a,
  16850. b,
  16851. c
  16852. } = _triangle;
  16853. a.fromBufferAttribute(positionAttr, indexArr[0]);
  16854. b.fromBufferAttribute(positionAttr, indexArr[1]);
  16855. c.fromBufferAttribute(positionAttr, indexArr[2]);
  16856. _triangle.getNormal(_normal); // create hashes for the edge from the vertices
  16857. hashes[0] = `${Math.round(a.x * precision)},${Math.round(a.y * precision)},${Math.round(a.z * precision)}`;
  16858. hashes[1] = `${Math.round(b.x * precision)},${Math.round(b.y * precision)},${Math.round(b.z * precision)}`;
  16859. hashes[2] = `${Math.round(c.x * precision)},${Math.round(c.y * precision)},${Math.round(c.z * precision)}`; // skip degenerate triangles
  16860. if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) {
  16861. continue;
  16862. } // iterate over every edge
  16863. for (let j = 0; j < 3; j++) {
  16864. // get the first and next vertex making up the edge
  16865. const jNext = (j + 1) % 3;
  16866. const vecHash0 = hashes[j];
  16867. const vecHash1 = hashes[jNext];
  16868. const v0 = _triangle[vertKeys[j]];
  16869. const v1 = _triangle[vertKeys[jNext]];
  16870. const hash = `${vecHash0}_${vecHash1}`;
  16871. const reverseHash = `${vecHash1}_${vecHash0}`;
  16872. if (reverseHash in edgeData && edgeData[reverseHash]) {
  16873. // if we found a sibling edge add it into the vertex array if
  16874. // it meets the angle threshold and delete the edge from the map.
  16875. if (_normal.dot(edgeData[reverseHash].normal) <= thresholdDot) {
  16876. vertices.push(v0.x, v0.y, v0.z);
  16877. vertices.push(v1.x, v1.y, v1.z);
  16878. }
  16879. edgeData[reverseHash] = null;
  16880. } else if (!(hash in edgeData)) {
  16881. // if we've already got an edge here then skip adding a new one
  16882. edgeData[hash] = {
  16883. index0: indexArr[j],
  16884. index1: indexArr[jNext],
  16885. normal: _normal.clone()
  16886. };
  16887. }
  16888. }
  16889. } // iterate over all remaining, unmatched edges and add them to the vertex array
  16890. for (const key in edgeData) {
  16891. if (edgeData[key]) {
  16892. const {
  16893. index0,
  16894. index1
  16895. } = edgeData[key];
  16896. _v0.fromBufferAttribute(positionAttr, index0);
  16897. _v1$1.fromBufferAttribute(positionAttr, index1);
  16898. vertices.push(_v0.x, _v0.y, _v0.z);
  16899. vertices.push(_v1$1.x, _v1$1.y, _v1$1.z);
  16900. }
  16901. }
  16902. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  16903. }
  16904. }
  16905. /**
  16906. * Port from https://github.com/mapbox/earcut (v2.2.2)
  16907. */
  16908. const Earcut = {
  16909. triangulate: function (data, holeIndices, dim) {
  16910. dim = dim || 2;
  16911. const hasHoles = holeIndices && holeIndices.length;
  16912. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  16913. let outerNode = linkedList(data, 0, outerLen, dim, true);
  16914. const triangles = [];
  16915. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  16916. let minX, minY, maxX, maxY, x, y, invSize;
  16917. 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
  16918. if (data.length > 80 * dim) {
  16919. minX = maxX = data[0];
  16920. minY = maxY = data[1];
  16921. for (let i = dim; i < outerLen; i += dim) {
  16922. x = data[i];
  16923. y = data[i + 1];
  16924. if (x < minX) minX = x;
  16925. if (y < minY) minY = y;
  16926. if (x > maxX) maxX = x;
  16927. if (y > maxY) maxY = y;
  16928. } // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  16929. invSize = Math.max(maxX - minX, maxY - minY);
  16930. invSize = invSize !== 0 ? 1 / invSize : 0;
  16931. }
  16932. earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
  16933. return triangles;
  16934. }
  16935. }; // create a circular doubly linked list from polygon points in the specified winding order
  16936. function linkedList(data, start, end, dim, clockwise) {
  16937. let i, last;
  16938. if (clockwise === signedArea(data, start, end, dim) > 0) {
  16939. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  16940. } else {
  16941. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  16942. }
  16943. if (last && equals(last, last.next)) {
  16944. removeNode(last);
  16945. last = last.next;
  16946. }
  16947. return last;
  16948. } // eliminate colinear or duplicate points
  16949. function filterPoints(start, end) {
  16950. if (!start) return start;
  16951. if (!end) end = start;
  16952. let p = start,
  16953. again;
  16954. do {
  16955. again = false;
  16956. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  16957. removeNode(p);
  16958. p = end = p.prev;
  16959. if (p === p.next) break;
  16960. again = true;
  16961. } else {
  16962. p = p.next;
  16963. }
  16964. } while (again || p !== end);
  16965. return end;
  16966. } // main ear slicing loop which triangulates a polygon (given as a linked list)
  16967. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  16968. if (!ear) return; // interlink polygon nodes in z-order
  16969. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  16970. let stop = ear,
  16971. prev,
  16972. next; // iterate through ears, slicing them one by one
  16973. while (ear.prev !== ear.next) {
  16974. prev = ear.prev;
  16975. next = ear.next;
  16976. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  16977. // cut off the triangle
  16978. triangles.push(prev.i / dim);
  16979. triangles.push(ear.i / dim);
  16980. triangles.push(next.i / dim);
  16981. removeNode(ear); // skipping the next vertex leads to less sliver triangles
  16982. ear = next.next;
  16983. stop = next.next;
  16984. continue;
  16985. }
  16986. ear = next; // if we looped through the whole remaining polygon and can't find any more ears
  16987. if (ear === stop) {
  16988. // try filtering points and slicing again
  16989. if (!pass) {
  16990. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally
  16991. } else if (pass === 1) {
  16992. ear = cureLocalIntersections(filterPoints(ear), triangles, dim);
  16993. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two
  16994. } else if (pass === 2) {
  16995. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  16996. }
  16997. break;
  16998. }
  16999. }
  17000. } // check whether a polygon node forms a valid ear with adjacent nodes
  17001. function isEar(ear) {
  17002. const a = ear.prev,
  17003. b = ear,
  17004. c = ear.next;
  17005. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  17006. // now make sure we don't have other points inside the potential ear
  17007. let p = ear.next.next;
  17008. while (p !== ear.prev) {
  17009. 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;
  17010. p = p.next;
  17011. }
  17012. return true;
  17013. }
  17014. function isEarHashed(ear, minX, minY, invSize) {
  17015. const a = ear.prev,
  17016. b = ear,
  17017. c = ear.next;
  17018. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  17019. // triangle bbox; min & max are calculated like this for speed
  17020. const minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x,
  17021. minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y,
  17022. maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x,
  17023. 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;
  17024. const minZ = zOrder(minTX, minTY, minX, minY, invSize),
  17025. maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
  17026. let p = ear.prevZ,
  17027. n = ear.nextZ; // look for points inside the triangle in both directions
  17028. while (p && p.z >= minZ && n && n.z <= maxZ) {
  17029. 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;
  17030. p = p.prevZ;
  17031. 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;
  17032. n = n.nextZ;
  17033. } // look for remaining points in decreasing z-order
  17034. while (p && p.z >= minZ) {
  17035. 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;
  17036. p = p.prevZ;
  17037. } // look for remaining points in increasing z-order
  17038. while (n && n.z <= maxZ) {
  17039. 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;
  17040. n = n.nextZ;
  17041. }
  17042. return true;
  17043. } // go through all polygon nodes and cure small local self-intersections
  17044. function cureLocalIntersections(start, triangles, dim) {
  17045. let p = start;
  17046. do {
  17047. const a = p.prev,
  17048. b = p.next.next;
  17049. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  17050. triangles.push(a.i / dim);
  17051. triangles.push(p.i / dim);
  17052. triangles.push(b.i / dim); // remove two nodes involved
  17053. removeNode(p);
  17054. removeNode(p.next);
  17055. p = start = b;
  17056. }
  17057. p = p.next;
  17058. } while (p !== start);
  17059. return filterPoints(p);
  17060. } // try splitting polygon into two and triangulate them independently
  17061. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  17062. // look for a valid diagonal that divides the polygon into two
  17063. let a = start;
  17064. do {
  17065. let b = a.next.next;
  17066. while (b !== a.prev) {
  17067. if (a.i !== b.i && isValidDiagonal(a, b)) {
  17068. // split the polygon in two by the diagonal
  17069. let c = splitPolygon(a, b); // filter colinear points around the cuts
  17070. a = filterPoints(a, a.next);
  17071. c = filterPoints(c, c.next); // run earcut on each half
  17072. earcutLinked(a, triangles, dim, minX, minY, invSize);
  17073. earcutLinked(c, triangles, dim, minX, minY, invSize);
  17074. return;
  17075. }
  17076. b = b.next;
  17077. }
  17078. a = a.next;
  17079. } while (a !== start);
  17080. } // link every hole into the outer loop, producing a single-ring polygon without holes
  17081. function eliminateHoles(data, holeIndices, outerNode, dim) {
  17082. const queue = [];
  17083. let i, len, start, end, list;
  17084. for (i = 0, len = holeIndices.length; i < len; i++) {
  17085. start = holeIndices[i] * dim;
  17086. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  17087. list = linkedList(data, start, end, dim, false);
  17088. if (list === list.next) list.steiner = true;
  17089. queue.push(getLeftmost(list));
  17090. }
  17091. queue.sort(compareX); // process holes from left to right
  17092. for (i = 0; i < queue.length; i++) {
  17093. eliminateHole(queue[i], outerNode);
  17094. outerNode = filterPoints(outerNode, outerNode.next);
  17095. }
  17096. return outerNode;
  17097. }
  17098. function compareX(a, b) {
  17099. return a.x - b.x;
  17100. } // find a bridge between vertices that connects hole with an outer ring and and link it
  17101. function eliminateHole(hole, outerNode) {
  17102. outerNode = findHoleBridge(hole, outerNode);
  17103. if (outerNode) {
  17104. const b = splitPolygon(outerNode, hole); // filter collinear points around the cuts
  17105. filterPoints(outerNode, outerNode.next);
  17106. filterPoints(b, b.next);
  17107. }
  17108. } // David Eberly's algorithm for finding a bridge between hole and outer polygon
  17109. function findHoleBridge(hole, outerNode) {
  17110. let p = outerNode;
  17111. const hx = hole.x;
  17112. const hy = hole.y;
  17113. let qx = -Infinity,
  17114. m; // find a segment intersected by a ray from the hole's leftmost point to the left;
  17115. // segment's endpoint with lesser x will be potential connection point
  17116. do {
  17117. if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  17118. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  17119. if (x <= hx && x > qx) {
  17120. qx = x;
  17121. if (x === hx) {
  17122. if (hy === p.y) return p;
  17123. if (hy === p.next.y) return p.next;
  17124. }
  17125. m = p.x < p.next.x ? p : p.next;
  17126. }
  17127. }
  17128. p = p.next;
  17129. } while (p !== outerNode);
  17130. if (!m) return null;
  17131. if (hx === qx) return m; // hole touches outer segment; pick leftmost endpoint
  17132. // look for points inside the triangle of hole point, segment intersection and endpoint;
  17133. // if there are no points found, we have a valid connection;
  17134. // otherwise choose the point of the minimum angle with the ray as connection point
  17135. const stop = m,
  17136. mx = m.x,
  17137. my = m.y;
  17138. let tanMin = Infinity,
  17139. tan;
  17140. p = m;
  17141. do {
  17142. 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)) {
  17143. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  17144. if (locallyInside(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) {
  17145. m = p;
  17146. tanMin = tan;
  17147. }
  17148. }
  17149. p = p.next;
  17150. } while (p !== stop);
  17151. return m;
  17152. } // whether sector in vertex m contains sector in vertex p in the same coordinates
  17153. function sectorContainsSector(m, p) {
  17154. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  17155. } // interlink polygon nodes in z-order
  17156. function indexCurve(start, minX, minY, invSize) {
  17157. let p = start;
  17158. do {
  17159. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  17160. p.prevZ = p.prev;
  17161. p.nextZ = p.next;
  17162. p = p.next;
  17163. } while (p !== start);
  17164. p.prevZ.nextZ = null;
  17165. p.prevZ = null;
  17166. sortLinked(p);
  17167. } // Simon Tatham's linked list merge sort algorithm
  17168. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  17169. function sortLinked(list) {
  17170. let i,
  17171. p,
  17172. q,
  17173. e,
  17174. tail,
  17175. numMerges,
  17176. pSize,
  17177. qSize,
  17178. inSize = 1;
  17179. do {
  17180. p = list;
  17181. list = null;
  17182. tail = null;
  17183. numMerges = 0;
  17184. while (p) {
  17185. numMerges++;
  17186. q = p;
  17187. pSize = 0;
  17188. for (i = 0; i < inSize; i++) {
  17189. pSize++;
  17190. q = q.nextZ;
  17191. if (!q) break;
  17192. }
  17193. qSize = inSize;
  17194. while (pSize > 0 || qSize > 0 && q) {
  17195. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  17196. e = p;
  17197. p = p.nextZ;
  17198. pSize--;
  17199. } else {
  17200. e = q;
  17201. q = q.nextZ;
  17202. qSize--;
  17203. }
  17204. if (tail) tail.nextZ = e;else list = e;
  17205. e.prevZ = tail;
  17206. tail = e;
  17207. }
  17208. p = q;
  17209. }
  17210. tail.nextZ = null;
  17211. inSize *= 2;
  17212. } while (numMerges > 1);
  17213. return list;
  17214. } // z-order of a point given coords and inverse of the longer side of data bbox
  17215. function zOrder(x, y, minX, minY, invSize) {
  17216. // coords are transformed into non-negative 15-bit integer range
  17217. x = 32767 * (x - minX) * invSize;
  17218. y = 32767 * (y - minY) * invSize;
  17219. x = (x | x << 8) & 0x00FF00FF;
  17220. x = (x | x << 4) & 0x0F0F0F0F;
  17221. x = (x | x << 2) & 0x33333333;
  17222. x = (x | x << 1) & 0x55555555;
  17223. y = (y | y << 8) & 0x00FF00FF;
  17224. y = (y | y << 4) & 0x0F0F0F0F;
  17225. y = (y | y << 2) & 0x33333333;
  17226. y = (y | y << 1) & 0x55555555;
  17227. return x | y << 1;
  17228. } // find the leftmost node of a polygon ring
  17229. function getLeftmost(start) {
  17230. let p = start,
  17231. leftmost = start;
  17232. do {
  17233. if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
  17234. p = p.next;
  17235. } while (p !== start);
  17236. return leftmost;
  17237. } // check if a point lies within a convex triangle
  17238. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  17239. 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;
  17240. } // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  17241. function isValidDiagonal(a, b) {
  17242. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && ( // dones't intersect other edges
  17243. locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && ( // locally visible
  17244. area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  17245. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  17246. } // signed area of a triangle
  17247. function area(p, q, r) {
  17248. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  17249. } // check if two points are equal
  17250. function equals(p1, p2) {
  17251. return p1.x === p2.x && p1.y === p2.y;
  17252. } // check if two segments intersect
  17253. function intersects(p1, q1, p2, q2) {
  17254. const o1 = sign(area(p1, q1, p2));
  17255. const o2 = sign(area(p1, q1, q2));
  17256. const o3 = sign(area(p2, q2, p1));
  17257. const o4 = sign(area(p2, q2, q1));
  17258. if (o1 !== o2 && o3 !== o4) return true; // general case
  17259. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  17260. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  17261. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  17262. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  17263. return false;
  17264. } // for collinear points p, q, r, check if point q lies on segment pr
  17265. function onSegment(p, q, r) {
  17266. 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);
  17267. }
  17268. function sign(num) {
  17269. return num > 0 ? 1 : num < 0 ? -1 : 0;
  17270. } // check if a polygon diagonal intersects any polygon segments
  17271. function intersectsPolygon(a, b) {
  17272. let p = a;
  17273. do {
  17274. 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;
  17275. p = p.next;
  17276. } while (p !== a);
  17277. return false;
  17278. } // check if a polygon diagonal is locally inside the polygon
  17279. function locallyInside(a, b) {
  17280. 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;
  17281. } // check if the middle point of a polygon diagonal is inside the polygon
  17282. function middleInside(a, b) {
  17283. let p = a,
  17284. inside = false;
  17285. const px = (a.x + b.x) / 2,
  17286. py = (a.y + b.y) / 2;
  17287. do {
  17288. 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;
  17289. p = p.next;
  17290. } while (p !== a);
  17291. return inside;
  17292. } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  17293. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  17294. function splitPolygon(a, b) {
  17295. const a2 = new Node(a.i, a.x, a.y),
  17296. b2 = new Node(b.i, b.x, b.y),
  17297. an = a.next,
  17298. bp = b.prev;
  17299. a.next = b;
  17300. b.prev = a;
  17301. a2.next = an;
  17302. an.prev = a2;
  17303. b2.next = a2;
  17304. a2.prev = b2;
  17305. bp.next = b2;
  17306. b2.prev = bp;
  17307. return b2;
  17308. } // create a node and optionally link it with previous one (in a circular doubly linked list)
  17309. function insertNode(i, x, y, last) {
  17310. const p = new Node(i, x, y);
  17311. if (!last) {
  17312. p.prev = p;
  17313. p.next = p;
  17314. } else {
  17315. p.next = last.next;
  17316. p.prev = last;
  17317. last.next.prev = p;
  17318. last.next = p;
  17319. }
  17320. return p;
  17321. }
  17322. function removeNode(p) {
  17323. p.next.prev = p.prev;
  17324. p.prev.next = p.next;
  17325. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  17326. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  17327. }
  17328. function Node(i, x, y) {
  17329. // vertex index in coordinates array
  17330. this.i = i; // vertex coordinates
  17331. this.x = x;
  17332. this.y = y; // previous and next vertex nodes in a polygon ring
  17333. this.prev = null;
  17334. this.next = null; // z-order curve value
  17335. this.z = null; // previous and next nodes in z-order
  17336. this.prevZ = null;
  17337. this.nextZ = null; // indicates whether this is a steiner point
  17338. this.steiner = false;
  17339. }
  17340. function signedArea(data, start, end, dim) {
  17341. let sum = 0;
  17342. for (let i = start, j = end - dim; i < end; i += dim) {
  17343. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  17344. j = i;
  17345. }
  17346. return sum;
  17347. }
  17348. class ShapeUtils {
  17349. // calculate area of the contour polygon
  17350. static area(contour) {
  17351. const n = contour.length;
  17352. let a = 0.0;
  17353. for (let p = n - 1, q = 0; q < n; p = q++) {
  17354. a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
  17355. }
  17356. return a * 0.5;
  17357. }
  17358. static isClockWise(pts) {
  17359. return ShapeUtils.area(pts) < 0;
  17360. }
  17361. static triangulateShape(contour, holes) {
  17362. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  17363. const holeIndices = []; // array of hole indices
  17364. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  17365. removeDupEndPts(contour);
  17366. addContour(vertices, contour); //
  17367. let holeIndex = contour.length;
  17368. holes.forEach(removeDupEndPts);
  17369. for (let i = 0; i < holes.length; i++) {
  17370. holeIndices.push(holeIndex);
  17371. holeIndex += holes[i].length;
  17372. addContour(vertices, holes[i]);
  17373. } //
  17374. const triangles = Earcut.triangulate(vertices, holeIndices); //
  17375. for (let i = 0; i < triangles.length; i += 3) {
  17376. faces.push(triangles.slice(i, i + 3));
  17377. }
  17378. return faces;
  17379. }
  17380. }
  17381. function removeDupEndPts(points) {
  17382. const l = points.length;
  17383. if (l > 2 && points[l - 1].equals(points[0])) {
  17384. points.pop();
  17385. }
  17386. }
  17387. function addContour(vertices, contour) {
  17388. for (let i = 0; i < contour.length; i++) {
  17389. vertices.push(contour[i].x);
  17390. vertices.push(contour[i].y);
  17391. }
  17392. }
  17393. /**
  17394. * Creates extruded geometry from a path shape.
  17395. *
  17396. * parameters = {
  17397. *
  17398. * curveSegments: <int>, // number of points on the curves
  17399. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  17400. * depth: <float>, // Depth to extrude the shape
  17401. *
  17402. * bevelEnabled: <bool>, // turn on bevel
  17403. * bevelThickness: <float>, // how deep into the original shape bevel goes
  17404. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  17405. * bevelOffset: <float>, // how far from shape outline does bevel start
  17406. * bevelSegments: <int>, // number of bevel layers
  17407. *
  17408. * extrudePath: <THREE.Curve> // curve to extrude shape along
  17409. *
  17410. * UVGenerator: <Object> // object that provides UV generator functions
  17411. *
  17412. * }
  17413. */
  17414. class ExtrudeGeometry extends BufferGeometry {
  17415. constructor(shapes, options) {
  17416. super();
  17417. this.type = 'ExtrudeGeometry';
  17418. this.parameters = {
  17419. shapes: shapes,
  17420. options: options
  17421. };
  17422. shapes = Array.isArray(shapes) ? shapes : [shapes];
  17423. const scope = this;
  17424. const verticesArray = [];
  17425. const uvArray = [];
  17426. for (let i = 0, l = shapes.length; i < l; i++) {
  17427. const shape = shapes[i];
  17428. addShape(shape);
  17429. } // build geometry
  17430. this.setAttribute('position', new Float32BufferAttribute(verticesArray, 3));
  17431. this.setAttribute('uv', new Float32BufferAttribute(uvArray, 2));
  17432. this.computeVertexNormals(); // functions
  17433. function addShape(shape) {
  17434. const placeholder = []; // options
  17435. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  17436. const steps = options.steps !== undefined ? options.steps : 1;
  17437. let depth = options.depth !== undefined ? options.depth : 100;
  17438. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  17439. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  17440. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  17441. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  17442. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  17443. const extrudePath = options.extrudePath;
  17444. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; // deprecated options
  17445. if (options.amount !== undefined) {
  17446. console.warn('THREE.ExtrudeBufferGeometry: amount has been renamed to depth.');
  17447. depth = options.amount;
  17448. } //
  17449. let extrudePts,
  17450. extrudeByPath = false;
  17451. let splineTube, binormal, normal, position2;
  17452. if (extrudePath) {
  17453. extrudePts = extrudePath.getSpacedPoints(steps);
  17454. extrudeByPath = true;
  17455. bevelEnabled = false; // bevels not supported for path extrusion
  17456. // SETUP TNB variables
  17457. // TODO1 - have a .isClosed in spline?
  17458. splineTube = extrudePath.computeFrenetFrames(steps, false); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  17459. binormal = new Vector3();
  17460. normal = new Vector3();
  17461. position2 = new Vector3();
  17462. } // Safeguards if bevels are not enabled
  17463. if (!bevelEnabled) {
  17464. bevelSegments = 0;
  17465. bevelThickness = 0;
  17466. bevelSize = 0;
  17467. bevelOffset = 0;
  17468. } // Variables initialization
  17469. const shapePoints = shape.extractPoints(curveSegments);
  17470. let vertices = shapePoints.shape;
  17471. const holes = shapePoints.holes;
  17472. const reverse = !ShapeUtils.isClockWise(vertices);
  17473. if (reverse) {
  17474. vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  17475. for (let h = 0, hl = holes.length; h < hl; h++) {
  17476. const ahole = holes[h];
  17477. if (ShapeUtils.isClockWise(ahole)) {
  17478. holes[h] = ahole.reverse();
  17479. }
  17480. }
  17481. }
  17482. const faces = ShapeUtils.triangulateShape(vertices, holes);
  17483. /* Vertices */
  17484. const contour = vertices; // vertices has all points but contour has only points of circumference
  17485. for (let h = 0, hl = holes.length; h < hl; h++) {
  17486. const ahole = holes[h];
  17487. vertices = vertices.concat(ahole);
  17488. }
  17489. function scalePt2(pt, vec, size) {
  17490. if (!vec) console.error('THREE.ExtrudeGeometry: vec does not exist');
  17491. return vec.clone().multiplyScalar(size).add(pt);
  17492. }
  17493. const vlen = vertices.length,
  17494. flen = faces.length; // Find directions for point movement
  17495. function getBevelVec(inPt, inPrev, inNext) {
  17496. // computes for inPt the corresponding point inPt' on a new contour
  17497. // shifted by 1 unit (length of normalized vector) to the left
  17498. // if we walk along contour clockwise, this new contour is outside the old one
  17499. //
  17500. // inPt' is the intersection of the two lines parallel to the two
  17501. // adjacent edges of inPt at a distance of 1 unit on the left side.
  17502. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  17503. // good reading for geometry algorithms (here: line-line intersection)
  17504. // http://geomalgorithms.com/a05-_intersect-1.html
  17505. const v_prev_x = inPt.x - inPrev.x,
  17506. v_prev_y = inPt.y - inPrev.y;
  17507. const v_next_x = inNext.x - inPt.x,
  17508. v_next_y = inNext.y - inPt.y;
  17509. const v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; // check for collinear edges
  17510. const collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
  17511. if (Math.abs(collinear0) > Number.EPSILON) {
  17512. // not collinear
  17513. // length of vectors for normalizing
  17514. const v_prev_len = Math.sqrt(v_prev_lensq);
  17515. 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
  17516. const ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
  17517. const ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
  17518. const ptNextShift_x = inNext.x - v_next_y / v_next_len;
  17519. const ptNextShift_y = inNext.y + v_next_x / v_next_len; // scaling factor for v_prev to intersection point
  17520. 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
  17521. v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
  17522. v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; // Don't normalize!, otherwise sharp corners become ugly
  17523. // but prevent crazy spikes
  17524. const v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
  17525. if (v_trans_lensq <= 2) {
  17526. return new Vector2(v_trans_x, v_trans_y);
  17527. } else {
  17528. shrink_by = Math.sqrt(v_trans_lensq / 2);
  17529. }
  17530. } else {
  17531. // handle special case of collinear edges
  17532. let direction_eq = false; // assumes: opposite
  17533. if (v_prev_x > Number.EPSILON) {
  17534. if (v_next_x > Number.EPSILON) {
  17535. direction_eq = true;
  17536. }
  17537. } else {
  17538. if (v_prev_x < -Number.EPSILON) {
  17539. if (v_next_x < -Number.EPSILON) {
  17540. direction_eq = true;
  17541. }
  17542. } else {
  17543. if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
  17544. direction_eq = true;
  17545. }
  17546. }
  17547. }
  17548. if (direction_eq) {
  17549. // console.log("Warning: lines are a straight sequence");
  17550. v_trans_x = -v_prev_y;
  17551. v_trans_y = v_prev_x;
  17552. shrink_by = Math.sqrt(v_prev_lensq);
  17553. } else {
  17554. // console.log("Warning: lines are a straight spike");
  17555. v_trans_x = v_prev_x;
  17556. v_trans_y = v_prev_y;
  17557. shrink_by = Math.sqrt(v_prev_lensq / 2);
  17558. }
  17559. }
  17560. return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
  17561. }
  17562. const contourMovements = [];
  17563. for (let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  17564. if (j === il) j = 0;
  17565. if (k === il) k = 0; // (j)---(i)---(k)
  17566. // console.log('i,j,k', i, j , k)
  17567. contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]);
  17568. }
  17569. const holesMovements = [];
  17570. let oneHoleMovements,
  17571. verticesMovements = contourMovements.concat();
  17572. for (let h = 0, hl = holes.length; h < hl; h++) {
  17573. const ahole = holes[h];
  17574. oneHoleMovements = [];
  17575. for (let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  17576. if (j === il) j = 0;
  17577. if (k === il) k = 0; // (j)---(i)---(k)
  17578. oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]);
  17579. }
  17580. holesMovements.push(oneHoleMovements);
  17581. verticesMovements = verticesMovements.concat(oneHoleMovements);
  17582. } // Loop bevelSegments, 1 for the front, 1 for the back
  17583. for (let b = 0; b < bevelSegments; b++) {
  17584. //for ( b = bevelSegments; b > 0; b -- ) {
  17585. const t = b / bevelSegments;
  17586. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  17587. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  17588. for (let i = 0, il = contour.length; i < il; i++) {
  17589. const vert = scalePt2(contour[i], contourMovements[i], bs);
  17590. v(vert.x, vert.y, -z);
  17591. } // expand holes
  17592. for (let h = 0, hl = holes.length; h < hl; h++) {
  17593. const ahole = holes[h];
  17594. oneHoleMovements = holesMovements[h];
  17595. for (let i = 0, il = ahole.length; i < il; i++) {
  17596. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  17597. v(vert.x, vert.y, -z);
  17598. }
  17599. }
  17600. }
  17601. const bs = bevelSize + bevelOffset; // Back facing vertices
  17602. for (let i = 0; i < vlen; i++) {
  17603. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  17604. if (!extrudeByPath) {
  17605. v(vert.x, vert.y, 0);
  17606. } else {
  17607. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  17608. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  17609. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  17610. position2.copy(extrudePts[0]).add(normal).add(binormal);
  17611. v(position2.x, position2.y, position2.z);
  17612. }
  17613. } // Add stepped vertices...
  17614. // Including front facing vertices
  17615. for (let s = 1; s <= steps; s++) {
  17616. for (let i = 0; i < vlen; i++) {
  17617. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  17618. if (!extrudeByPath) {
  17619. v(vert.x, vert.y, depth / steps * s);
  17620. } else {
  17621. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  17622. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  17623. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  17624. position2.copy(extrudePts[s]).add(normal).add(binormal);
  17625. v(position2.x, position2.y, position2.z);
  17626. }
  17627. }
  17628. } // Add bevel segments planes
  17629. //for ( b = 1; b <= bevelSegments; b ++ ) {
  17630. for (let b = bevelSegments - 1; b >= 0; b--) {
  17631. const t = b / bevelSegments;
  17632. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  17633. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  17634. for (let i = 0, il = contour.length; i < il; i++) {
  17635. const vert = scalePt2(contour[i], contourMovements[i], bs);
  17636. v(vert.x, vert.y, depth + z);
  17637. } // expand holes
  17638. for (let h = 0, hl = holes.length; h < hl; h++) {
  17639. const ahole = holes[h];
  17640. oneHoleMovements = holesMovements[h];
  17641. for (let i = 0, il = ahole.length; i < il; i++) {
  17642. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  17643. if (!extrudeByPath) {
  17644. v(vert.x, vert.y, depth + z);
  17645. } else {
  17646. v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z);
  17647. }
  17648. }
  17649. }
  17650. }
  17651. /* Faces */
  17652. // Top and bottom faces
  17653. buildLidFaces(); // Sides faces
  17654. buildSideFaces(); ///// Internal functions
  17655. function buildLidFaces() {
  17656. const start = verticesArray.length / 3;
  17657. if (bevelEnabled) {
  17658. let layer = 0; // steps + 1
  17659. let offset = vlen * layer; // Bottom faces
  17660. for (let i = 0; i < flen; i++) {
  17661. const face = faces[i];
  17662. f3(face[2] + offset, face[1] + offset, face[0] + offset);
  17663. }
  17664. layer = steps + bevelSegments * 2;
  17665. offset = vlen * layer; // Top faces
  17666. for (let i = 0; i < flen; i++) {
  17667. const face = faces[i];
  17668. f3(face[0] + offset, face[1] + offset, face[2] + offset);
  17669. }
  17670. } else {
  17671. // Bottom faces
  17672. for (let i = 0; i < flen; i++) {
  17673. const face = faces[i];
  17674. f3(face[2], face[1], face[0]);
  17675. } // Top faces
  17676. for (let i = 0; i < flen; i++) {
  17677. const face = faces[i];
  17678. f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps);
  17679. }
  17680. }
  17681. scope.addGroup(start, verticesArray.length / 3 - start, 0);
  17682. } // Create faces for the z-sides of the shape
  17683. function buildSideFaces() {
  17684. const start = verticesArray.length / 3;
  17685. let layeroffset = 0;
  17686. sidewalls(contour, layeroffset);
  17687. layeroffset += contour.length;
  17688. for (let h = 0, hl = holes.length; h < hl; h++) {
  17689. const ahole = holes[h];
  17690. sidewalls(ahole, layeroffset); //, true
  17691. layeroffset += ahole.length;
  17692. }
  17693. scope.addGroup(start, verticesArray.length / 3 - start, 1);
  17694. }
  17695. function sidewalls(contour, layeroffset) {
  17696. let i = contour.length;
  17697. while (--i >= 0) {
  17698. const j = i;
  17699. let k = i - 1;
  17700. if (k < 0) k = contour.length - 1; //console.log('b', i,j, i-1, k,vertices.length);
  17701. for (let s = 0, sl = steps + bevelSegments * 2; s < sl; s++) {
  17702. const slen1 = vlen * s;
  17703. const slen2 = vlen * (s + 1);
  17704. const a = layeroffset + j + slen1,
  17705. b = layeroffset + k + slen1,
  17706. c = layeroffset + k + slen2,
  17707. d = layeroffset + j + slen2;
  17708. f4(a, b, c, d);
  17709. }
  17710. }
  17711. }
  17712. function v(x, y, z) {
  17713. placeholder.push(x);
  17714. placeholder.push(y);
  17715. placeholder.push(z);
  17716. }
  17717. function f3(a, b, c) {
  17718. addVertex(a);
  17719. addVertex(b);
  17720. addVertex(c);
  17721. const nextIndex = verticesArray.length / 3;
  17722. const uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  17723. addUV(uvs[0]);
  17724. addUV(uvs[1]);
  17725. addUV(uvs[2]);
  17726. }
  17727. function f4(a, b, c, d) {
  17728. addVertex(a);
  17729. addVertex(b);
  17730. addVertex(d);
  17731. addVertex(b);
  17732. addVertex(c);
  17733. addVertex(d);
  17734. const nextIndex = verticesArray.length / 3;
  17735. const uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  17736. addUV(uvs[0]);
  17737. addUV(uvs[1]);
  17738. addUV(uvs[3]);
  17739. addUV(uvs[1]);
  17740. addUV(uvs[2]);
  17741. addUV(uvs[3]);
  17742. }
  17743. function addVertex(index) {
  17744. verticesArray.push(placeholder[index * 3 + 0]);
  17745. verticesArray.push(placeholder[index * 3 + 1]);
  17746. verticesArray.push(placeholder[index * 3 + 2]);
  17747. }
  17748. function addUV(vector2) {
  17749. uvArray.push(vector2.x);
  17750. uvArray.push(vector2.y);
  17751. }
  17752. }
  17753. }
  17754. toJSON() {
  17755. const data = BufferGeometry.prototype.toJSON.call(this);
  17756. const shapes = this.parameters.shapes;
  17757. const options = this.parameters.options;
  17758. return toJSON$1(shapes, options, data);
  17759. }
  17760. }
  17761. const WorldUVGenerator = {
  17762. generateTopUV: function (geometry, vertices, indexA, indexB, indexC) {
  17763. const a_x = vertices[indexA * 3];
  17764. const a_y = vertices[indexA * 3 + 1];
  17765. const b_x = vertices[indexB * 3];
  17766. const b_y = vertices[indexB * 3 + 1];
  17767. const c_x = vertices[indexC * 3];
  17768. const c_y = vertices[indexC * 3 + 1];
  17769. return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];
  17770. },
  17771. generateSideWallUV: function (geometry, vertices, indexA, indexB, indexC, indexD) {
  17772. const a_x = vertices[indexA * 3];
  17773. const a_y = vertices[indexA * 3 + 1];
  17774. const a_z = vertices[indexA * 3 + 2];
  17775. const b_x = vertices[indexB * 3];
  17776. const b_y = vertices[indexB * 3 + 1];
  17777. const b_z = vertices[indexB * 3 + 2];
  17778. const c_x = vertices[indexC * 3];
  17779. const c_y = vertices[indexC * 3 + 1];
  17780. const c_z = vertices[indexC * 3 + 2];
  17781. const d_x = vertices[indexD * 3];
  17782. const d_y = vertices[indexD * 3 + 1];
  17783. const d_z = vertices[indexD * 3 + 2];
  17784. if (Math.abs(a_y - b_y) < 0.01) {
  17785. 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)];
  17786. } else {
  17787. 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)];
  17788. }
  17789. }
  17790. };
  17791. function toJSON$1(shapes, options, data) {
  17792. data.shapes = [];
  17793. if (Array.isArray(shapes)) {
  17794. for (let i = 0, l = shapes.length; i < l; i++) {
  17795. const shape = shapes[i];
  17796. data.shapes.push(shape.uuid);
  17797. }
  17798. } else {
  17799. data.shapes.push(shapes.uuid);
  17800. }
  17801. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  17802. return data;
  17803. }
  17804. class IcosahedronGeometry extends PolyhedronGeometry {
  17805. constructor(radius = 1, detail = 0) {
  17806. const t = (1 + Math.sqrt(5)) / 2;
  17807. 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];
  17808. 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];
  17809. super(vertices, indices, radius, detail);
  17810. this.type = 'IcosahedronGeometry';
  17811. this.parameters = {
  17812. radius: radius,
  17813. detail: detail
  17814. };
  17815. }
  17816. }
  17817. class LatheGeometry extends BufferGeometry {
  17818. constructor(points, segments = 12, phiStart = 0, phiLength = Math.PI * 2) {
  17819. super();
  17820. this.type = 'LatheGeometry';
  17821. this.parameters = {
  17822. points: points,
  17823. segments: segments,
  17824. phiStart: phiStart,
  17825. phiLength: phiLength
  17826. };
  17827. segments = Math.floor(segments); // clamp phiLength so it's in range of [ 0, 2PI ]
  17828. phiLength = clamp(phiLength, 0, Math.PI * 2); // buffers
  17829. const indices = [];
  17830. const vertices = [];
  17831. const uvs = []; // helper variables
  17832. const inverseSegments = 1.0 / segments;
  17833. const vertex = new Vector3();
  17834. const uv = new Vector2(); // generate vertices and uvs
  17835. for (let i = 0; i <= segments; i++) {
  17836. const phi = phiStart + i * inverseSegments * phiLength;
  17837. const sin = Math.sin(phi);
  17838. const cos = Math.cos(phi);
  17839. for (let j = 0; j <= points.length - 1; j++) {
  17840. // vertex
  17841. vertex.x = points[j].x * sin;
  17842. vertex.y = points[j].y;
  17843. vertex.z = points[j].x * cos;
  17844. vertices.push(vertex.x, vertex.y, vertex.z); // uv
  17845. uv.x = i / segments;
  17846. uv.y = j / (points.length - 1);
  17847. uvs.push(uv.x, uv.y);
  17848. }
  17849. } // indices
  17850. for (let i = 0; i < segments; i++) {
  17851. for (let j = 0; j < points.length - 1; j++) {
  17852. const base = j + i * points.length;
  17853. const a = base;
  17854. const b = base + points.length;
  17855. const c = base + points.length + 1;
  17856. const d = base + 1; // faces
  17857. indices.push(a, b, d);
  17858. indices.push(b, c, d);
  17859. }
  17860. } // build geometry
  17861. this.setIndex(indices);
  17862. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17863. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // generate normals
  17864. this.computeVertexNormals(); // if the geometry is closed, we need to average the normals along the seam.
  17865. // because the corresponding vertices are identical (but still have different UVs).
  17866. if (phiLength === Math.PI * 2) {
  17867. const normals = this.attributes.normal.array;
  17868. const n1 = new Vector3();
  17869. const n2 = new Vector3();
  17870. const n = new Vector3(); // this is the buffer offset for the last line of vertices
  17871. const base = segments * points.length * 3;
  17872. for (let i = 0, j = 0; i < points.length; i++, j += 3) {
  17873. // select the normal of the vertex in the first line
  17874. n1.x = normals[j + 0];
  17875. n1.y = normals[j + 1];
  17876. n1.z = normals[j + 2]; // select the normal of the vertex in the last line
  17877. n2.x = normals[base + j + 0];
  17878. n2.y = normals[base + j + 1];
  17879. n2.z = normals[base + j + 2]; // average normals
  17880. n.addVectors(n1, n2).normalize(); // assign the new values to both normals
  17881. normals[j + 0] = normals[base + j + 0] = n.x;
  17882. normals[j + 1] = normals[base + j + 1] = n.y;
  17883. normals[j + 2] = normals[base + j + 2] = n.z;
  17884. }
  17885. }
  17886. }
  17887. }
  17888. class OctahedronGeometry extends PolyhedronGeometry {
  17889. constructor(radius = 1, detail = 0) {
  17890. const vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
  17891. 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];
  17892. super(vertices, indices, radius, detail);
  17893. this.type = 'OctahedronGeometry';
  17894. this.parameters = {
  17895. radius: radius,
  17896. detail: detail
  17897. };
  17898. }
  17899. }
  17900. /**
  17901. * Parametric Surfaces Geometry
  17902. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  17903. */
  17904. class ParametricGeometry extends BufferGeometry {
  17905. constructor(func, slices, stacks) {
  17906. super();
  17907. this.type = 'ParametricGeometry';
  17908. this.parameters = {
  17909. func: func,
  17910. slices: slices,
  17911. stacks: stacks
  17912. }; // buffers
  17913. const indices = [];
  17914. const vertices = [];
  17915. const normals = [];
  17916. const uvs = [];
  17917. const EPS = 0.00001;
  17918. const normal = new Vector3();
  17919. const p0 = new Vector3(),
  17920. p1 = new Vector3();
  17921. const pu = new Vector3(),
  17922. pv = new Vector3();
  17923. if (func.length < 3) {
  17924. console.error('THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.');
  17925. } // generate vertices, normals and uvs
  17926. const sliceCount = slices + 1;
  17927. for (let i = 0; i <= stacks; i++) {
  17928. const v = i / stacks;
  17929. for (let j = 0; j <= slices; j++) {
  17930. const u = j / slices; // vertex
  17931. func(u, v, p0);
  17932. vertices.push(p0.x, p0.y, p0.z); // normal
  17933. // approximate tangent vectors via finite differences
  17934. if (u - EPS >= 0) {
  17935. func(u - EPS, v, p1);
  17936. pu.subVectors(p0, p1);
  17937. } else {
  17938. func(u + EPS, v, p1);
  17939. pu.subVectors(p1, p0);
  17940. }
  17941. if (v - EPS >= 0) {
  17942. func(u, v - EPS, p1);
  17943. pv.subVectors(p0, p1);
  17944. } else {
  17945. func(u, v + EPS, p1);
  17946. pv.subVectors(p1, p0);
  17947. } // cross product of tangent vectors returns surface normal
  17948. normal.crossVectors(pu, pv).normalize();
  17949. normals.push(normal.x, normal.y, normal.z); // uv
  17950. uvs.push(u, v);
  17951. }
  17952. } // generate indices
  17953. for (let i = 0; i < stacks; i++) {
  17954. for (let j = 0; j < slices; j++) {
  17955. const a = i * sliceCount + j;
  17956. const b = i * sliceCount + j + 1;
  17957. const c = (i + 1) * sliceCount + j + 1;
  17958. const d = (i + 1) * sliceCount + j; // faces one and two
  17959. indices.push(a, b, d);
  17960. indices.push(b, c, d);
  17961. }
  17962. } // build geometry
  17963. this.setIndex(indices);
  17964. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17965. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  17966. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  17967. }
  17968. }
  17969. class RingGeometry extends BufferGeometry {
  17970. constructor(innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2) {
  17971. super();
  17972. this.type = 'RingGeometry';
  17973. this.parameters = {
  17974. innerRadius: innerRadius,
  17975. outerRadius: outerRadius,
  17976. thetaSegments: thetaSegments,
  17977. phiSegments: phiSegments,
  17978. thetaStart: thetaStart,
  17979. thetaLength: thetaLength
  17980. };
  17981. thetaSegments = Math.max(3, thetaSegments);
  17982. phiSegments = Math.max(1, phiSegments); // buffers
  17983. const indices = [];
  17984. const vertices = [];
  17985. const normals = [];
  17986. const uvs = []; // some helper variables
  17987. let radius = innerRadius;
  17988. const radiusStep = (outerRadius - innerRadius) / phiSegments;
  17989. const vertex = new Vector3();
  17990. const uv = new Vector2(); // generate vertices, normals and uvs
  17991. for (let j = 0; j <= phiSegments; j++) {
  17992. for (let i = 0; i <= thetaSegments; i++) {
  17993. // values are generate from the inside of the ring to the outside
  17994. const segment = thetaStart + i / thetaSegments * thetaLength; // vertex
  17995. vertex.x = radius * Math.cos(segment);
  17996. vertex.y = radius * Math.sin(segment);
  17997. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  17998. normals.push(0, 0, 1); // uv
  17999. uv.x = (vertex.x / outerRadius + 1) / 2;
  18000. uv.y = (vertex.y / outerRadius + 1) / 2;
  18001. uvs.push(uv.x, uv.y);
  18002. } // increase the radius for next row of vertices
  18003. radius += radiusStep;
  18004. } // indices
  18005. for (let j = 0; j < phiSegments; j++) {
  18006. const thetaSegmentLevel = j * (thetaSegments + 1);
  18007. for (let i = 0; i < thetaSegments; i++) {
  18008. const segment = i + thetaSegmentLevel;
  18009. const a = segment;
  18010. const b = segment + thetaSegments + 1;
  18011. const c = segment + thetaSegments + 2;
  18012. const d = segment + 1; // faces
  18013. indices.push(a, b, d);
  18014. indices.push(b, c, d);
  18015. }
  18016. } // build geometry
  18017. this.setIndex(indices);
  18018. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18019. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  18020. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  18021. }
  18022. }
  18023. class ShapeGeometry extends BufferGeometry {
  18024. constructor(shapes, curveSegments = 12) {
  18025. super();
  18026. this.type = 'ShapeGeometry';
  18027. this.parameters = {
  18028. shapes: shapes,
  18029. curveSegments: curveSegments
  18030. }; // buffers
  18031. const indices = [];
  18032. const vertices = [];
  18033. const normals = [];
  18034. const uvs = []; // helper variables
  18035. let groupStart = 0;
  18036. let groupCount = 0; // allow single and array values for "shapes" parameter
  18037. if (Array.isArray(shapes) === false) {
  18038. addShape(shapes);
  18039. } else {
  18040. for (let i = 0; i < shapes.length; i++) {
  18041. addShape(shapes[i]);
  18042. this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
  18043. groupStart += groupCount;
  18044. groupCount = 0;
  18045. }
  18046. } // build geometry
  18047. this.setIndex(indices);
  18048. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18049. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  18050. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // helper functions
  18051. function addShape(shape) {
  18052. const indexOffset = vertices.length / 3;
  18053. const points = shape.extractPoints(curveSegments);
  18054. let shapeVertices = points.shape;
  18055. const shapeHoles = points.holes; // check direction of vertices
  18056. if (ShapeUtils.isClockWise(shapeVertices) === false) {
  18057. shapeVertices = shapeVertices.reverse();
  18058. }
  18059. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  18060. const shapeHole = shapeHoles[i];
  18061. if (ShapeUtils.isClockWise(shapeHole) === true) {
  18062. shapeHoles[i] = shapeHole.reverse();
  18063. }
  18064. }
  18065. const faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); // join vertices of inner and outer paths to a single array
  18066. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  18067. const shapeHole = shapeHoles[i];
  18068. shapeVertices = shapeVertices.concat(shapeHole);
  18069. } // vertices, normals, uvs
  18070. for (let i = 0, l = shapeVertices.length; i < l; i++) {
  18071. const vertex = shapeVertices[i];
  18072. vertices.push(vertex.x, vertex.y, 0);
  18073. normals.push(0, 0, 1);
  18074. uvs.push(vertex.x, vertex.y); // world uvs
  18075. } // incides
  18076. for (let i = 0, l = faces.length; i < l; i++) {
  18077. const face = faces[i];
  18078. const a = face[0] + indexOffset;
  18079. const b = face[1] + indexOffset;
  18080. const c = face[2] + indexOffset;
  18081. indices.push(a, b, c);
  18082. groupCount += 3;
  18083. }
  18084. }
  18085. }
  18086. toJSON() {
  18087. const data = BufferGeometry.prototype.toJSON.call(this);
  18088. const shapes = this.parameters.shapes;
  18089. return toJSON(shapes, data);
  18090. }
  18091. }
  18092. function toJSON(shapes, data) {
  18093. data.shapes = [];
  18094. if (Array.isArray(shapes)) {
  18095. for (let i = 0, l = shapes.length; i < l; i++) {
  18096. const shape = shapes[i];
  18097. data.shapes.push(shape.uuid);
  18098. }
  18099. } else {
  18100. data.shapes.push(shapes.uuid);
  18101. }
  18102. return data;
  18103. }
  18104. class SphereGeometry extends BufferGeometry {
  18105. constructor(radius = 1, widthSegments = 8, heightSegments = 6, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI) {
  18106. super();
  18107. this.type = 'SphereGeometry';
  18108. this.parameters = {
  18109. radius: radius,
  18110. widthSegments: widthSegments,
  18111. heightSegments: heightSegments,
  18112. phiStart: phiStart,
  18113. phiLength: phiLength,
  18114. thetaStart: thetaStart,
  18115. thetaLength: thetaLength
  18116. };
  18117. widthSegments = Math.max(3, Math.floor(widthSegments));
  18118. heightSegments = Math.max(2, Math.floor(heightSegments));
  18119. const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
  18120. let index = 0;
  18121. const grid = [];
  18122. const vertex = new Vector3();
  18123. const normal = new Vector3(); // buffers
  18124. const indices = [];
  18125. const vertices = [];
  18126. const normals = [];
  18127. const uvs = []; // generate vertices, normals and uvs
  18128. for (let iy = 0; iy <= heightSegments; iy++) {
  18129. const verticesRow = [];
  18130. const v = iy / heightSegments; // special case for the poles
  18131. let uOffset = 0;
  18132. if (iy == 0 && thetaStart == 0) {
  18133. uOffset = 0.5 / widthSegments;
  18134. } else if (iy == heightSegments && thetaEnd == Math.PI) {
  18135. uOffset = -0.5 / widthSegments;
  18136. }
  18137. for (let ix = 0; ix <= widthSegments; ix++) {
  18138. const u = ix / widthSegments; // vertex
  18139. vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  18140. vertex.y = radius * Math.cos(thetaStart + v * thetaLength);
  18141. vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  18142. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  18143. normal.copy(vertex).normalize();
  18144. normals.push(normal.x, normal.y, normal.z); // uv
  18145. uvs.push(u + uOffset, 1 - v);
  18146. verticesRow.push(index++);
  18147. }
  18148. grid.push(verticesRow);
  18149. } // indices
  18150. for (let iy = 0; iy < heightSegments; iy++) {
  18151. for (let ix = 0; ix < widthSegments; ix++) {
  18152. const a = grid[iy][ix + 1];
  18153. const b = grid[iy][ix];
  18154. const c = grid[iy + 1][ix];
  18155. const d = grid[iy + 1][ix + 1];
  18156. if (iy !== 0 || thetaStart > 0) indices.push(a, b, d);
  18157. if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
  18158. }
  18159. } // build geometry
  18160. this.setIndex(indices);
  18161. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18162. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  18163. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  18164. }
  18165. }
  18166. class TetrahedronGeometry extends PolyhedronGeometry {
  18167. constructor(radius = 1, detail = 0) {
  18168. const vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
  18169. const indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
  18170. super(vertices, indices, radius, detail);
  18171. this.type = 'TetrahedronGeometry';
  18172. this.parameters = {
  18173. radius: radius,
  18174. detail: detail
  18175. };
  18176. }
  18177. }
  18178. /**
  18179. * Text = 3D Text
  18180. *
  18181. * parameters = {
  18182. * font: <THREE.Font>, // font
  18183. *
  18184. * size: <float>, // size of the text
  18185. * height: <float>, // thickness to extrude text
  18186. * curveSegments: <int>, // number of points on the curves
  18187. *
  18188. * bevelEnabled: <bool>, // turn on bevel
  18189. * bevelThickness: <float>, // how deep into text bevel goes
  18190. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  18191. * bevelOffset: <float> // how far from text outline does bevel start
  18192. * }
  18193. */
  18194. class TextGeometry extends ExtrudeGeometry {
  18195. constructor(text, parameters = {}) {
  18196. const font = parameters.font;
  18197. if (!(font && font.isFont)) {
  18198. console.error('THREE.TextGeometry: font parameter is not an instance of THREE.Font.');
  18199. return new BufferGeometry();
  18200. }
  18201. const shapes = font.generateShapes(text, parameters.size); // translate parameters to ExtrudeGeometry API
  18202. parameters.depth = parameters.height !== undefined ? parameters.height : 50; // defaults
  18203. if (parameters.bevelThickness === undefined) parameters.bevelThickness = 10;
  18204. if (parameters.bevelSize === undefined) parameters.bevelSize = 8;
  18205. if (parameters.bevelEnabled === undefined) parameters.bevelEnabled = false;
  18206. super(shapes, parameters);
  18207. this.type = 'TextGeometry';
  18208. }
  18209. }
  18210. class TorusGeometry extends BufferGeometry {
  18211. constructor(radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2) {
  18212. super();
  18213. this.type = 'TorusGeometry';
  18214. this.parameters = {
  18215. radius: radius,
  18216. tube: tube,
  18217. radialSegments: radialSegments,
  18218. tubularSegments: tubularSegments,
  18219. arc: arc
  18220. };
  18221. radialSegments = Math.floor(radialSegments);
  18222. tubularSegments = Math.floor(tubularSegments); // buffers
  18223. const indices = [];
  18224. const vertices = [];
  18225. const normals = [];
  18226. const uvs = []; // helper variables
  18227. const center = new Vector3();
  18228. const vertex = new Vector3();
  18229. const normal = new Vector3(); // generate vertices, normals and uvs
  18230. for (let j = 0; j <= radialSegments; j++) {
  18231. for (let i = 0; i <= tubularSegments; i++) {
  18232. const u = i / tubularSegments * arc;
  18233. const v = j / radialSegments * Math.PI * 2; // vertex
  18234. vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
  18235. vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
  18236. vertex.z = tube * Math.sin(v);
  18237. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  18238. center.x = radius * Math.cos(u);
  18239. center.y = radius * Math.sin(u);
  18240. normal.subVectors(vertex, center).normalize();
  18241. normals.push(normal.x, normal.y, normal.z); // uv
  18242. uvs.push(i / tubularSegments);
  18243. uvs.push(j / radialSegments);
  18244. }
  18245. } // generate indices
  18246. for (let j = 1; j <= radialSegments; j++) {
  18247. for (let i = 1; i <= tubularSegments; i++) {
  18248. // indices
  18249. const a = (tubularSegments + 1) * j + i - 1;
  18250. const b = (tubularSegments + 1) * (j - 1) + i - 1;
  18251. const c = (tubularSegments + 1) * (j - 1) + i;
  18252. const d = (tubularSegments + 1) * j + i; // faces
  18253. indices.push(a, b, d);
  18254. indices.push(b, c, d);
  18255. }
  18256. } // build geometry
  18257. this.setIndex(indices);
  18258. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18259. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  18260. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  18261. }
  18262. }
  18263. class TorusKnotGeometry extends BufferGeometry {
  18264. constructor(radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3) {
  18265. super();
  18266. this.type = 'TorusKnotGeometry';
  18267. this.parameters = {
  18268. radius: radius,
  18269. tube: tube,
  18270. tubularSegments: tubularSegments,
  18271. radialSegments: radialSegments,
  18272. p: p,
  18273. q: q
  18274. };
  18275. tubularSegments = Math.floor(tubularSegments);
  18276. radialSegments = Math.floor(radialSegments); // buffers
  18277. const indices = [];
  18278. const vertices = [];
  18279. const normals = [];
  18280. const uvs = []; // helper variables
  18281. const vertex = new Vector3();
  18282. const normal = new Vector3();
  18283. const P1 = new Vector3();
  18284. const P2 = new Vector3();
  18285. const B = new Vector3();
  18286. const T = new Vector3();
  18287. const N = new Vector3(); // generate vertices, normals and uvs
  18288. for (let i = 0; i <= tubularSegments; ++i) {
  18289. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  18290. 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.
  18291. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  18292. calculatePositionOnCurve(u, p, q, radius, P1);
  18293. calculatePositionOnCurve(u + 0.01, p, q, radius, P2); // calculate orthonormal basis
  18294. T.subVectors(P2, P1);
  18295. N.addVectors(P2, P1);
  18296. B.crossVectors(T, N);
  18297. N.crossVectors(B, T); // normalize B, N. T can be ignored, we don't use it
  18298. B.normalize();
  18299. N.normalize();
  18300. for (let j = 0; j <= radialSegments; ++j) {
  18301. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  18302. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  18303. const v = j / radialSegments * Math.PI * 2;
  18304. const cx = -tube * Math.cos(v);
  18305. const cy = tube * Math.sin(v); // now calculate the final vertex position.
  18306. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  18307. vertex.x = P1.x + (cx * N.x + cy * B.x);
  18308. vertex.y = P1.y + (cx * N.y + cy * B.y);
  18309. vertex.z = P1.z + (cx * N.z + cy * B.z);
  18310. 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)
  18311. normal.subVectors(vertex, P1).normalize();
  18312. normals.push(normal.x, normal.y, normal.z); // uv
  18313. uvs.push(i / tubularSegments);
  18314. uvs.push(j / radialSegments);
  18315. }
  18316. } // generate indices
  18317. for (let j = 1; j <= tubularSegments; j++) {
  18318. for (let i = 1; i <= radialSegments; i++) {
  18319. // indices
  18320. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  18321. const b = (radialSegments + 1) * j + (i - 1);
  18322. const c = (radialSegments + 1) * j + i;
  18323. const d = (radialSegments + 1) * (j - 1) + i; // faces
  18324. indices.push(a, b, d);
  18325. indices.push(b, c, d);
  18326. }
  18327. } // build geometry
  18328. this.setIndex(indices);
  18329. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18330. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  18331. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // this function calculates the current position on the torus curve
  18332. function calculatePositionOnCurve(u, p, q, radius, position) {
  18333. const cu = Math.cos(u);
  18334. const su = Math.sin(u);
  18335. const quOverP = q / p * u;
  18336. const cs = Math.cos(quOverP);
  18337. position.x = radius * (2 + cs) * 0.5 * cu;
  18338. position.y = radius * (2 + cs) * su * 0.5;
  18339. position.z = radius * Math.sin(quOverP) * 0.5;
  18340. }
  18341. }
  18342. }
  18343. class TubeGeometry extends BufferGeometry {
  18344. constructor(path, tubularSegments = 64, radius = 1, radialSegments = 8, closed = false) {
  18345. super();
  18346. this.type = 'TubeGeometry';
  18347. this.parameters = {
  18348. path: path,
  18349. tubularSegments: tubularSegments,
  18350. radius: radius,
  18351. radialSegments: radialSegments,
  18352. closed: closed
  18353. };
  18354. const frames = path.computeFrenetFrames(tubularSegments, closed); // expose internals
  18355. this.tangents = frames.tangents;
  18356. this.normals = frames.normals;
  18357. this.binormals = frames.binormals; // helper variables
  18358. const vertex = new Vector3();
  18359. const normal = new Vector3();
  18360. const uv = new Vector2();
  18361. let P = new Vector3(); // buffer
  18362. const vertices = [];
  18363. const normals = [];
  18364. const uvs = [];
  18365. const indices = []; // create buffer data
  18366. generateBufferData(); // build geometry
  18367. this.setIndex(indices);
  18368. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18369. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  18370. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // functions
  18371. function generateBufferData() {
  18372. for (let i = 0; i < tubularSegments; i++) {
  18373. generateSegment(i);
  18374. } // if the geometry is not closed, generate the last row of vertices and normals
  18375. // at the regular position on the given path
  18376. //
  18377. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  18378. generateSegment(closed === false ? tubularSegments : 0); // uvs are generated in a separate function.
  18379. // this makes it easy compute correct values for closed geometries
  18380. generateUVs(); // finally create faces
  18381. generateIndices();
  18382. }
  18383. function generateSegment(i) {
  18384. // we use getPointAt to sample evenly distributed points from the given path
  18385. P = path.getPointAt(i / tubularSegments, P); // retrieve corresponding normal and binormal
  18386. const N = frames.normals[i];
  18387. const B = frames.binormals[i]; // generate normals and vertices for the current segment
  18388. for (let j = 0; j <= radialSegments; j++) {
  18389. const v = j / radialSegments * Math.PI * 2;
  18390. const sin = Math.sin(v);
  18391. const cos = -Math.cos(v); // normal
  18392. normal.x = cos * N.x + sin * B.x;
  18393. normal.y = cos * N.y + sin * B.y;
  18394. normal.z = cos * N.z + sin * B.z;
  18395. normal.normalize();
  18396. normals.push(normal.x, normal.y, normal.z); // vertex
  18397. vertex.x = P.x + radius * normal.x;
  18398. vertex.y = P.y + radius * normal.y;
  18399. vertex.z = P.z + radius * normal.z;
  18400. vertices.push(vertex.x, vertex.y, vertex.z);
  18401. }
  18402. }
  18403. function generateIndices() {
  18404. for (let j = 1; j <= tubularSegments; j++) {
  18405. for (let i = 1; i <= radialSegments; i++) {
  18406. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  18407. const b = (radialSegments + 1) * j + (i - 1);
  18408. const c = (radialSegments + 1) * j + i;
  18409. const d = (radialSegments + 1) * (j - 1) + i; // faces
  18410. indices.push(a, b, d);
  18411. indices.push(b, c, d);
  18412. }
  18413. }
  18414. }
  18415. function generateUVs() {
  18416. for (let i = 0; i <= tubularSegments; i++) {
  18417. for (let j = 0; j <= radialSegments; j++) {
  18418. uv.x = i / tubularSegments;
  18419. uv.y = j / radialSegments;
  18420. uvs.push(uv.x, uv.y);
  18421. }
  18422. }
  18423. }
  18424. }
  18425. toJSON() {
  18426. const data = BufferGeometry.prototype.toJSON.call(this);
  18427. data.path = this.parameters.path.toJSON();
  18428. return data;
  18429. }
  18430. }
  18431. class WireframeGeometry extends BufferGeometry {
  18432. constructor(geometry) {
  18433. super();
  18434. this.type = 'WireframeGeometry';
  18435. if (geometry.isGeometry === true) {
  18436. console.error('THREE.WireframeGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  18437. return;
  18438. } // buffer
  18439. const vertices = []; // helper variables
  18440. const edge = [0, 0],
  18441. edges = {};
  18442. const vertex = new Vector3();
  18443. if (geometry.index !== null) {
  18444. // indexed BufferGeometry
  18445. const position = geometry.attributes.position;
  18446. const indices = geometry.index;
  18447. let groups = geometry.groups;
  18448. if (groups.length === 0) {
  18449. groups = [{
  18450. start: 0,
  18451. count: indices.count,
  18452. materialIndex: 0
  18453. }];
  18454. } // create a data structure that contains all eges without duplicates
  18455. for (let o = 0, ol = groups.length; o < ol; ++o) {
  18456. const group = groups[o];
  18457. const start = group.start;
  18458. const count = group.count;
  18459. for (let i = start, l = start + count; i < l; i += 3) {
  18460. for (let j = 0; j < 3; j++) {
  18461. const edge1 = indices.getX(i + j);
  18462. const edge2 = indices.getX(i + (j + 1) % 3);
  18463. edge[0] = Math.min(edge1, edge2); // sorting prevents duplicates
  18464. edge[1] = Math.max(edge1, edge2);
  18465. const key = edge[0] + ',' + edge[1];
  18466. if (edges[key] === undefined) {
  18467. edges[key] = {
  18468. index1: edge[0],
  18469. index2: edge[1]
  18470. };
  18471. }
  18472. }
  18473. }
  18474. } // generate vertices
  18475. for (const key in edges) {
  18476. const e = edges[key];
  18477. vertex.fromBufferAttribute(position, e.index1);
  18478. vertices.push(vertex.x, vertex.y, vertex.z);
  18479. vertex.fromBufferAttribute(position, e.index2);
  18480. vertices.push(vertex.x, vertex.y, vertex.z);
  18481. }
  18482. } else {
  18483. // non-indexed BufferGeometry
  18484. const position = geometry.attributes.position;
  18485. for (let i = 0, l = position.count / 3; i < l; i++) {
  18486. for (let j = 0; j < 3; j++) {
  18487. // three edges per triangle, an edge is represented as (index1, index2)
  18488. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  18489. const index1 = 3 * i + j;
  18490. vertex.fromBufferAttribute(position, index1);
  18491. vertices.push(vertex.x, vertex.y, vertex.z);
  18492. const index2 = 3 * i + (j + 1) % 3;
  18493. vertex.fromBufferAttribute(position, index2);
  18494. vertices.push(vertex.x, vertex.y, vertex.z);
  18495. }
  18496. }
  18497. } // build geometry
  18498. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18499. }
  18500. }
  18501. var Geometries = /*#__PURE__*/Object.freeze({
  18502. __proto__: null,
  18503. BoxGeometry: BoxGeometry,
  18504. BoxBufferGeometry: BoxGeometry,
  18505. CircleGeometry: CircleGeometry,
  18506. CircleBufferGeometry: CircleGeometry,
  18507. ConeGeometry: ConeGeometry,
  18508. ConeBufferGeometry: ConeGeometry,
  18509. CylinderGeometry: CylinderGeometry,
  18510. CylinderBufferGeometry: CylinderGeometry,
  18511. DodecahedronGeometry: DodecahedronGeometry,
  18512. DodecahedronBufferGeometry: DodecahedronGeometry,
  18513. EdgesGeometry: EdgesGeometry,
  18514. ExtrudeGeometry: ExtrudeGeometry,
  18515. ExtrudeBufferGeometry: ExtrudeGeometry,
  18516. IcosahedronGeometry: IcosahedronGeometry,
  18517. IcosahedronBufferGeometry: IcosahedronGeometry,
  18518. LatheGeometry: LatheGeometry,
  18519. LatheBufferGeometry: LatheGeometry,
  18520. OctahedronGeometry: OctahedronGeometry,
  18521. OctahedronBufferGeometry: OctahedronGeometry,
  18522. ParametricGeometry: ParametricGeometry,
  18523. ParametricBufferGeometry: ParametricGeometry,
  18524. PlaneGeometry: PlaneGeometry,
  18525. PlaneBufferGeometry: PlaneGeometry,
  18526. PolyhedronGeometry: PolyhedronGeometry,
  18527. PolyhedronBufferGeometry: PolyhedronGeometry,
  18528. RingGeometry: RingGeometry,
  18529. RingBufferGeometry: RingGeometry,
  18530. ShapeGeometry: ShapeGeometry,
  18531. ShapeBufferGeometry: ShapeGeometry,
  18532. SphereGeometry: SphereGeometry,
  18533. SphereBufferGeometry: SphereGeometry,
  18534. TetrahedronGeometry: TetrahedronGeometry,
  18535. TetrahedronBufferGeometry: TetrahedronGeometry,
  18536. TextGeometry: TextGeometry,
  18537. TextBufferGeometry: TextGeometry,
  18538. TorusGeometry: TorusGeometry,
  18539. TorusBufferGeometry: TorusGeometry,
  18540. TorusKnotGeometry: TorusKnotGeometry,
  18541. TorusKnotBufferGeometry: TorusKnotGeometry,
  18542. TubeGeometry: TubeGeometry,
  18543. TubeBufferGeometry: TubeGeometry,
  18544. WireframeGeometry: WireframeGeometry
  18545. });
  18546. /**
  18547. * parameters = {
  18548. * color: <THREE.Color>
  18549. * }
  18550. */
  18551. class ShadowMaterial extends Material {
  18552. constructor(parameters) {
  18553. super();
  18554. this.type = 'ShadowMaterial';
  18555. this.color = new Color(0x000000);
  18556. this.transparent = true;
  18557. this.setValues(parameters);
  18558. }
  18559. copy(source) {
  18560. super.copy(source);
  18561. this.color.copy(source.color);
  18562. return this;
  18563. }
  18564. }
  18565. ShadowMaterial.prototype.isShadowMaterial = true;
  18566. class RawShaderMaterial extends ShaderMaterial {
  18567. constructor(parameters) {
  18568. super(parameters);
  18569. this.type = 'RawShaderMaterial';
  18570. }
  18571. }
  18572. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  18573. /**
  18574. * parameters = {
  18575. * color: <hex>,
  18576. * roughness: <float>,
  18577. * metalness: <float>,
  18578. * opacity: <float>,
  18579. *
  18580. * map: new THREE.Texture( <Image> ),
  18581. *
  18582. * lightMap: new THREE.Texture( <Image> ),
  18583. * lightMapIntensity: <float>
  18584. *
  18585. * aoMap: new THREE.Texture( <Image> ),
  18586. * aoMapIntensity: <float>
  18587. *
  18588. * emissive: <hex>,
  18589. * emissiveIntensity: <float>
  18590. * emissiveMap: new THREE.Texture( <Image> ),
  18591. *
  18592. * bumpMap: new THREE.Texture( <Image> ),
  18593. * bumpScale: <float>,
  18594. *
  18595. * normalMap: new THREE.Texture( <Image> ),
  18596. * normalMapType: THREE.TangentSpaceNormalMap,
  18597. * normalScale: <Vector2>,
  18598. *
  18599. * displacementMap: new THREE.Texture( <Image> ),
  18600. * displacementScale: <float>,
  18601. * displacementBias: <float>,
  18602. *
  18603. * roughnessMap: new THREE.Texture( <Image> ),
  18604. *
  18605. * metalnessMap: new THREE.Texture( <Image> ),
  18606. *
  18607. * alphaMap: new THREE.Texture( <Image> ),
  18608. *
  18609. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  18610. * envMapIntensity: <float>
  18611. *
  18612. * refractionRatio: <float>,
  18613. *
  18614. * wireframe: <boolean>,
  18615. * wireframeLinewidth: <float>,
  18616. *
  18617. * morphTargets: <bool>,
  18618. * morphNormals: <bool>,
  18619. *
  18620. * flatShading: <bool>
  18621. * }
  18622. */
  18623. class MeshStandardMaterial extends Material {
  18624. constructor(parameters) {
  18625. super();
  18626. this.defines = {
  18627. 'STANDARD': ''
  18628. };
  18629. this.type = 'MeshStandardMaterial';
  18630. this.color = new Color(0xffffff); // diffuse
  18631. this.roughness = 1.0;
  18632. this.metalness = 0.0;
  18633. this.map = null;
  18634. this.lightMap = null;
  18635. this.lightMapIntensity = 1.0;
  18636. this.aoMap = null;
  18637. this.aoMapIntensity = 1.0;
  18638. this.emissive = new Color(0x000000);
  18639. this.emissiveIntensity = 1.0;
  18640. this.emissiveMap = null;
  18641. this.bumpMap = null;
  18642. this.bumpScale = 1;
  18643. this.normalMap = null;
  18644. this.normalMapType = TangentSpaceNormalMap;
  18645. this.normalScale = new Vector2(1, 1);
  18646. this.displacementMap = null;
  18647. this.displacementScale = 1;
  18648. this.displacementBias = 0;
  18649. this.roughnessMap = null;
  18650. this.metalnessMap = null;
  18651. this.alphaMap = null;
  18652. this.envMap = null;
  18653. this.envMapIntensity = 1.0;
  18654. this.refractionRatio = 0.98;
  18655. this.wireframe = false;
  18656. this.wireframeLinewidth = 1;
  18657. this.wireframeLinecap = 'round';
  18658. this.wireframeLinejoin = 'round';
  18659. this.morphTargets = false;
  18660. this.morphNormals = false;
  18661. this.flatShading = false;
  18662. this.vertexTangents = false;
  18663. this.setValues(parameters);
  18664. }
  18665. copy(source) {
  18666. super.copy(source);
  18667. this.defines = {
  18668. 'STANDARD': ''
  18669. };
  18670. this.color.copy(source.color);
  18671. this.roughness = source.roughness;
  18672. this.metalness = source.metalness;
  18673. this.map = source.map;
  18674. this.lightMap = source.lightMap;
  18675. this.lightMapIntensity = source.lightMapIntensity;
  18676. this.aoMap = source.aoMap;
  18677. this.aoMapIntensity = source.aoMapIntensity;
  18678. this.emissive.copy(source.emissive);
  18679. this.emissiveMap = source.emissiveMap;
  18680. this.emissiveIntensity = source.emissiveIntensity;
  18681. this.bumpMap = source.bumpMap;
  18682. this.bumpScale = source.bumpScale;
  18683. this.normalMap = source.normalMap;
  18684. this.normalMapType = source.normalMapType;
  18685. this.normalScale.copy(source.normalScale);
  18686. this.displacementMap = source.displacementMap;
  18687. this.displacementScale = source.displacementScale;
  18688. this.displacementBias = source.displacementBias;
  18689. this.roughnessMap = source.roughnessMap;
  18690. this.metalnessMap = source.metalnessMap;
  18691. this.alphaMap = source.alphaMap;
  18692. this.envMap = source.envMap;
  18693. this.envMapIntensity = source.envMapIntensity;
  18694. this.refractionRatio = source.refractionRatio;
  18695. this.wireframe = source.wireframe;
  18696. this.wireframeLinewidth = source.wireframeLinewidth;
  18697. this.wireframeLinecap = source.wireframeLinecap;
  18698. this.wireframeLinejoin = source.wireframeLinejoin;
  18699. this.morphTargets = source.morphTargets;
  18700. this.morphNormals = source.morphNormals;
  18701. this.flatShading = source.flatShading;
  18702. this.vertexTangents = source.vertexTangents;
  18703. return this;
  18704. }
  18705. }
  18706. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  18707. /**
  18708. * parameters = {
  18709. * clearcoat: <float>,
  18710. * clearcoatMap: new THREE.Texture( <Image> ),
  18711. * clearcoatRoughness: <float>,
  18712. * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
  18713. * clearcoatNormalScale: <Vector2>,
  18714. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  18715. *
  18716. * reflectivity: <float>,
  18717. * ior: <float>,
  18718. *
  18719. * sheen: <Color>,
  18720. *
  18721. * transmission: <float>,
  18722. * transmissionMap: new THREE.Texture( <Image> )
  18723. * }
  18724. */
  18725. class MeshPhysicalMaterial extends MeshStandardMaterial {
  18726. constructor(parameters) {
  18727. super();
  18728. this.defines = {
  18729. 'STANDARD': '',
  18730. 'PHYSICAL': ''
  18731. };
  18732. this.type = 'MeshPhysicalMaterial';
  18733. this.clearcoat = 0.0;
  18734. this.clearcoatMap = null;
  18735. this.clearcoatRoughness = 0.0;
  18736. this.clearcoatRoughnessMap = null;
  18737. this.clearcoatNormalScale = new Vector2(1, 1);
  18738. this.clearcoatNormalMap = null;
  18739. this.reflectivity = 0.5; // maps to F0 = 0.04
  18740. Object.defineProperty(this, 'ior', {
  18741. get: function () {
  18742. return (1 + 0.4 * this.reflectivity) / (1 - 0.4 * this.reflectivity);
  18743. },
  18744. set: function (ior) {
  18745. this.reflectivity = clamp(2.5 * (ior - 1) / (ior + 1), 0, 1);
  18746. }
  18747. });
  18748. this.sheen = null; // null will disable sheen bsdf
  18749. this.transmission = 0.0;
  18750. this.transmissionMap = null;
  18751. this.setValues(parameters);
  18752. }
  18753. copy(source) {
  18754. super.copy(source);
  18755. this.defines = {
  18756. 'STANDARD': '',
  18757. 'PHYSICAL': ''
  18758. };
  18759. this.clearcoat = source.clearcoat;
  18760. this.clearcoatMap = source.clearcoatMap;
  18761. this.clearcoatRoughness = source.clearcoatRoughness;
  18762. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  18763. this.clearcoatNormalMap = source.clearcoatNormalMap;
  18764. this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
  18765. this.reflectivity = source.reflectivity;
  18766. if (source.sheen) {
  18767. this.sheen = (this.sheen || new Color()).copy(source.sheen);
  18768. } else {
  18769. this.sheen = null;
  18770. }
  18771. this.transmission = source.transmission;
  18772. this.transmissionMap = source.transmissionMap;
  18773. return this;
  18774. }
  18775. }
  18776. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  18777. /**
  18778. * parameters = {
  18779. * color: <hex>,
  18780. * specular: <hex>,
  18781. * shininess: <float>,
  18782. * opacity: <float>,
  18783. *
  18784. * map: new THREE.Texture( <Image> ),
  18785. *
  18786. * lightMap: new THREE.Texture( <Image> ),
  18787. * lightMapIntensity: <float>
  18788. *
  18789. * aoMap: new THREE.Texture( <Image> ),
  18790. * aoMapIntensity: <float>
  18791. *
  18792. * emissive: <hex>,
  18793. * emissiveIntensity: <float>
  18794. * emissiveMap: new THREE.Texture( <Image> ),
  18795. *
  18796. * bumpMap: new THREE.Texture( <Image> ),
  18797. * bumpScale: <float>,
  18798. *
  18799. * normalMap: new THREE.Texture( <Image> ),
  18800. * normalMapType: THREE.TangentSpaceNormalMap,
  18801. * normalScale: <Vector2>,
  18802. *
  18803. * displacementMap: new THREE.Texture( <Image> ),
  18804. * displacementScale: <float>,
  18805. * displacementBias: <float>,
  18806. *
  18807. * specularMap: new THREE.Texture( <Image> ),
  18808. *
  18809. * alphaMap: new THREE.Texture( <Image> ),
  18810. *
  18811. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  18812. * combine: THREE.MultiplyOperation,
  18813. * reflectivity: <float>,
  18814. * refractionRatio: <float>,
  18815. *
  18816. * wireframe: <boolean>,
  18817. * wireframeLinewidth: <float>,
  18818. *
  18819. * morphTargets: <bool>,
  18820. * morphNormals: <bool>,
  18821. *
  18822. * flatShading: <bool>
  18823. * }
  18824. */
  18825. class MeshPhongMaterial extends Material {
  18826. constructor(parameters) {
  18827. super();
  18828. this.type = 'MeshPhongMaterial';
  18829. this.color = new Color(0xffffff); // diffuse
  18830. this.specular = new Color(0x111111);
  18831. this.shininess = 30;
  18832. this.map = null;
  18833. this.lightMap = null;
  18834. this.lightMapIntensity = 1.0;
  18835. this.aoMap = null;
  18836. this.aoMapIntensity = 1.0;
  18837. this.emissive = new Color(0x000000);
  18838. this.emissiveIntensity = 1.0;
  18839. this.emissiveMap = null;
  18840. this.bumpMap = null;
  18841. this.bumpScale = 1;
  18842. this.normalMap = null;
  18843. this.normalMapType = TangentSpaceNormalMap;
  18844. this.normalScale = new Vector2(1, 1);
  18845. this.displacementMap = null;
  18846. this.displacementScale = 1;
  18847. this.displacementBias = 0;
  18848. this.specularMap = null;
  18849. this.alphaMap = null;
  18850. this.envMap = null;
  18851. this.combine = MultiplyOperation;
  18852. this.reflectivity = 1;
  18853. this.refractionRatio = 0.98;
  18854. this.wireframe = false;
  18855. this.wireframeLinewidth = 1;
  18856. this.wireframeLinecap = 'round';
  18857. this.wireframeLinejoin = 'round';
  18858. this.morphTargets = false;
  18859. this.morphNormals = false;
  18860. this.flatShading = false;
  18861. this.setValues(parameters);
  18862. }
  18863. copy(source) {
  18864. super.copy(source);
  18865. this.color.copy(source.color);
  18866. this.specular.copy(source.specular);
  18867. this.shininess = source.shininess;
  18868. this.map = source.map;
  18869. this.lightMap = source.lightMap;
  18870. this.lightMapIntensity = source.lightMapIntensity;
  18871. this.aoMap = source.aoMap;
  18872. this.aoMapIntensity = source.aoMapIntensity;
  18873. this.emissive.copy(source.emissive);
  18874. this.emissiveMap = source.emissiveMap;
  18875. this.emissiveIntensity = source.emissiveIntensity;
  18876. this.bumpMap = source.bumpMap;
  18877. this.bumpScale = source.bumpScale;
  18878. this.normalMap = source.normalMap;
  18879. this.normalMapType = source.normalMapType;
  18880. this.normalScale.copy(source.normalScale);
  18881. this.displacementMap = source.displacementMap;
  18882. this.displacementScale = source.displacementScale;
  18883. this.displacementBias = source.displacementBias;
  18884. this.specularMap = source.specularMap;
  18885. this.alphaMap = source.alphaMap;
  18886. this.envMap = source.envMap;
  18887. this.combine = source.combine;
  18888. this.reflectivity = source.reflectivity;
  18889. this.refractionRatio = source.refractionRatio;
  18890. this.wireframe = source.wireframe;
  18891. this.wireframeLinewidth = source.wireframeLinewidth;
  18892. this.wireframeLinecap = source.wireframeLinecap;
  18893. this.wireframeLinejoin = source.wireframeLinejoin;
  18894. this.morphTargets = source.morphTargets;
  18895. this.morphNormals = source.morphNormals;
  18896. this.flatShading = source.flatShading;
  18897. return this;
  18898. }
  18899. }
  18900. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  18901. /**
  18902. * parameters = {
  18903. * color: <hex>,
  18904. *
  18905. * map: new THREE.Texture( <Image> ),
  18906. * gradientMap: new THREE.Texture( <Image> ),
  18907. *
  18908. * lightMap: new THREE.Texture( <Image> ),
  18909. * lightMapIntensity: <float>
  18910. *
  18911. * aoMap: new THREE.Texture( <Image> ),
  18912. * aoMapIntensity: <float>
  18913. *
  18914. * emissive: <hex>,
  18915. * emissiveIntensity: <float>
  18916. * emissiveMap: new THREE.Texture( <Image> ),
  18917. *
  18918. * bumpMap: new THREE.Texture( <Image> ),
  18919. * bumpScale: <float>,
  18920. *
  18921. * normalMap: new THREE.Texture( <Image> ),
  18922. * normalMapType: THREE.TangentSpaceNormalMap,
  18923. * normalScale: <Vector2>,
  18924. *
  18925. * displacementMap: new THREE.Texture( <Image> ),
  18926. * displacementScale: <float>,
  18927. * displacementBias: <float>,
  18928. *
  18929. * alphaMap: new THREE.Texture( <Image> ),
  18930. *
  18931. * wireframe: <boolean>,
  18932. * wireframeLinewidth: <float>,
  18933. *
  18934. * morphTargets: <bool>,
  18935. * morphNormals: <bool>
  18936. * }
  18937. */
  18938. class MeshToonMaterial extends Material {
  18939. constructor(parameters) {
  18940. super();
  18941. this.defines = {
  18942. 'TOON': ''
  18943. };
  18944. this.type = 'MeshToonMaterial';
  18945. this.color = new Color(0xffffff);
  18946. this.map = null;
  18947. this.gradientMap = null;
  18948. this.lightMap = null;
  18949. this.lightMapIntensity = 1.0;
  18950. this.aoMap = null;
  18951. this.aoMapIntensity = 1.0;
  18952. this.emissive = new Color(0x000000);
  18953. this.emissiveIntensity = 1.0;
  18954. this.emissiveMap = null;
  18955. this.bumpMap = null;
  18956. this.bumpScale = 1;
  18957. this.normalMap = null;
  18958. this.normalMapType = TangentSpaceNormalMap;
  18959. this.normalScale = new Vector2(1, 1);
  18960. this.displacementMap = null;
  18961. this.displacementScale = 1;
  18962. this.displacementBias = 0;
  18963. this.alphaMap = null;
  18964. this.wireframe = false;
  18965. this.wireframeLinewidth = 1;
  18966. this.wireframeLinecap = 'round';
  18967. this.wireframeLinejoin = 'round';
  18968. this.morphTargets = false;
  18969. this.morphNormals = false;
  18970. this.setValues(parameters);
  18971. }
  18972. copy(source) {
  18973. super.copy(source);
  18974. this.color.copy(source.color);
  18975. this.map = source.map;
  18976. this.gradientMap = source.gradientMap;
  18977. this.lightMap = source.lightMap;
  18978. this.lightMapIntensity = source.lightMapIntensity;
  18979. this.aoMap = source.aoMap;
  18980. this.aoMapIntensity = source.aoMapIntensity;
  18981. this.emissive.copy(source.emissive);
  18982. this.emissiveMap = source.emissiveMap;
  18983. this.emissiveIntensity = source.emissiveIntensity;
  18984. this.bumpMap = source.bumpMap;
  18985. this.bumpScale = source.bumpScale;
  18986. this.normalMap = source.normalMap;
  18987. this.normalMapType = source.normalMapType;
  18988. this.normalScale.copy(source.normalScale);
  18989. this.displacementMap = source.displacementMap;
  18990. this.displacementScale = source.displacementScale;
  18991. this.displacementBias = source.displacementBias;
  18992. this.alphaMap = source.alphaMap;
  18993. this.wireframe = source.wireframe;
  18994. this.wireframeLinewidth = source.wireframeLinewidth;
  18995. this.wireframeLinecap = source.wireframeLinecap;
  18996. this.wireframeLinejoin = source.wireframeLinejoin;
  18997. this.morphTargets = source.morphTargets;
  18998. this.morphNormals = source.morphNormals;
  18999. return this;
  19000. }
  19001. }
  19002. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  19003. /**
  19004. * parameters = {
  19005. * opacity: <float>,
  19006. *
  19007. * bumpMap: new THREE.Texture( <Image> ),
  19008. * bumpScale: <float>,
  19009. *
  19010. * normalMap: new THREE.Texture( <Image> ),
  19011. * normalMapType: THREE.TangentSpaceNormalMap,
  19012. * normalScale: <Vector2>,
  19013. *
  19014. * displacementMap: new THREE.Texture( <Image> ),
  19015. * displacementScale: <float>,
  19016. * displacementBias: <float>,
  19017. *
  19018. * wireframe: <boolean>,
  19019. * wireframeLinewidth: <float>
  19020. *
  19021. * morphTargets: <bool>,
  19022. * morphNormals: <bool>,
  19023. *
  19024. * flatShading: <bool>
  19025. * }
  19026. */
  19027. class MeshNormalMaterial extends Material {
  19028. constructor(parameters) {
  19029. super();
  19030. this.type = 'MeshNormalMaterial';
  19031. this.bumpMap = null;
  19032. this.bumpScale = 1;
  19033. this.normalMap = null;
  19034. this.normalMapType = TangentSpaceNormalMap;
  19035. this.normalScale = new Vector2(1, 1);
  19036. this.displacementMap = null;
  19037. this.displacementScale = 1;
  19038. this.displacementBias = 0;
  19039. this.wireframe = false;
  19040. this.wireframeLinewidth = 1;
  19041. this.fog = false;
  19042. this.morphTargets = false;
  19043. this.morphNormals = false;
  19044. this.flatShading = false;
  19045. this.setValues(parameters);
  19046. }
  19047. copy(source) {
  19048. super.copy(source);
  19049. this.bumpMap = source.bumpMap;
  19050. this.bumpScale = source.bumpScale;
  19051. this.normalMap = source.normalMap;
  19052. this.normalMapType = source.normalMapType;
  19053. this.normalScale.copy(source.normalScale);
  19054. this.displacementMap = source.displacementMap;
  19055. this.displacementScale = source.displacementScale;
  19056. this.displacementBias = source.displacementBias;
  19057. this.wireframe = source.wireframe;
  19058. this.wireframeLinewidth = source.wireframeLinewidth;
  19059. this.morphTargets = source.morphTargets;
  19060. this.morphNormals = source.morphNormals;
  19061. this.flatShading = source.flatShading;
  19062. return this;
  19063. }
  19064. }
  19065. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  19066. /**
  19067. * parameters = {
  19068. * color: <hex>,
  19069. * opacity: <float>,
  19070. *
  19071. * map: new THREE.Texture( <Image> ),
  19072. *
  19073. * lightMap: new THREE.Texture( <Image> ),
  19074. * lightMapIntensity: <float>
  19075. *
  19076. * aoMap: new THREE.Texture( <Image> ),
  19077. * aoMapIntensity: <float>
  19078. *
  19079. * emissive: <hex>,
  19080. * emissiveIntensity: <float>
  19081. * emissiveMap: new THREE.Texture( <Image> ),
  19082. *
  19083. * specularMap: new THREE.Texture( <Image> ),
  19084. *
  19085. * alphaMap: new THREE.Texture( <Image> ),
  19086. *
  19087. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  19088. * combine: THREE.Multiply,
  19089. * reflectivity: <float>,
  19090. * refractionRatio: <float>,
  19091. *
  19092. * wireframe: <boolean>,
  19093. * wireframeLinewidth: <float>,
  19094. *
  19095. * morphTargets: <bool>,
  19096. * morphNormals: <bool>
  19097. * }
  19098. */
  19099. class MeshLambertMaterial extends Material {
  19100. constructor(parameters) {
  19101. super();
  19102. this.type = 'MeshLambertMaterial';
  19103. this.color = new Color(0xffffff); // diffuse
  19104. this.map = null;
  19105. this.lightMap = null;
  19106. this.lightMapIntensity = 1.0;
  19107. this.aoMap = null;
  19108. this.aoMapIntensity = 1.0;
  19109. this.emissive = new Color(0x000000);
  19110. this.emissiveIntensity = 1.0;
  19111. this.emissiveMap = null;
  19112. this.specularMap = null;
  19113. this.alphaMap = null;
  19114. this.envMap = null;
  19115. this.combine = MultiplyOperation;
  19116. this.reflectivity = 1;
  19117. this.refractionRatio = 0.98;
  19118. this.wireframe = false;
  19119. this.wireframeLinewidth = 1;
  19120. this.wireframeLinecap = 'round';
  19121. this.wireframeLinejoin = 'round';
  19122. this.morphTargets = false;
  19123. this.morphNormals = false;
  19124. this.setValues(parameters);
  19125. }
  19126. copy(source) {
  19127. super.copy(source);
  19128. this.color.copy(source.color);
  19129. this.map = source.map;
  19130. this.lightMap = source.lightMap;
  19131. this.lightMapIntensity = source.lightMapIntensity;
  19132. this.aoMap = source.aoMap;
  19133. this.aoMapIntensity = source.aoMapIntensity;
  19134. this.emissive.copy(source.emissive);
  19135. this.emissiveMap = source.emissiveMap;
  19136. this.emissiveIntensity = source.emissiveIntensity;
  19137. this.specularMap = source.specularMap;
  19138. this.alphaMap = source.alphaMap;
  19139. this.envMap = source.envMap;
  19140. this.combine = source.combine;
  19141. this.reflectivity = source.reflectivity;
  19142. this.refractionRatio = source.refractionRatio;
  19143. this.wireframe = source.wireframe;
  19144. this.wireframeLinewidth = source.wireframeLinewidth;
  19145. this.wireframeLinecap = source.wireframeLinecap;
  19146. this.wireframeLinejoin = source.wireframeLinejoin;
  19147. this.morphTargets = source.morphTargets;
  19148. this.morphNormals = source.morphNormals;
  19149. return this;
  19150. }
  19151. }
  19152. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  19153. /**
  19154. * parameters = {
  19155. * color: <hex>,
  19156. * opacity: <float>,
  19157. *
  19158. * matcap: new THREE.Texture( <Image> ),
  19159. *
  19160. * map: new THREE.Texture( <Image> ),
  19161. *
  19162. * bumpMap: new THREE.Texture( <Image> ),
  19163. * bumpScale: <float>,
  19164. *
  19165. * normalMap: new THREE.Texture( <Image> ),
  19166. * normalMapType: THREE.TangentSpaceNormalMap,
  19167. * normalScale: <Vector2>,
  19168. *
  19169. * displacementMap: new THREE.Texture( <Image> ),
  19170. * displacementScale: <float>,
  19171. * displacementBias: <float>,
  19172. *
  19173. * alphaMap: new THREE.Texture( <Image> ),
  19174. *
  19175. * morphTargets: <bool>,
  19176. * morphNormals: <bool>
  19177. *
  19178. * flatShading: <bool>
  19179. * }
  19180. */
  19181. class MeshMatcapMaterial extends Material {
  19182. constructor(parameters) {
  19183. super();
  19184. this.defines = {
  19185. 'MATCAP': ''
  19186. };
  19187. this.type = 'MeshMatcapMaterial';
  19188. this.color = new Color(0xffffff); // diffuse
  19189. this.matcap = null;
  19190. this.map = null;
  19191. this.bumpMap = null;
  19192. this.bumpScale = 1;
  19193. this.normalMap = null;
  19194. this.normalMapType = TangentSpaceNormalMap;
  19195. this.normalScale = new Vector2(1, 1);
  19196. this.displacementMap = null;
  19197. this.displacementScale = 1;
  19198. this.displacementBias = 0;
  19199. this.alphaMap = null;
  19200. this.morphTargets = false;
  19201. this.morphNormals = false;
  19202. this.flatShading = false;
  19203. this.setValues(parameters);
  19204. }
  19205. copy(source) {
  19206. super.copy(source);
  19207. this.defines = {
  19208. 'MATCAP': ''
  19209. };
  19210. this.color.copy(source.color);
  19211. this.matcap = source.matcap;
  19212. this.map = source.map;
  19213. this.bumpMap = source.bumpMap;
  19214. this.bumpScale = source.bumpScale;
  19215. this.normalMap = source.normalMap;
  19216. this.normalMapType = source.normalMapType;
  19217. this.normalScale.copy(source.normalScale);
  19218. this.displacementMap = source.displacementMap;
  19219. this.displacementScale = source.displacementScale;
  19220. this.displacementBias = source.displacementBias;
  19221. this.alphaMap = source.alphaMap;
  19222. this.morphTargets = source.morphTargets;
  19223. this.morphNormals = source.morphNormals;
  19224. this.flatShading = source.flatShading;
  19225. return this;
  19226. }
  19227. }
  19228. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  19229. /**
  19230. * parameters = {
  19231. * color: <hex>,
  19232. * opacity: <float>,
  19233. *
  19234. * linewidth: <float>,
  19235. *
  19236. * scale: <float>,
  19237. * dashSize: <float>,
  19238. * gapSize: <float>
  19239. * }
  19240. */
  19241. class LineDashedMaterial extends LineBasicMaterial {
  19242. constructor(parameters) {
  19243. super();
  19244. this.type = 'LineDashedMaterial';
  19245. this.scale = 1;
  19246. this.dashSize = 3;
  19247. this.gapSize = 1;
  19248. this.setValues(parameters);
  19249. }
  19250. copy(source) {
  19251. super.copy(source);
  19252. this.scale = source.scale;
  19253. this.dashSize = source.dashSize;
  19254. this.gapSize = source.gapSize;
  19255. return this;
  19256. }
  19257. }
  19258. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  19259. var Materials = /*#__PURE__*/Object.freeze({
  19260. __proto__: null,
  19261. ShadowMaterial: ShadowMaterial,
  19262. SpriteMaterial: SpriteMaterial,
  19263. RawShaderMaterial: RawShaderMaterial,
  19264. ShaderMaterial: ShaderMaterial,
  19265. PointsMaterial: PointsMaterial,
  19266. MeshPhysicalMaterial: MeshPhysicalMaterial,
  19267. MeshStandardMaterial: MeshStandardMaterial,
  19268. MeshPhongMaterial: MeshPhongMaterial,
  19269. MeshToonMaterial: MeshToonMaterial,
  19270. MeshNormalMaterial: MeshNormalMaterial,
  19271. MeshLambertMaterial: MeshLambertMaterial,
  19272. MeshDepthMaterial: MeshDepthMaterial,
  19273. MeshDistanceMaterial: MeshDistanceMaterial,
  19274. MeshBasicMaterial: MeshBasicMaterial,
  19275. MeshMatcapMaterial: MeshMatcapMaterial,
  19276. LineDashedMaterial: LineDashedMaterial,
  19277. LineBasicMaterial: LineBasicMaterial,
  19278. Material: Material
  19279. });
  19280. const AnimationUtils = {
  19281. // same as Array.prototype.slice, but also works on typed arrays
  19282. arraySlice: function (array, from, to) {
  19283. if (AnimationUtils.isTypedArray(array)) {
  19284. // in ios9 array.subarray(from, undefined) will return empty array
  19285. // but array.subarray(from) or array.subarray(from, len) is correct
  19286. return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
  19287. }
  19288. return array.slice(from, to);
  19289. },
  19290. // converts an array to a specific type
  19291. convertArray: function (array, type, forceClone) {
  19292. if (!array || // let 'undefined' and 'null' pass
  19293. !forceClone && array.constructor === type) return array;
  19294. if (typeof type.BYTES_PER_ELEMENT === 'number') {
  19295. return new type(array); // create typed array
  19296. }
  19297. return Array.prototype.slice.call(array); // create Array
  19298. },
  19299. isTypedArray: function (object) {
  19300. return ArrayBuffer.isView(object) && !(object instanceof DataView);
  19301. },
  19302. // returns an array by which times and values can be sorted
  19303. getKeyframeOrder: function (times) {
  19304. function compareTime(i, j) {
  19305. return times[i] - times[j];
  19306. }
  19307. const n = times.length;
  19308. const result = new Array(n);
  19309. for (let i = 0; i !== n; ++i) result[i] = i;
  19310. result.sort(compareTime);
  19311. return result;
  19312. },
  19313. // uses the array previously returned by 'getKeyframeOrder' to sort data
  19314. sortedArray: function (values, stride, order) {
  19315. const nValues = values.length;
  19316. const result = new values.constructor(nValues);
  19317. for (let i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {
  19318. const srcOffset = order[i] * stride;
  19319. for (let j = 0; j !== stride; ++j) {
  19320. result[dstOffset++] = values[srcOffset + j];
  19321. }
  19322. }
  19323. return result;
  19324. },
  19325. // function for parsing AOS keyframe formats
  19326. flattenJSON: function (jsonKeys, times, values, valuePropertyName) {
  19327. let i = 1,
  19328. key = jsonKeys[0];
  19329. while (key !== undefined && key[valuePropertyName] === undefined) {
  19330. key = jsonKeys[i++];
  19331. }
  19332. if (key === undefined) return; // no data
  19333. let value = key[valuePropertyName];
  19334. if (value === undefined) return; // no data
  19335. if (Array.isArray(value)) {
  19336. do {
  19337. value = key[valuePropertyName];
  19338. if (value !== undefined) {
  19339. times.push(key.time);
  19340. values.push.apply(values, value); // push all elements
  19341. }
  19342. key = jsonKeys[i++];
  19343. } while (key !== undefined);
  19344. } else if (value.toArray !== undefined) {
  19345. // ...assume THREE.Math-ish
  19346. do {
  19347. value = key[valuePropertyName];
  19348. if (value !== undefined) {
  19349. times.push(key.time);
  19350. value.toArray(values, values.length);
  19351. }
  19352. key = jsonKeys[i++];
  19353. } while (key !== undefined);
  19354. } else {
  19355. // otherwise push as-is
  19356. do {
  19357. value = key[valuePropertyName];
  19358. if (value !== undefined) {
  19359. times.push(key.time);
  19360. values.push(value);
  19361. }
  19362. key = jsonKeys[i++];
  19363. } while (key !== undefined);
  19364. }
  19365. },
  19366. subclip: function (sourceClip, name, startFrame, endFrame, fps = 30) {
  19367. const clip = sourceClip.clone();
  19368. clip.name = name;
  19369. const tracks = [];
  19370. for (let i = 0; i < clip.tracks.length; ++i) {
  19371. const track = clip.tracks[i];
  19372. const valueSize = track.getValueSize();
  19373. const times = [];
  19374. const values = [];
  19375. for (let j = 0; j < track.times.length; ++j) {
  19376. const frame = track.times[j] * fps;
  19377. if (frame < startFrame || frame >= endFrame) continue;
  19378. times.push(track.times[j]);
  19379. for (let k = 0; k < valueSize; ++k) {
  19380. values.push(track.values[j * valueSize + k]);
  19381. }
  19382. }
  19383. if (times.length === 0) continue;
  19384. track.times = AnimationUtils.convertArray(times, track.times.constructor);
  19385. track.values = AnimationUtils.convertArray(values, track.values.constructor);
  19386. tracks.push(track);
  19387. }
  19388. clip.tracks = tracks; // find minimum .times value across all tracks in the trimmed clip
  19389. let minStartTime = Infinity;
  19390. for (let i = 0; i < clip.tracks.length; ++i) {
  19391. if (minStartTime > clip.tracks[i].times[0]) {
  19392. minStartTime = clip.tracks[i].times[0];
  19393. }
  19394. } // shift all tracks such that clip begins at t=0
  19395. for (let i = 0; i < clip.tracks.length; ++i) {
  19396. clip.tracks[i].shift(-1 * minStartTime);
  19397. }
  19398. clip.resetDuration();
  19399. return clip;
  19400. },
  19401. makeClipAdditive: function (targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30) {
  19402. if (fps <= 0) fps = 30;
  19403. const numTracks = referenceClip.tracks.length;
  19404. const referenceTime = referenceFrame / fps; // Make each track's values relative to the values at the reference frame
  19405. for (let i = 0; i < numTracks; ++i) {
  19406. const referenceTrack = referenceClip.tracks[i];
  19407. const referenceTrackType = referenceTrack.ValueTypeName; // Skip this track if it's non-numeric
  19408. if (referenceTrackType === 'bool' || referenceTrackType === 'string') continue; // Find the track in the target clip whose name and type matches the reference track
  19409. const targetTrack = targetClip.tracks.find(function (track) {
  19410. return track.name === referenceTrack.name && track.ValueTypeName === referenceTrackType;
  19411. });
  19412. if (targetTrack === undefined) continue;
  19413. let referenceOffset = 0;
  19414. const referenceValueSize = referenceTrack.getValueSize();
  19415. if (referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  19416. referenceOffset = referenceValueSize / 3;
  19417. }
  19418. let targetOffset = 0;
  19419. const targetValueSize = targetTrack.getValueSize();
  19420. if (targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  19421. targetOffset = targetValueSize / 3;
  19422. }
  19423. const lastIndex = referenceTrack.times.length - 1;
  19424. let referenceValue; // Find the value to subtract out of the track
  19425. if (referenceTime <= referenceTrack.times[0]) {
  19426. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  19427. const startIndex = referenceOffset;
  19428. const endIndex = referenceValueSize - referenceOffset;
  19429. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
  19430. } else if (referenceTime >= referenceTrack.times[lastIndex]) {
  19431. // Reference frame is after the last keyframe, so just use the last keyframe
  19432. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  19433. const endIndex = startIndex + referenceValueSize - referenceOffset;
  19434. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
  19435. } else {
  19436. // Interpolate to the reference value
  19437. const interpolant = referenceTrack.createInterpolant();
  19438. const startIndex = referenceOffset;
  19439. const endIndex = referenceValueSize - referenceOffset;
  19440. interpolant.evaluate(referenceTime);
  19441. referenceValue = AnimationUtils.arraySlice(interpolant.resultBuffer, startIndex, endIndex);
  19442. } // Conjugate the quaternion
  19443. if (referenceTrackType === 'quaternion') {
  19444. const referenceQuat = new Quaternion().fromArray(referenceValue).normalize().conjugate();
  19445. referenceQuat.toArray(referenceValue);
  19446. } // Subtract the reference value from all of the track values
  19447. const numTimes = targetTrack.times.length;
  19448. for (let j = 0; j < numTimes; ++j) {
  19449. const valueStart = j * targetValueSize + targetOffset;
  19450. if (referenceTrackType === 'quaternion') {
  19451. // Multiply the conjugate for quaternion track types
  19452. Quaternion.multiplyQuaternionsFlat(targetTrack.values, valueStart, referenceValue, 0, targetTrack.values, valueStart);
  19453. } else {
  19454. const valueEnd = targetValueSize - targetOffset * 2; // Subtract each value for all other numeric track types
  19455. for (let k = 0; k < valueEnd; ++k) {
  19456. targetTrack.values[valueStart + k] -= referenceValue[k];
  19457. }
  19458. }
  19459. }
  19460. }
  19461. targetClip.blendMode = AdditiveAnimationBlendMode;
  19462. return targetClip;
  19463. }
  19464. };
  19465. /**
  19466. * Abstract base class of interpolants over parametric samples.
  19467. *
  19468. * The parameter domain is one dimensional, typically the time or a path
  19469. * along a curve defined by the data.
  19470. *
  19471. * The sample values can have any dimensionality and derived classes may
  19472. * apply special interpretations to the data.
  19473. *
  19474. * This class provides the interval seek in a Template Method, deferring
  19475. * the actual interpolation to derived classes.
  19476. *
  19477. * Time complexity is O(1) for linear access crossing at most two points
  19478. * and O(log N) for random access, where N is the number of positions.
  19479. *
  19480. * References:
  19481. *
  19482. * http://www.oodesign.com/template-method-pattern.html
  19483. *
  19484. */
  19485. class Interpolant {
  19486. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  19487. this.parameterPositions = parameterPositions;
  19488. this._cachedIndex = 0;
  19489. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
  19490. this.sampleValues = sampleValues;
  19491. this.valueSize = sampleSize;
  19492. this.settings = null;
  19493. this.DefaultSettings_ = {};
  19494. }
  19495. evaluate(t) {
  19496. const pp = this.parameterPositions;
  19497. let i1 = this._cachedIndex,
  19498. t1 = pp[i1],
  19499. t0 = pp[i1 - 1];
  19500. validate_interval: {
  19501. seek: {
  19502. let right;
  19503. linear_scan: {
  19504. //- See http://jsperf.com/comparison-to-undefined/3
  19505. //- slower code:
  19506. //-
  19507. //- if ( t >= t1 || t1 === undefined ) {
  19508. forward_scan: if (!(t < t1)) {
  19509. for (let giveUpAt = i1 + 2;;) {
  19510. if (t1 === undefined) {
  19511. if (t < t0) break forward_scan; // after end
  19512. i1 = pp.length;
  19513. this._cachedIndex = i1;
  19514. return this.afterEnd_(i1 - 1, t, t0);
  19515. }
  19516. if (i1 === giveUpAt) break; // this loop
  19517. t0 = t1;
  19518. t1 = pp[++i1];
  19519. if (t < t1) {
  19520. // we have arrived at the sought interval
  19521. break seek;
  19522. }
  19523. } // prepare binary search on the right side of the index
  19524. right = pp.length;
  19525. break linear_scan;
  19526. } //- slower code:
  19527. //- if ( t < t0 || t0 === undefined ) {
  19528. if (!(t >= t0)) {
  19529. // looping?
  19530. const t1global = pp[1];
  19531. if (t < t1global) {
  19532. i1 = 2; // + 1, using the scan for the details
  19533. t0 = t1global;
  19534. } // linear reverse scan
  19535. for (let giveUpAt = i1 - 2;;) {
  19536. if (t0 === undefined) {
  19537. // before start
  19538. this._cachedIndex = 0;
  19539. return this.beforeStart_(0, t, t1);
  19540. }
  19541. if (i1 === giveUpAt) break; // this loop
  19542. t1 = t0;
  19543. t0 = pp[--i1 - 1];
  19544. if (t >= t0) {
  19545. // we have arrived at the sought interval
  19546. break seek;
  19547. }
  19548. } // prepare binary search on the left side of the index
  19549. right = i1;
  19550. i1 = 0;
  19551. break linear_scan;
  19552. } // the interval is valid
  19553. break validate_interval;
  19554. } // linear scan
  19555. // binary search
  19556. while (i1 < right) {
  19557. const mid = i1 + right >>> 1;
  19558. if (t < pp[mid]) {
  19559. right = mid;
  19560. } else {
  19561. i1 = mid + 1;
  19562. }
  19563. }
  19564. t1 = pp[i1];
  19565. t0 = pp[i1 - 1]; // check boundary cases, again
  19566. if (t0 === undefined) {
  19567. this._cachedIndex = 0;
  19568. return this.beforeStart_(0, t, t1);
  19569. }
  19570. if (t1 === undefined) {
  19571. i1 = pp.length;
  19572. this._cachedIndex = i1;
  19573. return this.afterEnd_(i1 - 1, t0, t);
  19574. }
  19575. } // seek
  19576. this._cachedIndex = i1;
  19577. this.intervalChanged_(i1, t0, t1);
  19578. } // validate_interval
  19579. return this.interpolate_(i1, t0, t, t1);
  19580. }
  19581. getSettings_() {
  19582. return this.settings || this.DefaultSettings_;
  19583. }
  19584. copySampleValue_(index) {
  19585. // copies a sample value to the result buffer
  19586. const result = this.resultBuffer,
  19587. values = this.sampleValues,
  19588. stride = this.valueSize,
  19589. offset = index * stride;
  19590. for (let i = 0; i !== stride; ++i) {
  19591. result[i] = values[offset + i];
  19592. }
  19593. return result;
  19594. } // Template methods for derived classes:
  19595. interpolate_()
  19596. /* i1, t0, t, t1 */
  19597. {
  19598. throw new Error('call to abstract method'); // implementations shall return this.resultBuffer
  19599. }
  19600. intervalChanged_()
  19601. /* i1, t0, t1 */
  19602. {// empty
  19603. }
  19604. } // ALIAS DEFINITIONS
  19605. Interpolant.prototype.beforeStart_ = Interpolant.prototype.copySampleValue_;
  19606. Interpolant.prototype.afterEnd_ = Interpolant.prototype.copySampleValue_;
  19607. /**
  19608. * Fast and simple cubic spline interpolant.
  19609. *
  19610. * It was derived from a Hermitian construction setting the first derivative
  19611. * at each sample position to the linear slope between neighboring positions
  19612. * over their parameter interval.
  19613. */
  19614. class CubicInterpolant extends Interpolant {
  19615. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  19616. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  19617. this._weightPrev = -0;
  19618. this._offsetPrev = -0;
  19619. this._weightNext = -0;
  19620. this._offsetNext = -0;
  19621. this.DefaultSettings_ = {
  19622. endingStart: ZeroCurvatureEnding,
  19623. endingEnd: ZeroCurvatureEnding
  19624. };
  19625. }
  19626. intervalChanged_(i1, t0, t1) {
  19627. const pp = this.parameterPositions;
  19628. let iPrev = i1 - 2,
  19629. iNext = i1 + 1,
  19630. tPrev = pp[iPrev],
  19631. tNext = pp[iNext];
  19632. if (tPrev === undefined) {
  19633. switch (this.getSettings_().endingStart) {
  19634. case ZeroSlopeEnding:
  19635. // f'(t0) = 0
  19636. iPrev = i1;
  19637. tPrev = 2 * t0 - t1;
  19638. break;
  19639. case WrapAroundEnding:
  19640. // use the other end of the curve
  19641. iPrev = pp.length - 2;
  19642. tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
  19643. break;
  19644. default:
  19645. // ZeroCurvatureEnding
  19646. // f''(t0) = 0 a.k.a. Natural Spline
  19647. iPrev = i1;
  19648. tPrev = t1;
  19649. }
  19650. }
  19651. if (tNext === undefined) {
  19652. switch (this.getSettings_().endingEnd) {
  19653. case ZeroSlopeEnding:
  19654. // f'(tN) = 0
  19655. iNext = i1;
  19656. tNext = 2 * t1 - t0;
  19657. break;
  19658. case WrapAroundEnding:
  19659. // use the other end of the curve
  19660. iNext = 1;
  19661. tNext = t1 + pp[1] - pp[0];
  19662. break;
  19663. default:
  19664. // ZeroCurvatureEnding
  19665. // f''(tN) = 0, a.k.a. Natural Spline
  19666. iNext = i1 - 1;
  19667. tNext = t0;
  19668. }
  19669. }
  19670. const halfDt = (t1 - t0) * 0.5,
  19671. stride = this.valueSize;
  19672. this._weightPrev = halfDt / (t0 - tPrev);
  19673. this._weightNext = halfDt / (tNext - t1);
  19674. this._offsetPrev = iPrev * stride;
  19675. this._offsetNext = iNext * stride;
  19676. }
  19677. interpolate_(i1, t0, t, t1) {
  19678. const result = this.resultBuffer,
  19679. values = this.sampleValues,
  19680. stride = this.valueSize,
  19681. o1 = i1 * stride,
  19682. o0 = o1 - stride,
  19683. oP = this._offsetPrev,
  19684. oN = this._offsetNext,
  19685. wP = this._weightPrev,
  19686. wN = this._weightNext,
  19687. p = (t - t0) / (t1 - t0),
  19688. pp = p * p,
  19689. ppp = pp * p; // evaluate polynomials
  19690. const sP = -wP * ppp + 2 * wP * pp - wP * p;
  19691. const s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
  19692. const s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
  19693. const sN = wN * ppp - wN * pp; // combine data linearly
  19694. for (let i = 0; i !== stride; ++i) {
  19695. result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
  19696. }
  19697. return result;
  19698. }
  19699. }
  19700. class LinearInterpolant extends Interpolant {
  19701. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  19702. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  19703. }
  19704. interpolate_(i1, t0, t, t1) {
  19705. const result = this.resultBuffer,
  19706. values = this.sampleValues,
  19707. stride = this.valueSize,
  19708. offset1 = i1 * stride,
  19709. offset0 = offset1 - stride,
  19710. weight1 = (t - t0) / (t1 - t0),
  19711. weight0 = 1 - weight1;
  19712. for (let i = 0; i !== stride; ++i) {
  19713. result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
  19714. }
  19715. return result;
  19716. }
  19717. }
  19718. /**
  19719. *
  19720. * Interpolant that evaluates to the sample value at the position preceeding
  19721. * the parameter.
  19722. */
  19723. class DiscreteInterpolant extends Interpolant {
  19724. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  19725. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  19726. }
  19727. interpolate_(i1
  19728. /*, t0, t, t1 */
  19729. ) {
  19730. return this.copySampleValue_(i1 - 1);
  19731. }
  19732. }
  19733. class KeyframeTrack {
  19734. constructor(name, times, values, interpolation) {
  19735. if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
  19736. if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
  19737. this.name = name;
  19738. this.times = AnimationUtils.convertArray(times, this.TimeBufferType);
  19739. this.values = AnimationUtils.convertArray(values, this.ValueBufferType);
  19740. this.setInterpolation(interpolation || this.DefaultInterpolation);
  19741. } // Serialization (in static context, because of constructor invocation
  19742. // and automatic invocation of .toJSON):
  19743. static toJSON(track) {
  19744. const trackType = track.constructor;
  19745. let json; // derived classes can define a static toJSON method
  19746. if (trackType.toJSON !== this.toJSON) {
  19747. json = trackType.toJSON(track);
  19748. } else {
  19749. // by default, we assume the data can be serialized as-is
  19750. json = {
  19751. 'name': track.name,
  19752. 'times': AnimationUtils.convertArray(track.times, Array),
  19753. 'values': AnimationUtils.convertArray(track.values, Array)
  19754. };
  19755. const interpolation = track.getInterpolation();
  19756. if (interpolation !== track.DefaultInterpolation) {
  19757. json.interpolation = interpolation;
  19758. }
  19759. }
  19760. json.type = track.ValueTypeName; // mandatory
  19761. return json;
  19762. }
  19763. InterpolantFactoryMethodDiscrete(result) {
  19764. return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
  19765. }
  19766. InterpolantFactoryMethodLinear(result) {
  19767. return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
  19768. }
  19769. InterpolantFactoryMethodSmooth(result) {
  19770. return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
  19771. }
  19772. setInterpolation(interpolation) {
  19773. let factoryMethod;
  19774. switch (interpolation) {
  19775. case InterpolateDiscrete:
  19776. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  19777. break;
  19778. case InterpolateLinear:
  19779. factoryMethod = this.InterpolantFactoryMethodLinear;
  19780. break;
  19781. case InterpolateSmooth:
  19782. factoryMethod = this.InterpolantFactoryMethodSmooth;
  19783. break;
  19784. }
  19785. if (factoryMethod === undefined) {
  19786. const message = 'unsupported interpolation for ' + this.ValueTypeName + ' keyframe track named ' + this.name;
  19787. if (this.createInterpolant === undefined) {
  19788. // fall back to default, unless the default itself is messed up
  19789. if (interpolation !== this.DefaultInterpolation) {
  19790. this.setInterpolation(this.DefaultInterpolation);
  19791. } else {
  19792. throw new Error(message); // fatal, in this case
  19793. }
  19794. }
  19795. console.warn('THREE.KeyframeTrack:', message);
  19796. return this;
  19797. }
  19798. this.createInterpolant = factoryMethod;
  19799. return this;
  19800. }
  19801. getInterpolation() {
  19802. switch (this.createInterpolant) {
  19803. case this.InterpolantFactoryMethodDiscrete:
  19804. return InterpolateDiscrete;
  19805. case this.InterpolantFactoryMethodLinear:
  19806. return InterpolateLinear;
  19807. case this.InterpolantFactoryMethodSmooth:
  19808. return InterpolateSmooth;
  19809. }
  19810. }
  19811. getValueSize() {
  19812. return this.values.length / this.times.length;
  19813. } // move all keyframes either forwards or backwards in time
  19814. shift(timeOffset) {
  19815. if (timeOffset !== 0.0) {
  19816. const times = this.times;
  19817. for (let i = 0, n = times.length; i !== n; ++i) {
  19818. times[i] += timeOffset;
  19819. }
  19820. }
  19821. return this;
  19822. } // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  19823. scale(timeScale) {
  19824. if (timeScale !== 1.0) {
  19825. const times = this.times;
  19826. for (let i = 0, n = times.length; i !== n; ++i) {
  19827. times[i] *= timeScale;
  19828. }
  19829. }
  19830. return this;
  19831. } // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  19832. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  19833. trim(startTime, endTime) {
  19834. const times = this.times,
  19835. nKeys = times.length;
  19836. let from = 0,
  19837. to = nKeys - 1;
  19838. while (from !== nKeys && times[from] < startTime) {
  19839. ++from;
  19840. }
  19841. while (to !== -1 && times[to] > endTime) {
  19842. --to;
  19843. }
  19844. ++to; // inclusive -> exclusive bound
  19845. if (from !== 0 || to !== nKeys) {
  19846. // empty tracks are forbidden, so keep at least one keyframe
  19847. if (from >= to) {
  19848. to = Math.max(to, 1);
  19849. from = to - 1;
  19850. }
  19851. const stride = this.getValueSize();
  19852. this.times = AnimationUtils.arraySlice(times, from, to);
  19853. this.values = AnimationUtils.arraySlice(this.values, from * stride, to * stride);
  19854. }
  19855. return this;
  19856. } // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  19857. validate() {
  19858. let valid = true;
  19859. const valueSize = this.getValueSize();
  19860. if (valueSize - Math.floor(valueSize) !== 0) {
  19861. console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
  19862. valid = false;
  19863. }
  19864. const times = this.times,
  19865. values = this.values,
  19866. nKeys = times.length;
  19867. if (nKeys === 0) {
  19868. console.error('THREE.KeyframeTrack: Track is empty.', this);
  19869. valid = false;
  19870. }
  19871. let prevTime = null;
  19872. for (let i = 0; i !== nKeys; i++) {
  19873. const currTime = times[i];
  19874. if (typeof currTime === 'number' && isNaN(currTime)) {
  19875. console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
  19876. valid = false;
  19877. break;
  19878. }
  19879. if (prevTime !== null && prevTime > currTime) {
  19880. console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
  19881. valid = false;
  19882. break;
  19883. }
  19884. prevTime = currTime;
  19885. }
  19886. if (values !== undefined) {
  19887. if (AnimationUtils.isTypedArray(values)) {
  19888. for (let i = 0, n = values.length; i !== n; ++i) {
  19889. const value = values[i];
  19890. if (isNaN(value)) {
  19891. console.error('THREE.KeyframeTrack: Value is not a valid number.', this, i, value);
  19892. valid = false;
  19893. break;
  19894. }
  19895. }
  19896. }
  19897. }
  19898. return valid;
  19899. } // removes equivalent sequential keys as common in morph target sequences
  19900. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  19901. optimize() {
  19902. // times or values may be shared with other tracks, so overwriting is unsafe
  19903. const times = AnimationUtils.arraySlice(this.times),
  19904. values = AnimationUtils.arraySlice(this.values),
  19905. stride = this.getValueSize(),
  19906. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  19907. lastIndex = times.length - 1;
  19908. let writeIndex = 1;
  19909. for (let i = 1; i < lastIndex; ++i) {
  19910. let keep = false;
  19911. const time = times[i];
  19912. const timeNext = times[i + 1]; // remove adjacent keyframes scheduled at the same time
  19913. if (time !== timeNext && (i !== 1 || time !== times[0])) {
  19914. if (!smoothInterpolation) {
  19915. // remove unnecessary keyframes same as their neighbors
  19916. const offset = i * stride,
  19917. offsetP = offset - stride,
  19918. offsetN = offset + stride;
  19919. for (let j = 0; j !== stride; ++j) {
  19920. const value = values[offset + j];
  19921. if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
  19922. keep = true;
  19923. break;
  19924. }
  19925. }
  19926. } else {
  19927. keep = true;
  19928. }
  19929. } // in-place compaction
  19930. if (keep) {
  19931. if (i !== writeIndex) {
  19932. times[writeIndex] = times[i];
  19933. const readOffset = i * stride,
  19934. writeOffset = writeIndex * stride;
  19935. for (let j = 0; j !== stride; ++j) {
  19936. values[writeOffset + j] = values[readOffset + j];
  19937. }
  19938. }
  19939. ++writeIndex;
  19940. }
  19941. } // flush last keyframe (compaction looks ahead)
  19942. if (lastIndex > 0) {
  19943. times[writeIndex] = times[lastIndex];
  19944. for (let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++j) {
  19945. values[writeOffset + j] = values[readOffset + j];
  19946. }
  19947. ++writeIndex;
  19948. }
  19949. if (writeIndex !== times.length) {
  19950. this.times = AnimationUtils.arraySlice(times, 0, writeIndex);
  19951. this.values = AnimationUtils.arraySlice(values, 0, writeIndex * stride);
  19952. } else {
  19953. this.times = times;
  19954. this.values = values;
  19955. }
  19956. return this;
  19957. }
  19958. clone() {
  19959. const times = AnimationUtils.arraySlice(this.times, 0);
  19960. const values = AnimationUtils.arraySlice(this.values, 0);
  19961. const TypedKeyframeTrack = this.constructor;
  19962. const track = new TypedKeyframeTrack(this.name, times, values); // Interpolant argument to constructor is not saved, so copy the factory method directly.
  19963. track.createInterpolant = this.createInterpolant;
  19964. return track;
  19965. }
  19966. }
  19967. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  19968. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  19969. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  19970. /**
  19971. * A Track of Boolean keyframe values.
  19972. */
  19973. class BooleanKeyframeTrack extends KeyframeTrack {}
  19974. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  19975. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  19976. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  19977. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  19978. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; // Note: Actually this track could have a optimized / compressed
  19979. /**
  19980. * A Track of keyframe values that represent color.
  19981. */
  19982. class ColorKeyframeTrack extends KeyframeTrack {}
  19983. ColorKeyframeTrack.prototype.ValueTypeName = 'color'; // ValueBufferType is inherited
  19984. /**
  19985. * A Track of numeric keyframe values.
  19986. */
  19987. class NumberKeyframeTrack extends KeyframeTrack {}
  19988. NumberKeyframeTrack.prototype.ValueTypeName = 'number'; // ValueBufferType is inherited
  19989. /**
  19990. * Spherical linear unit quaternion interpolant.
  19991. */
  19992. class QuaternionLinearInterpolant extends Interpolant {
  19993. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  19994. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  19995. }
  19996. interpolate_(i1, t0, t, t1) {
  19997. const result = this.resultBuffer,
  19998. values = this.sampleValues,
  19999. stride = this.valueSize,
  20000. alpha = (t - t0) / (t1 - t0);
  20001. let offset = i1 * stride;
  20002. for (let end = offset + stride; offset !== end; offset += 4) {
  20003. Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
  20004. }
  20005. return result;
  20006. }
  20007. }
  20008. /**
  20009. * A Track of quaternion keyframe values.
  20010. */
  20011. class QuaternionKeyframeTrack extends KeyframeTrack {
  20012. InterpolantFactoryMethodLinear(result) {
  20013. return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
  20014. }
  20015. }
  20016. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion'; // ValueBufferType is inherited
  20017. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  20018. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  20019. /**
  20020. * A Track that interpolates Strings
  20021. */
  20022. class StringKeyframeTrack extends KeyframeTrack {}
  20023. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  20024. StringKeyframeTrack.prototype.ValueBufferType = Array;
  20025. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  20026. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  20027. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  20028. /**
  20029. * A Track of vectored keyframe values.
  20030. */
  20031. class VectorKeyframeTrack extends KeyframeTrack {}
  20032. VectorKeyframeTrack.prototype.ValueTypeName = 'vector'; // ValueBufferType is inherited
  20033. class AnimationClip {
  20034. constructor(name, duration = -1, tracks, blendMode = NormalAnimationBlendMode) {
  20035. this.name = name;
  20036. this.tracks = tracks;
  20037. this.duration = duration;
  20038. this.blendMode = blendMode;
  20039. this.uuid = generateUUID(); // this means it should figure out its duration by scanning the tracks
  20040. if (this.duration < 0) {
  20041. this.resetDuration();
  20042. }
  20043. }
  20044. static parse(json) {
  20045. const tracks = [],
  20046. jsonTracks = json.tracks,
  20047. frameTime = 1.0 / (json.fps || 1.0);
  20048. for (let i = 0, n = jsonTracks.length; i !== n; ++i) {
  20049. tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime));
  20050. }
  20051. const clip = new this(json.name, json.duration, tracks, json.blendMode);
  20052. clip.uuid = json.uuid;
  20053. return clip;
  20054. }
  20055. static toJSON(clip) {
  20056. const tracks = [],
  20057. clipTracks = clip.tracks;
  20058. const json = {
  20059. 'name': clip.name,
  20060. 'duration': clip.duration,
  20061. 'tracks': tracks,
  20062. 'uuid': clip.uuid,
  20063. 'blendMode': clip.blendMode
  20064. };
  20065. for (let i = 0, n = clipTracks.length; i !== n; ++i) {
  20066. tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
  20067. }
  20068. return json;
  20069. }
  20070. static CreateFromMorphTargetSequence(name, morphTargetSequence, fps, noLoop) {
  20071. const numMorphTargets = morphTargetSequence.length;
  20072. const tracks = [];
  20073. for (let i = 0; i < numMorphTargets; i++) {
  20074. let times = [];
  20075. let values = [];
  20076. times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);
  20077. values.push(0, 1, 0);
  20078. const order = AnimationUtils.getKeyframeOrder(times);
  20079. times = AnimationUtils.sortedArray(times, 1, order);
  20080. values = AnimationUtils.sortedArray(values, 1, order); // if there is a key at the first frame, duplicate it as the
  20081. // last frame as well for perfect loop.
  20082. if (!noLoop && times[0] === 0) {
  20083. times.push(numMorphTargets);
  20084. values.push(values[0]);
  20085. }
  20086. tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
  20087. }
  20088. return new this(name, -1, tracks);
  20089. }
  20090. static findByName(objectOrClipArray, name) {
  20091. let clipArray = objectOrClipArray;
  20092. if (!Array.isArray(objectOrClipArray)) {
  20093. const o = objectOrClipArray;
  20094. clipArray = o.geometry && o.geometry.animations || o.animations;
  20095. }
  20096. for (let i = 0; i < clipArray.length; i++) {
  20097. if (clipArray[i].name === name) {
  20098. return clipArray[i];
  20099. }
  20100. }
  20101. return null;
  20102. }
  20103. static CreateClipsFromMorphTargetSequences(morphTargets, fps, noLoop) {
  20104. const animationToMorphTargets = {}; // tested with https://regex101.com/ on trick sequences
  20105. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  20106. const pattern = /^([\w-]*?)([\d]+)$/; // sort morph target names into animation groups based
  20107. // patterns like Walk_001, Walk_002, Run_001, Run_002
  20108. for (let i = 0, il = morphTargets.length; i < il; i++) {
  20109. const morphTarget = morphTargets[i];
  20110. const parts = morphTarget.name.match(pattern);
  20111. if (parts && parts.length > 1) {
  20112. const name = parts[1];
  20113. let animationMorphTargets = animationToMorphTargets[name];
  20114. if (!animationMorphTargets) {
  20115. animationToMorphTargets[name] = animationMorphTargets = [];
  20116. }
  20117. animationMorphTargets.push(morphTarget);
  20118. }
  20119. }
  20120. const clips = [];
  20121. for (const name in animationToMorphTargets) {
  20122. clips.push(this.CreateFromMorphTargetSequence(name, animationToMorphTargets[name], fps, noLoop));
  20123. }
  20124. return clips;
  20125. } // parse the animation.hierarchy format
  20126. static parseAnimation(animation, bones) {
  20127. if (!animation) {
  20128. console.error('THREE.AnimationClip: No animation in JSONLoader data.');
  20129. return null;
  20130. }
  20131. const addNonemptyTrack = function (trackType, trackName, animationKeys, propertyName, destTracks) {
  20132. // only return track if there are actually keys.
  20133. if (animationKeys.length !== 0) {
  20134. const times = [];
  20135. const values = [];
  20136. AnimationUtils.flattenJSON(animationKeys, times, values, propertyName); // empty keys are filtered out, so check again
  20137. if (times.length !== 0) {
  20138. destTracks.push(new trackType(trackName, times, values));
  20139. }
  20140. }
  20141. };
  20142. const tracks = [];
  20143. const clipName = animation.name || 'default';
  20144. const fps = animation.fps || 30;
  20145. const blendMode = animation.blendMode; // automatic length determination in AnimationClip.
  20146. let duration = animation.length || -1;
  20147. const hierarchyTracks = animation.hierarchy || [];
  20148. for (let h = 0; h < hierarchyTracks.length; h++) {
  20149. const animationKeys = hierarchyTracks[h].keys; // skip empty tracks
  20150. if (!animationKeys || animationKeys.length === 0) continue; // process morph targets
  20151. if (animationKeys[0].morphTargets) {
  20152. // figure out all morph targets used in this track
  20153. const morphTargetNames = {};
  20154. let k;
  20155. for (k = 0; k < animationKeys.length; k++) {
  20156. if (animationKeys[k].morphTargets) {
  20157. for (let m = 0; m < animationKeys[k].morphTargets.length; m++) {
  20158. morphTargetNames[animationKeys[k].morphTargets[m]] = -1;
  20159. }
  20160. }
  20161. } // create a track for each morph target with all zero
  20162. // morphTargetInfluences except for the keys in which
  20163. // the morphTarget is named.
  20164. for (const morphTargetName in morphTargetNames) {
  20165. const times = [];
  20166. const values = [];
  20167. for (let m = 0; m !== animationKeys[k].morphTargets.length; ++m) {
  20168. const animationKey = animationKeys[k];
  20169. times.push(animationKey.time);
  20170. values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
  20171. }
  20172. tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));
  20173. }
  20174. duration = morphTargetNames.length * (fps || 1.0);
  20175. } else {
  20176. // ...assume skeletal animation
  20177. const boneName = '.bones[' + bones[h].name + ']';
  20178. addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);
  20179. addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);
  20180. addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);
  20181. }
  20182. }
  20183. if (tracks.length === 0) {
  20184. return null;
  20185. }
  20186. const clip = new this(clipName, duration, tracks, blendMode);
  20187. return clip;
  20188. }
  20189. resetDuration() {
  20190. const tracks = this.tracks;
  20191. let duration = 0;
  20192. for (let i = 0, n = tracks.length; i !== n; ++i) {
  20193. const track = this.tracks[i];
  20194. duration = Math.max(duration, track.times[track.times.length - 1]);
  20195. }
  20196. this.duration = duration;
  20197. return this;
  20198. }
  20199. trim() {
  20200. for (let i = 0; i < this.tracks.length; i++) {
  20201. this.tracks[i].trim(0, this.duration);
  20202. }
  20203. return this;
  20204. }
  20205. validate() {
  20206. let valid = true;
  20207. for (let i = 0; i < this.tracks.length; i++) {
  20208. valid = valid && this.tracks[i].validate();
  20209. }
  20210. return valid;
  20211. }
  20212. optimize() {
  20213. for (let i = 0; i < this.tracks.length; i++) {
  20214. this.tracks[i].optimize();
  20215. }
  20216. return this;
  20217. }
  20218. clone() {
  20219. const tracks = [];
  20220. for (let i = 0; i < this.tracks.length; i++) {
  20221. tracks.push(this.tracks[i].clone());
  20222. }
  20223. return new this.constructor(this.name, this.duration, tracks, this.blendMode);
  20224. }
  20225. toJSON() {
  20226. return this.constructor.toJSON(this);
  20227. }
  20228. }
  20229. function getTrackTypeForValueTypeName(typeName) {
  20230. switch (typeName.toLowerCase()) {
  20231. case 'scalar':
  20232. case 'double':
  20233. case 'float':
  20234. case 'number':
  20235. case 'integer':
  20236. return NumberKeyframeTrack;
  20237. case 'vector':
  20238. case 'vector2':
  20239. case 'vector3':
  20240. case 'vector4':
  20241. return VectorKeyframeTrack;
  20242. case 'color':
  20243. return ColorKeyframeTrack;
  20244. case 'quaternion':
  20245. return QuaternionKeyframeTrack;
  20246. case 'bool':
  20247. case 'boolean':
  20248. return BooleanKeyframeTrack;
  20249. case 'string':
  20250. return StringKeyframeTrack;
  20251. }
  20252. throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);
  20253. }
  20254. function parseKeyframeTrack(json) {
  20255. if (json.type === undefined) {
  20256. throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
  20257. }
  20258. const trackType = getTrackTypeForValueTypeName(json.type);
  20259. if (json.times === undefined) {
  20260. const times = [],
  20261. values = [];
  20262. AnimationUtils.flattenJSON(json.keys, times, values, 'value');
  20263. json.times = times;
  20264. json.values = values;
  20265. } // derived classes can define a static parse method
  20266. if (trackType.parse !== undefined) {
  20267. return trackType.parse(json);
  20268. } else {
  20269. // by default, we assume a constructor compatible with the base
  20270. return new trackType(json.name, json.times, json.values, json.interpolation);
  20271. }
  20272. }
  20273. const Cache = {
  20274. enabled: false,
  20275. files: {},
  20276. add: function (key, file) {
  20277. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Adding key:', key );
  20278. this.files[key] = file;
  20279. },
  20280. get: function (key) {
  20281. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Checking key:', key );
  20282. return this.files[key];
  20283. },
  20284. remove: function (key) {
  20285. delete this.files[key];
  20286. },
  20287. clear: function () {
  20288. this.files = {};
  20289. }
  20290. };
  20291. class LoadingManager {
  20292. constructor(onLoad, onProgress, onError) {
  20293. const scope = this;
  20294. let isLoading = false;
  20295. let itemsLoaded = 0;
  20296. let itemsTotal = 0;
  20297. let urlModifier = undefined;
  20298. const handlers = []; // Refer to #5689 for the reason why we don't set .onStart
  20299. // in the constructor
  20300. this.onStart = undefined;
  20301. this.onLoad = onLoad;
  20302. this.onProgress = onProgress;
  20303. this.onError = onError;
  20304. this.itemStart = function (url) {
  20305. itemsTotal++;
  20306. if (isLoading === false) {
  20307. if (scope.onStart !== undefined) {
  20308. scope.onStart(url, itemsLoaded, itemsTotal);
  20309. }
  20310. }
  20311. isLoading = true;
  20312. };
  20313. this.itemEnd = function (url) {
  20314. itemsLoaded++;
  20315. if (scope.onProgress !== undefined) {
  20316. scope.onProgress(url, itemsLoaded, itemsTotal);
  20317. }
  20318. if (itemsLoaded === itemsTotal) {
  20319. isLoading = false;
  20320. if (scope.onLoad !== undefined) {
  20321. scope.onLoad();
  20322. }
  20323. }
  20324. };
  20325. this.itemError = function (url) {
  20326. if (scope.onError !== undefined) {
  20327. scope.onError(url);
  20328. }
  20329. };
  20330. this.resolveURL = function (url) {
  20331. if (urlModifier) {
  20332. return urlModifier(url);
  20333. }
  20334. return url;
  20335. };
  20336. this.setURLModifier = function (transform) {
  20337. urlModifier = transform;
  20338. return this;
  20339. };
  20340. this.addHandler = function (regex, loader) {
  20341. handlers.push(regex, loader);
  20342. return this;
  20343. };
  20344. this.removeHandler = function (regex) {
  20345. const index = handlers.indexOf(regex);
  20346. if (index !== -1) {
  20347. handlers.splice(index, 2);
  20348. }
  20349. return this;
  20350. };
  20351. this.getHandler = function (file) {
  20352. for (let i = 0, l = handlers.length; i < l; i += 2) {
  20353. const regex = handlers[i];
  20354. const loader = handlers[i + 1];
  20355. if (regex.global) regex.lastIndex = 0; // see #17920
  20356. if (regex.test(file)) {
  20357. return loader;
  20358. }
  20359. }
  20360. return null;
  20361. };
  20362. }
  20363. }
  20364. const DefaultLoadingManager = new LoadingManager();
  20365. class Loader {
  20366. constructor(manager) {
  20367. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  20368. this.crossOrigin = 'anonymous';
  20369. this.withCredentials = false;
  20370. this.path = '';
  20371. this.resourcePath = '';
  20372. this.requestHeader = {};
  20373. }
  20374. load()
  20375. /* url, onLoad, onProgress, onError */
  20376. {}
  20377. loadAsync(url, onProgress) {
  20378. const scope = this;
  20379. return new Promise(function (resolve, reject) {
  20380. scope.load(url, resolve, onProgress, reject);
  20381. });
  20382. }
  20383. parse()
  20384. /* data */
  20385. {}
  20386. setCrossOrigin(crossOrigin) {
  20387. this.crossOrigin = crossOrigin;
  20388. return this;
  20389. }
  20390. setWithCredentials(value) {
  20391. this.withCredentials = value;
  20392. return this;
  20393. }
  20394. setPath(path) {
  20395. this.path = path;
  20396. return this;
  20397. }
  20398. setResourcePath(resourcePath) {
  20399. this.resourcePath = resourcePath;
  20400. return this;
  20401. }
  20402. setRequestHeader(requestHeader) {
  20403. this.requestHeader = requestHeader;
  20404. return this;
  20405. }
  20406. }
  20407. const loading = {};
  20408. class FileLoader extends Loader {
  20409. constructor(manager) {
  20410. super(manager);
  20411. }
  20412. load(url, onLoad, onProgress, onError) {
  20413. if (url === undefined) url = '';
  20414. if (this.path !== undefined) url = this.path + url;
  20415. url = this.manager.resolveURL(url);
  20416. const scope = this;
  20417. const cached = Cache.get(url);
  20418. if (cached !== undefined) {
  20419. scope.manager.itemStart(url);
  20420. setTimeout(function () {
  20421. if (onLoad) onLoad(cached);
  20422. scope.manager.itemEnd(url);
  20423. }, 0);
  20424. return cached;
  20425. } // Check if request is duplicate
  20426. if (loading[url] !== undefined) {
  20427. loading[url].push({
  20428. onLoad: onLoad,
  20429. onProgress: onProgress,
  20430. onError: onError
  20431. });
  20432. return;
  20433. } // Check for data: URI
  20434. const dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  20435. const dataUriRegexResult = url.match(dataUriRegex);
  20436. let request; // Safari can not handle Data URIs through XMLHttpRequest so process manually
  20437. if (dataUriRegexResult) {
  20438. const mimeType = dataUriRegexResult[1];
  20439. const isBase64 = !!dataUriRegexResult[2];
  20440. let data = dataUriRegexResult[3];
  20441. data = decodeURIComponent(data);
  20442. if (isBase64) data = atob(data);
  20443. try {
  20444. let response;
  20445. const responseType = (this.responseType || '').toLowerCase();
  20446. switch (responseType) {
  20447. case 'arraybuffer':
  20448. case 'blob':
  20449. const view = new Uint8Array(data.length);
  20450. for (let i = 0; i < data.length; i++) {
  20451. view[i] = data.charCodeAt(i);
  20452. }
  20453. if (responseType === 'blob') {
  20454. response = new Blob([view.buffer], {
  20455. type: mimeType
  20456. });
  20457. } else {
  20458. response = view.buffer;
  20459. }
  20460. break;
  20461. case 'document':
  20462. const parser = new DOMParser();
  20463. response = parser.parseFromString(data, mimeType);
  20464. break;
  20465. case 'json':
  20466. response = JSON.parse(data);
  20467. break;
  20468. default:
  20469. // 'text' or other
  20470. response = data;
  20471. break;
  20472. } // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  20473. setTimeout(function () {
  20474. if (onLoad) onLoad(response);
  20475. scope.manager.itemEnd(url);
  20476. }, 0);
  20477. } catch (error) {
  20478. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  20479. setTimeout(function () {
  20480. if (onError) onError(error);
  20481. scope.manager.itemError(url);
  20482. scope.manager.itemEnd(url);
  20483. }, 0);
  20484. }
  20485. } else {
  20486. // Initialise array for duplicate requests
  20487. loading[url] = [];
  20488. loading[url].push({
  20489. onLoad: onLoad,
  20490. onProgress: onProgress,
  20491. onError: onError
  20492. });
  20493. request = new XMLHttpRequest();
  20494. request.open('GET', url, true);
  20495. request.addEventListener('load', function (event) {
  20496. const response = this.response;
  20497. const callbacks = loading[url];
  20498. delete loading[url];
  20499. if (this.status === 200 || this.status === 0) {
  20500. // Some browsers return HTTP Status 0 when using non-http protocol
  20501. // e.g. 'file://' or 'data://'. Handle as success.
  20502. if (this.status === 0) console.warn('THREE.FileLoader: HTTP Status 0 received.'); // Add to cache only on HTTP success, so that we do not cache
  20503. // error response bodies as proper responses to requests.
  20504. Cache.add(url, response);
  20505. for (let i = 0, il = callbacks.length; i < il; i++) {
  20506. const callback = callbacks[i];
  20507. if (callback.onLoad) callback.onLoad(response);
  20508. }
  20509. scope.manager.itemEnd(url);
  20510. } else {
  20511. for (let i = 0, il = callbacks.length; i < il; i++) {
  20512. const callback = callbacks[i];
  20513. if (callback.onError) callback.onError(event);
  20514. }
  20515. scope.manager.itemError(url);
  20516. scope.manager.itemEnd(url);
  20517. }
  20518. }, false);
  20519. request.addEventListener('progress', function (event) {
  20520. const callbacks = loading[url];
  20521. for (let i = 0, il = callbacks.length; i < il; i++) {
  20522. const callback = callbacks[i];
  20523. if (callback.onProgress) callback.onProgress(event);
  20524. }
  20525. }, false);
  20526. request.addEventListener('error', function (event) {
  20527. const callbacks = loading[url];
  20528. delete loading[url];
  20529. for (let i = 0, il = callbacks.length; i < il; i++) {
  20530. const callback = callbacks[i];
  20531. if (callback.onError) callback.onError(event);
  20532. }
  20533. scope.manager.itemError(url);
  20534. scope.manager.itemEnd(url);
  20535. }, false);
  20536. request.addEventListener('abort', function (event) {
  20537. const callbacks = loading[url];
  20538. delete loading[url];
  20539. for (let i = 0, il = callbacks.length; i < il; i++) {
  20540. const callback = callbacks[i];
  20541. if (callback.onError) callback.onError(event);
  20542. }
  20543. scope.manager.itemError(url);
  20544. scope.manager.itemEnd(url);
  20545. }, false);
  20546. if (this.responseType !== undefined) request.responseType = this.responseType;
  20547. if (this.withCredentials !== undefined) request.withCredentials = this.withCredentials;
  20548. if (request.overrideMimeType) request.overrideMimeType(this.mimeType !== undefined ? this.mimeType : 'text/plain');
  20549. for (const header in this.requestHeader) {
  20550. request.setRequestHeader(header, this.requestHeader[header]);
  20551. }
  20552. request.send(null);
  20553. }
  20554. scope.manager.itemStart(url);
  20555. return request;
  20556. }
  20557. setResponseType(value) {
  20558. this.responseType = value;
  20559. return this;
  20560. }
  20561. setMimeType(value) {
  20562. this.mimeType = value;
  20563. return this;
  20564. }
  20565. }
  20566. class AnimationLoader extends Loader {
  20567. constructor(manager) {
  20568. super(manager);
  20569. }
  20570. load(url, onLoad, onProgress, onError) {
  20571. const scope = this;
  20572. const loader = new FileLoader(this.manager);
  20573. loader.setPath(this.path);
  20574. loader.setRequestHeader(this.requestHeader);
  20575. loader.setWithCredentials(this.withCredentials);
  20576. loader.load(url, function (text) {
  20577. try {
  20578. onLoad(scope.parse(JSON.parse(text)));
  20579. } catch (e) {
  20580. if (onError) {
  20581. onError(e);
  20582. } else {
  20583. console.error(e);
  20584. }
  20585. scope.manager.itemError(url);
  20586. }
  20587. }, onProgress, onError);
  20588. }
  20589. parse(json) {
  20590. const animations = [];
  20591. for (let i = 0; i < json.length; i++) {
  20592. const clip = AnimationClip.parse(json[i]);
  20593. animations.push(clip);
  20594. }
  20595. return animations;
  20596. }
  20597. }
  20598. /**
  20599. * Abstract Base class to block based textures loader (dds, pvr, ...)
  20600. *
  20601. * Sub classes have to implement the parse() method which will be used in load().
  20602. */
  20603. class CompressedTextureLoader extends Loader {
  20604. constructor(manager) {
  20605. super(manager);
  20606. }
  20607. load(url, onLoad, onProgress, onError) {
  20608. const scope = this;
  20609. const images = [];
  20610. const texture = new CompressedTexture();
  20611. const loader = new FileLoader(this.manager);
  20612. loader.setPath(this.path);
  20613. loader.setResponseType('arraybuffer');
  20614. loader.setRequestHeader(this.requestHeader);
  20615. loader.setWithCredentials(scope.withCredentials);
  20616. let loaded = 0;
  20617. function loadTexture(i) {
  20618. loader.load(url[i], function (buffer) {
  20619. const texDatas = scope.parse(buffer, true);
  20620. images[i] = {
  20621. width: texDatas.width,
  20622. height: texDatas.height,
  20623. format: texDatas.format,
  20624. mipmaps: texDatas.mipmaps
  20625. };
  20626. loaded += 1;
  20627. if (loaded === 6) {
  20628. if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
  20629. texture.image = images;
  20630. texture.format = texDatas.format;
  20631. texture.needsUpdate = true;
  20632. if (onLoad) onLoad(texture);
  20633. }
  20634. }, onProgress, onError);
  20635. }
  20636. if (Array.isArray(url)) {
  20637. for (let i = 0, il = url.length; i < il; ++i) {
  20638. loadTexture(i);
  20639. }
  20640. } else {
  20641. // compressed cubemap texture stored in a single DDS file
  20642. loader.load(url, function (buffer) {
  20643. const texDatas = scope.parse(buffer, true);
  20644. if (texDatas.isCubemap) {
  20645. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  20646. for (let f = 0; f < faces; f++) {
  20647. images[f] = {
  20648. mipmaps: []
  20649. };
  20650. for (let i = 0; i < texDatas.mipmapCount; i++) {
  20651. images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]);
  20652. images[f].format = texDatas.format;
  20653. images[f].width = texDatas.width;
  20654. images[f].height = texDatas.height;
  20655. }
  20656. }
  20657. texture.image = images;
  20658. } else {
  20659. texture.image.width = texDatas.width;
  20660. texture.image.height = texDatas.height;
  20661. texture.mipmaps = texDatas.mipmaps;
  20662. }
  20663. if (texDatas.mipmapCount === 1) {
  20664. texture.minFilter = LinearFilter;
  20665. }
  20666. texture.format = texDatas.format;
  20667. texture.needsUpdate = true;
  20668. if (onLoad) onLoad(texture);
  20669. }, onProgress, onError);
  20670. }
  20671. return texture;
  20672. }
  20673. }
  20674. class ImageLoader extends Loader {
  20675. constructor(manager) {
  20676. super(manager);
  20677. }
  20678. load(url, onLoad, onProgress, onError) {
  20679. if (this.path !== undefined) url = this.path + url;
  20680. url = this.manager.resolveURL(url);
  20681. const scope = this;
  20682. const cached = Cache.get(url);
  20683. if (cached !== undefined) {
  20684. scope.manager.itemStart(url);
  20685. setTimeout(function () {
  20686. if (onLoad) onLoad(cached);
  20687. scope.manager.itemEnd(url);
  20688. }, 0);
  20689. return cached;
  20690. }
  20691. const image = document.createElementNS('http://www.w3.org/1999/xhtml', 'img');
  20692. function onImageLoad() {
  20693. image.removeEventListener('load', onImageLoad, false);
  20694. image.removeEventListener('error', onImageError, false);
  20695. Cache.add(url, this);
  20696. if (onLoad) onLoad(this);
  20697. scope.manager.itemEnd(url);
  20698. }
  20699. function onImageError(event) {
  20700. image.removeEventListener('load', onImageLoad, false);
  20701. image.removeEventListener('error', onImageError, false);
  20702. if (onError) onError(event);
  20703. scope.manager.itemError(url);
  20704. scope.manager.itemEnd(url);
  20705. }
  20706. image.addEventListener('load', onImageLoad, false);
  20707. image.addEventListener('error', onImageError, false);
  20708. if (url.substr(0, 5) !== 'data:') {
  20709. if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
  20710. }
  20711. scope.manager.itemStart(url);
  20712. image.src = url;
  20713. return image;
  20714. }
  20715. }
  20716. class CubeTextureLoader extends Loader {
  20717. constructor(manager) {
  20718. super(manager);
  20719. }
  20720. load(urls, onLoad, onProgress, onError) {
  20721. const texture = new CubeTexture();
  20722. const loader = new ImageLoader(this.manager);
  20723. loader.setCrossOrigin(this.crossOrigin);
  20724. loader.setPath(this.path);
  20725. let loaded = 0;
  20726. function loadTexture(i) {
  20727. loader.load(urls[i], function (image) {
  20728. texture.images[i] = image;
  20729. loaded++;
  20730. if (loaded === 6) {
  20731. texture.needsUpdate = true;
  20732. if (onLoad) onLoad(texture);
  20733. }
  20734. }, undefined, onError);
  20735. }
  20736. for (let i = 0; i < urls.length; ++i) {
  20737. loadTexture(i);
  20738. }
  20739. return texture;
  20740. }
  20741. }
  20742. /**
  20743. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  20744. *
  20745. * Sub classes have to implement the parse() method which will be used in load().
  20746. */
  20747. class DataTextureLoader extends Loader {
  20748. constructor(manager) {
  20749. super(manager);
  20750. }
  20751. load(url, onLoad, onProgress, onError) {
  20752. const scope = this;
  20753. const texture = new DataTexture();
  20754. const loader = new FileLoader(this.manager);
  20755. loader.setResponseType('arraybuffer');
  20756. loader.setRequestHeader(this.requestHeader);
  20757. loader.setPath(this.path);
  20758. loader.setWithCredentials(scope.withCredentials);
  20759. loader.load(url, function (buffer) {
  20760. const texData = scope.parse(buffer);
  20761. if (!texData) return;
  20762. if (texData.image !== undefined) {
  20763. texture.image = texData.image;
  20764. } else if (texData.data !== undefined) {
  20765. texture.image.width = texData.width;
  20766. texture.image.height = texData.height;
  20767. texture.image.data = texData.data;
  20768. }
  20769. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  20770. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  20771. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  20772. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  20773. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  20774. if (texData.encoding !== undefined) {
  20775. texture.encoding = texData.encoding;
  20776. }
  20777. if (texData.flipY !== undefined) {
  20778. texture.flipY = texData.flipY;
  20779. }
  20780. if (texData.format !== undefined) {
  20781. texture.format = texData.format;
  20782. }
  20783. if (texData.type !== undefined) {
  20784. texture.type = texData.type;
  20785. }
  20786. if (texData.mipmaps !== undefined) {
  20787. texture.mipmaps = texData.mipmaps;
  20788. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  20789. }
  20790. if (texData.mipmapCount === 1) {
  20791. texture.minFilter = LinearFilter;
  20792. }
  20793. if (texData.generateMipmaps !== undefined) {
  20794. texture.generateMipmaps = texData.generateMipmaps;
  20795. }
  20796. texture.needsUpdate = true;
  20797. if (onLoad) onLoad(texture, texData);
  20798. }, onProgress, onError);
  20799. return texture;
  20800. }
  20801. }
  20802. class TextureLoader extends Loader {
  20803. constructor(manager) {
  20804. super(manager);
  20805. }
  20806. load(url, onLoad, onProgress, onError) {
  20807. const texture = new Texture();
  20808. const loader = new ImageLoader(this.manager);
  20809. loader.setCrossOrigin(this.crossOrigin);
  20810. loader.setPath(this.path);
  20811. loader.load(url, function (image) {
  20812. texture.image = image; // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  20813. const isJPEG = url.search(/\.jpe?g($|\?)/i) > 0 || url.search(/^data\:image\/jpeg/) === 0;
  20814. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  20815. texture.needsUpdate = true;
  20816. if (onLoad !== undefined) {
  20817. onLoad(texture);
  20818. }
  20819. }, onProgress, onError);
  20820. return texture;
  20821. }
  20822. }
  20823. /**
  20824. * Extensible curve object.
  20825. *
  20826. * Some common of curve methods:
  20827. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  20828. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  20829. * .getPoints(), .getSpacedPoints()
  20830. * .getLength()
  20831. * .updateArcLengths()
  20832. *
  20833. * This following curves inherit from THREE.Curve:
  20834. *
  20835. * -- 2D curves --
  20836. * THREE.ArcCurve
  20837. * THREE.CubicBezierCurve
  20838. * THREE.EllipseCurve
  20839. * THREE.LineCurve
  20840. * THREE.QuadraticBezierCurve
  20841. * THREE.SplineCurve
  20842. *
  20843. * -- 3D curves --
  20844. * THREE.CatmullRomCurve3
  20845. * THREE.CubicBezierCurve3
  20846. * THREE.LineCurve3
  20847. * THREE.QuadraticBezierCurve3
  20848. *
  20849. * A series of curves can be represented as a THREE.CurvePath.
  20850. *
  20851. **/
  20852. class Curve {
  20853. constructor() {
  20854. this.type = 'Curve';
  20855. this.arcLengthDivisions = 200;
  20856. } // Virtual base class method to overwrite and implement in subclasses
  20857. // - t [0 .. 1]
  20858. getPoint()
  20859. /* t, optionalTarget */
  20860. {
  20861. console.warn('THREE.Curve: .getPoint() not implemented.');
  20862. return null;
  20863. } // Get point at relative position in curve according to arc length
  20864. // - u [0 .. 1]
  20865. getPointAt(u, optionalTarget) {
  20866. const t = this.getUtoTmapping(u);
  20867. return this.getPoint(t, optionalTarget);
  20868. } // Get sequence of points using getPoint( t )
  20869. getPoints(divisions = 5) {
  20870. const points = [];
  20871. for (let d = 0; d <= divisions; d++) {
  20872. points.push(this.getPoint(d / divisions));
  20873. }
  20874. return points;
  20875. } // Get sequence of points using getPointAt( u )
  20876. getSpacedPoints(divisions = 5) {
  20877. const points = [];
  20878. for (let d = 0; d <= divisions; d++) {
  20879. points.push(this.getPointAt(d / divisions));
  20880. }
  20881. return points;
  20882. } // Get total curve arc length
  20883. getLength() {
  20884. const lengths = this.getLengths();
  20885. return lengths[lengths.length - 1];
  20886. } // Get list of cumulative segment lengths
  20887. getLengths(divisions = this.arcLengthDivisions) {
  20888. if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
  20889. return this.cacheArcLengths;
  20890. }
  20891. this.needsUpdate = false;
  20892. const cache = [];
  20893. let current,
  20894. last = this.getPoint(0);
  20895. let sum = 0;
  20896. cache.push(0);
  20897. for (let p = 1; p <= divisions; p++) {
  20898. current = this.getPoint(p / divisions);
  20899. sum += current.distanceTo(last);
  20900. cache.push(sum);
  20901. last = current;
  20902. }
  20903. this.cacheArcLengths = cache;
  20904. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  20905. }
  20906. updateArcLengths() {
  20907. this.needsUpdate = true;
  20908. this.getLengths();
  20909. } // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  20910. getUtoTmapping(u, distance) {
  20911. const arcLengths = this.getLengths();
  20912. let i = 0;
  20913. const il = arcLengths.length;
  20914. let targetArcLength; // The targeted u distance value to get
  20915. if (distance) {
  20916. targetArcLength = distance;
  20917. } else {
  20918. targetArcLength = u * arcLengths[il - 1];
  20919. } // binary search for the index with largest value smaller than target u distance
  20920. let low = 0,
  20921. high = il - 1,
  20922. comparison;
  20923. while (low <= high) {
  20924. 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
  20925. comparison = arcLengths[i] - targetArcLength;
  20926. if (comparison < 0) {
  20927. low = i + 1;
  20928. } else if (comparison > 0) {
  20929. high = i - 1;
  20930. } else {
  20931. high = i;
  20932. break; // DONE
  20933. }
  20934. }
  20935. i = high;
  20936. if (arcLengths[i] === targetArcLength) {
  20937. return i / (il - 1);
  20938. } // we could get finer grain at lengths, or use simple interpolation between two points
  20939. const lengthBefore = arcLengths[i];
  20940. const lengthAfter = arcLengths[i + 1];
  20941. const segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points
  20942. const segmentFraction = (targetArcLength - lengthBefore) / segmentLength; // add that fractional amount to t
  20943. const t = (i + segmentFraction) / (il - 1);
  20944. return t;
  20945. } // Returns a unit vector tangent at t
  20946. // In case any sub curve does not implement its tangent derivation,
  20947. // 2 points a small delta apart will be used to find its gradient
  20948. // which seems to give a reasonable approximation
  20949. getTangent(t, optionalTarget) {
  20950. const delta = 0.0001;
  20951. let t1 = t - delta;
  20952. let t2 = t + delta; // Capping in case of danger
  20953. if (t1 < 0) t1 = 0;
  20954. if (t2 > 1) t2 = 1;
  20955. const pt1 = this.getPoint(t1);
  20956. const pt2 = this.getPoint(t2);
  20957. const tangent = optionalTarget || (pt1.isVector2 ? new Vector2() : new Vector3());
  20958. tangent.copy(pt2).sub(pt1).normalize();
  20959. return tangent;
  20960. }
  20961. getTangentAt(u, optionalTarget) {
  20962. const t = this.getUtoTmapping(u);
  20963. return this.getTangent(t, optionalTarget);
  20964. }
  20965. computeFrenetFrames(segments, closed) {
  20966. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  20967. const normal = new Vector3();
  20968. const tangents = [];
  20969. const normals = [];
  20970. const binormals = [];
  20971. const vec = new Vector3();
  20972. const mat = new Matrix4(); // compute the tangent vectors for each segment on the curve
  20973. for (let i = 0; i <= segments; i++) {
  20974. const u = i / segments;
  20975. tangents[i] = this.getTangentAt(u, new Vector3());
  20976. tangents[i].normalize();
  20977. } // select an initial normal vector perpendicular to the first tangent vector,
  20978. // and in the direction of the minimum tangent xyz component
  20979. normals[0] = new Vector3();
  20980. binormals[0] = new Vector3();
  20981. let min = Number.MAX_VALUE;
  20982. const tx = Math.abs(tangents[0].x);
  20983. const ty = Math.abs(tangents[0].y);
  20984. const tz = Math.abs(tangents[0].z);
  20985. if (tx <= min) {
  20986. min = tx;
  20987. normal.set(1, 0, 0);
  20988. }
  20989. if (ty <= min) {
  20990. min = ty;
  20991. normal.set(0, 1, 0);
  20992. }
  20993. if (tz <= min) {
  20994. normal.set(0, 0, 1);
  20995. }
  20996. vec.crossVectors(tangents[0], normal).normalize();
  20997. normals[0].crossVectors(tangents[0], vec);
  20998. binormals[0].crossVectors(tangents[0], normals[0]); // compute the slowly-varying normal and binormal vectors for each segment on the curve
  20999. for (let i = 1; i <= segments; i++) {
  21000. normals[i] = normals[i - 1].clone();
  21001. binormals[i] = binormals[i - 1].clone();
  21002. vec.crossVectors(tangents[i - 1], tangents[i]);
  21003. if (vec.length() > Number.EPSILON) {
  21004. vec.normalize();
  21005. const theta = Math.acos(clamp(tangents[i - 1].dot(tangents[i]), -1, 1)); // clamp for floating pt errors
  21006. normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta));
  21007. }
  21008. binormals[i].crossVectors(tangents[i], normals[i]);
  21009. } // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  21010. if (closed === true) {
  21011. let theta = Math.acos(clamp(normals[0].dot(normals[segments]), -1, 1));
  21012. theta /= segments;
  21013. if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
  21014. theta = -theta;
  21015. }
  21016. for (let i = 1; i <= segments; i++) {
  21017. // twist a little...
  21018. normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i));
  21019. binormals[i].crossVectors(tangents[i], normals[i]);
  21020. }
  21021. }
  21022. return {
  21023. tangents: tangents,
  21024. normals: normals,
  21025. binormals: binormals
  21026. };
  21027. }
  21028. clone() {
  21029. return new this.constructor().copy(this);
  21030. }
  21031. copy(source) {
  21032. this.arcLengthDivisions = source.arcLengthDivisions;
  21033. return this;
  21034. }
  21035. toJSON() {
  21036. const data = {
  21037. metadata: {
  21038. version: 4.5,
  21039. type: 'Curve',
  21040. generator: 'Curve.toJSON'
  21041. }
  21042. };
  21043. data.arcLengthDivisions = this.arcLengthDivisions;
  21044. data.type = this.type;
  21045. return data;
  21046. }
  21047. fromJSON(json) {
  21048. this.arcLengthDivisions = json.arcLengthDivisions;
  21049. return this;
  21050. }
  21051. }
  21052. class EllipseCurve extends Curve {
  21053. constructor(aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0) {
  21054. super();
  21055. this.type = 'EllipseCurve';
  21056. this.aX = aX;
  21057. this.aY = aY;
  21058. this.xRadius = xRadius;
  21059. this.yRadius = yRadius;
  21060. this.aStartAngle = aStartAngle;
  21061. this.aEndAngle = aEndAngle;
  21062. this.aClockwise = aClockwise;
  21063. this.aRotation = aRotation;
  21064. }
  21065. getPoint(t, optionalTarget) {
  21066. const point = optionalTarget || new Vector2();
  21067. const twoPi = Math.PI * 2;
  21068. let deltaAngle = this.aEndAngle - this.aStartAngle;
  21069. const samePoints = Math.abs(deltaAngle) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI
  21070. while (deltaAngle < 0) deltaAngle += twoPi;
  21071. while (deltaAngle > twoPi) deltaAngle -= twoPi;
  21072. if (deltaAngle < Number.EPSILON) {
  21073. if (samePoints) {
  21074. deltaAngle = 0;
  21075. } else {
  21076. deltaAngle = twoPi;
  21077. }
  21078. }
  21079. if (this.aClockwise === true && !samePoints) {
  21080. if (deltaAngle === twoPi) {
  21081. deltaAngle = -twoPi;
  21082. } else {
  21083. deltaAngle = deltaAngle - twoPi;
  21084. }
  21085. }
  21086. const angle = this.aStartAngle + t * deltaAngle;
  21087. let x = this.aX + this.xRadius * Math.cos(angle);
  21088. let y = this.aY + this.yRadius * Math.sin(angle);
  21089. if (this.aRotation !== 0) {
  21090. const cos = Math.cos(this.aRotation);
  21091. const sin = Math.sin(this.aRotation);
  21092. const tx = x - this.aX;
  21093. const ty = y - this.aY; // Rotate the point about the center of the ellipse.
  21094. x = tx * cos - ty * sin + this.aX;
  21095. y = tx * sin + ty * cos + this.aY;
  21096. }
  21097. return point.set(x, y);
  21098. }
  21099. copy(source) {
  21100. super.copy(source);
  21101. this.aX = source.aX;
  21102. this.aY = source.aY;
  21103. this.xRadius = source.xRadius;
  21104. this.yRadius = source.yRadius;
  21105. this.aStartAngle = source.aStartAngle;
  21106. this.aEndAngle = source.aEndAngle;
  21107. this.aClockwise = source.aClockwise;
  21108. this.aRotation = source.aRotation;
  21109. return this;
  21110. }
  21111. toJSON() {
  21112. const data = super.toJSON();
  21113. data.aX = this.aX;
  21114. data.aY = this.aY;
  21115. data.xRadius = this.xRadius;
  21116. data.yRadius = this.yRadius;
  21117. data.aStartAngle = this.aStartAngle;
  21118. data.aEndAngle = this.aEndAngle;
  21119. data.aClockwise = this.aClockwise;
  21120. data.aRotation = this.aRotation;
  21121. return data;
  21122. }
  21123. fromJSON(json) {
  21124. super.fromJSON(json);
  21125. this.aX = json.aX;
  21126. this.aY = json.aY;
  21127. this.xRadius = json.xRadius;
  21128. this.yRadius = json.yRadius;
  21129. this.aStartAngle = json.aStartAngle;
  21130. this.aEndAngle = json.aEndAngle;
  21131. this.aClockwise = json.aClockwise;
  21132. this.aRotation = json.aRotation;
  21133. return this;
  21134. }
  21135. }
  21136. EllipseCurve.prototype.isEllipseCurve = true;
  21137. class ArcCurve extends EllipseCurve {
  21138. constructor(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  21139. super(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  21140. this.type = 'ArcCurve';
  21141. }
  21142. }
  21143. ArcCurve.prototype.isArcCurve = true;
  21144. /**
  21145. * Centripetal CatmullRom Curve - which is useful for avoiding
  21146. * cusps and self-intersections in non-uniform catmull rom curves.
  21147. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  21148. *
  21149. * curve.type accepts centripetal(default), chordal and catmullrom
  21150. * curve.tension is used for catmullrom which defaults to 0.5
  21151. */
  21152. /*
  21153. Based on an optimized c++ solution in
  21154. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  21155. - http://ideone.com/NoEbVM
  21156. This CubicPoly class could be used for reusing some variables and calculations,
  21157. but for three.js curve use, it could be possible inlined and flatten into a single function call
  21158. which can be placed in CurveUtils.
  21159. */
  21160. function CubicPoly() {
  21161. let c0 = 0,
  21162. c1 = 0,
  21163. c2 = 0,
  21164. c3 = 0;
  21165. /*
  21166. * Compute coefficients for a cubic polynomial
  21167. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  21168. * such that
  21169. * p(0) = x0, p(1) = x1
  21170. * and
  21171. * p'(0) = t0, p'(1) = t1.
  21172. */
  21173. function init(x0, x1, t0, t1) {
  21174. c0 = x0;
  21175. c1 = t0;
  21176. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  21177. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  21178. }
  21179. return {
  21180. initCatmullRom: function (x0, x1, x2, x3, tension) {
  21181. init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
  21182. },
  21183. initNonuniformCatmullRom: function (x0, x1, x2, x3, dt0, dt1, dt2) {
  21184. // compute tangents when parameterized in [t1,t2]
  21185. let t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
  21186. let t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; // rescale tangents for parametrization in [0,1]
  21187. t1 *= dt1;
  21188. t2 *= dt1;
  21189. init(x1, x2, t1, t2);
  21190. },
  21191. calc: function (t) {
  21192. const t2 = t * t;
  21193. const t3 = t2 * t;
  21194. return c0 + c1 * t + c2 * t2 + c3 * t3;
  21195. }
  21196. };
  21197. } //
  21198. const tmp = new Vector3();
  21199. const px = new CubicPoly(),
  21200. py = new CubicPoly(),
  21201. pz = new CubicPoly();
  21202. class CatmullRomCurve3 extends Curve {
  21203. constructor(points = [], closed = false, curveType = 'centripetal', tension = 0.5) {
  21204. super();
  21205. this.type = 'CatmullRomCurve3';
  21206. this.points = points;
  21207. this.closed = closed;
  21208. this.curveType = curveType;
  21209. this.tension = tension;
  21210. }
  21211. getPoint(t, optionalTarget = new Vector3()) {
  21212. const point = optionalTarget;
  21213. const points = this.points;
  21214. const l = points.length;
  21215. const p = (l - (this.closed ? 0 : 1)) * t;
  21216. let intPoint = Math.floor(p);
  21217. let weight = p - intPoint;
  21218. if (this.closed) {
  21219. intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;
  21220. } else if (weight === 0 && intPoint === l - 1) {
  21221. intPoint = l - 2;
  21222. weight = 1;
  21223. }
  21224. let p0, p3; // 4 points (p1 & p2 defined below)
  21225. if (this.closed || intPoint > 0) {
  21226. p0 = points[(intPoint - 1) % l];
  21227. } else {
  21228. // extrapolate first point
  21229. tmp.subVectors(points[0], points[1]).add(points[0]);
  21230. p0 = tmp;
  21231. }
  21232. const p1 = points[intPoint % l];
  21233. const p2 = points[(intPoint + 1) % l];
  21234. if (this.closed || intPoint + 2 < l) {
  21235. p3 = points[(intPoint + 2) % l];
  21236. } else {
  21237. // extrapolate last point
  21238. tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
  21239. p3 = tmp;
  21240. }
  21241. if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
  21242. // init Centripetal / Chordal Catmull-Rom
  21243. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  21244. let dt0 = Math.pow(p0.distanceToSquared(p1), pow);
  21245. let dt1 = Math.pow(p1.distanceToSquared(p2), pow);
  21246. let dt2 = Math.pow(p2.distanceToSquared(p3), pow); // safety check for repeated points
  21247. if (dt1 < 1e-4) dt1 = 1.0;
  21248. if (dt0 < 1e-4) dt0 = dt1;
  21249. if (dt2 < 1e-4) dt2 = dt1;
  21250. px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);
  21251. py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);
  21252. pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);
  21253. } else if (this.curveType === 'catmullrom') {
  21254. px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);
  21255. py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);
  21256. pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);
  21257. }
  21258. point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
  21259. return point;
  21260. }
  21261. copy(source) {
  21262. super.copy(source);
  21263. this.points = [];
  21264. for (let i = 0, l = source.points.length; i < l; i++) {
  21265. const point = source.points[i];
  21266. this.points.push(point.clone());
  21267. }
  21268. this.closed = source.closed;
  21269. this.curveType = source.curveType;
  21270. this.tension = source.tension;
  21271. return this;
  21272. }
  21273. toJSON() {
  21274. const data = super.toJSON();
  21275. data.points = [];
  21276. for (let i = 0, l = this.points.length; i < l; i++) {
  21277. const point = this.points[i];
  21278. data.points.push(point.toArray());
  21279. }
  21280. data.closed = this.closed;
  21281. data.curveType = this.curveType;
  21282. data.tension = this.tension;
  21283. return data;
  21284. }
  21285. fromJSON(json) {
  21286. super.fromJSON(json);
  21287. this.points = [];
  21288. for (let i = 0, l = json.points.length; i < l; i++) {
  21289. const point = json.points[i];
  21290. this.points.push(new Vector3().fromArray(point));
  21291. }
  21292. this.closed = json.closed;
  21293. this.curveType = json.curveType;
  21294. this.tension = json.tension;
  21295. return this;
  21296. }
  21297. }
  21298. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  21299. /**
  21300. * Bezier Curves formulas obtained from
  21301. * http://en.wikipedia.org/wiki/Bézier_curve
  21302. */
  21303. function CatmullRom(t, p0, p1, p2, p3) {
  21304. const v0 = (p2 - p0) * 0.5;
  21305. const v1 = (p3 - p1) * 0.5;
  21306. const t2 = t * t;
  21307. const t3 = t * t2;
  21308. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  21309. } //
  21310. function QuadraticBezierP0(t, p) {
  21311. const k = 1 - t;
  21312. return k * k * p;
  21313. }
  21314. function QuadraticBezierP1(t, p) {
  21315. return 2 * (1 - t) * t * p;
  21316. }
  21317. function QuadraticBezierP2(t, p) {
  21318. return t * t * p;
  21319. }
  21320. function QuadraticBezier(t, p0, p1, p2) {
  21321. return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);
  21322. } //
  21323. function CubicBezierP0(t, p) {
  21324. const k = 1 - t;
  21325. return k * k * k * p;
  21326. }
  21327. function CubicBezierP1(t, p) {
  21328. const k = 1 - t;
  21329. return 3 * k * k * t * p;
  21330. }
  21331. function CubicBezierP2(t, p) {
  21332. return 3 * (1 - t) * t * t * p;
  21333. }
  21334. function CubicBezierP3(t, p) {
  21335. return t * t * t * p;
  21336. }
  21337. function CubicBezier(t, p0, p1, p2, p3) {
  21338. return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);
  21339. }
  21340. class CubicBezierCurve extends Curve {
  21341. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2()) {
  21342. super();
  21343. this.type = 'CubicBezierCurve';
  21344. this.v0 = v0;
  21345. this.v1 = v1;
  21346. this.v2 = v2;
  21347. this.v3 = v3;
  21348. }
  21349. getPoint(t, optionalTarget = new Vector2()) {
  21350. const point = optionalTarget;
  21351. const v0 = this.v0,
  21352. v1 = this.v1,
  21353. v2 = this.v2,
  21354. v3 = this.v3;
  21355. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
  21356. return point;
  21357. }
  21358. copy(source) {
  21359. super.copy(source);
  21360. this.v0.copy(source.v0);
  21361. this.v1.copy(source.v1);
  21362. this.v2.copy(source.v2);
  21363. this.v3.copy(source.v3);
  21364. return this;
  21365. }
  21366. toJSON() {
  21367. const data = super.toJSON();
  21368. data.v0 = this.v0.toArray();
  21369. data.v1 = this.v1.toArray();
  21370. data.v2 = this.v2.toArray();
  21371. data.v3 = this.v3.toArray();
  21372. return data;
  21373. }
  21374. fromJSON(json) {
  21375. super.fromJSON(json);
  21376. this.v0.fromArray(json.v0);
  21377. this.v1.fromArray(json.v1);
  21378. this.v2.fromArray(json.v2);
  21379. this.v3.fromArray(json.v3);
  21380. return this;
  21381. }
  21382. }
  21383. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  21384. class CubicBezierCurve3 extends Curve {
  21385. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3()) {
  21386. super();
  21387. this.type = 'CubicBezierCurve3';
  21388. this.v0 = v0;
  21389. this.v1 = v1;
  21390. this.v2 = v2;
  21391. this.v3 = v3;
  21392. }
  21393. getPoint(t, optionalTarget = new Vector3()) {
  21394. const point = optionalTarget;
  21395. const v0 = this.v0,
  21396. v1 = this.v1,
  21397. v2 = this.v2,
  21398. v3 = this.v3;
  21399. 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));
  21400. return point;
  21401. }
  21402. copy(source) {
  21403. super.copy(source);
  21404. this.v0.copy(source.v0);
  21405. this.v1.copy(source.v1);
  21406. this.v2.copy(source.v2);
  21407. this.v3.copy(source.v3);
  21408. return this;
  21409. }
  21410. toJSON() {
  21411. const data = super.toJSON();
  21412. data.v0 = this.v0.toArray();
  21413. data.v1 = this.v1.toArray();
  21414. data.v2 = this.v2.toArray();
  21415. data.v3 = this.v3.toArray();
  21416. return data;
  21417. }
  21418. fromJSON(json) {
  21419. super.fromJSON(json);
  21420. this.v0.fromArray(json.v0);
  21421. this.v1.fromArray(json.v1);
  21422. this.v2.fromArray(json.v2);
  21423. this.v3.fromArray(json.v3);
  21424. return this;
  21425. }
  21426. }
  21427. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  21428. class LineCurve extends Curve {
  21429. constructor(v1 = new Vector2(), v2 = new Vector2()) {
  21430. super();
  21431. this.type = 'LineCurve';
  21432. this.v1 = v1;
  21433. this.v2 = v2;
  21434. }
  21435. getPoint(t, optionalTarget = new Vector2()) {
  21436. const point = optionalTarget;
  21437. if (t === 1) {
  21438. point.copy(this.v2);
  21439. } else {
  21440. point.copy(this.v2).sub(this.v1);
  21441. point.multiplyScalar(t).add(this.v1);
  21442. }
  21443. return point;
  21444. } // Line curve is linear, so we can overwrite default getPointAt
  21445. getPointAt(u, optionalTarget) {
  21446. return this.getPoint(u, optionalTarget);
  21447. }
  21448. getTangent(t, optionalTarget) {
  21449. const tangent = optionalTarget || new Vector2();
  21450. tangent.copy(this.v2).sub(this.v1).normalize();
  21451. return tangent;
  21452. }
  21453. copy(source) {
  21454. super.copy(source);
  21455. this.v1.copy(source.v1);
  21456. this.v2.copy(source.v2);
  21457. return this;
  21458. }
  21459. toJSON() {
  21460. const data = super.toJSON();
  21461. data.v1 = this.v1.toArray();
  21462. data.v2 = this.v2.toArray();
  21463. return data;
  21464. }
  21465. fromJSON(json) {
  21466. super.fromJSON(json);
  21467. this.v1.fromArray(json.v1);
  21468. this.v2.fromArray(json.v2);
  21469. return this;
  21470. }
  21471. }
  21472. LineCurve.prototype.isLineCurve = true;
  21473. class LineCurve3 extends Curve {
  21474. constructor(v1 = new Vector3(), v2 = new Vector3()) {
  21475. super();
  21476. this.type = 'LineCurve3';
  21477. this.isLineCurve3 = true;
  21478. this.v1 = v1;
  21479. this.v2 = v2;
  21480. }
  21481. getPoint(t, optionalTarget = new Vector3()) {
  21482. const point = optionalTarget;
  21483. if (t === 1) {
  21484. point.copy(this.v2);
  21485. } else {
  21486. point.copy(this.v2).sub(this.v1);
  21487. point.multiplyScalar(t).add(this.v1);
  21488. }
  21489. return point;
  21490. } // Line curve is linear, so we can overwrite default getPointAt
  21491. getPointAt(u, optionalTarget) {
  21492. return this.getPoint(u, optionalTarget);
  21493. }
  21494. copy(source) {
  21495. super.copy(source);
  21496. this.v1.copy(source.v1);
  21497. this.v2.copy(source.v2);
  21498. return this;
  21499. }
  21500. toJSON() {
  21501. const data = super.toJSON();
  21502. data.v1 = this.v1.toArray();
  21503. data.v2 = this.v2.toArray();
  21504. return data;
  21505. }
  21506. fromJSON(json) {
  21507. super.fromJSON(json);
  21508. this.v1.fromArray(json.v1);
  21509. this.v2.fromArray(json.v2);
  21510. return this;
  21511. }
  21512. }
  21513. class QuadraticBezierCurve extends Curve {
  21514. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2()) {
  21515. super();
  21516. this.type = 'QuadraticBezierCurve';
  21517. this.v0 = v0;
  21518. this.v1 = v1;
  21519. this.v2 = v2;
  21520. }
  21521. getPoint(t, optionalTarget = new Vector2()) {
  21522. const point = optionalTarget;
  21523. const v0 = this.v0,
  21524. v1 = this.v1,
  21525. v2 = this.v2;
  21526. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
  21527. return point;
  21528. }
  21529. copy(source) {
  21530. super.copy(source);
  21531. this.v0.copy(source.v0);
  21532. this.v1.copy(source.v1);
  21533. this.v2.copy(source.v2);
  21534. return this;
  21535. }
  21536. toJSON() {
  21537. const data = super.toJSON();
  21538. data.v0 = this.v0.toArray();
  21539. data.v1 = this.v1.toArray();
  21540. data.v2 = this.v2.toArray();
  21541. return data;
  21542. }
  21543. fromJSON(json) {
  21544. super.fromJSON(json);
  21545. this.v0.fromArray(json.v0);
  21546. this.v1.fromArray(json.v1);
  21547. this.v2.fromArray(json.v2);
  21548. return this;
  21549. }
  21550. }
  21551. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  21552. class QuadraticBezierCurve3 extends Curve {
  21553. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3()) {
  21554. super();
  21555. this.type = 'QuadraticBezierCurve3';
  21556. this.v0 = v0;
  21557. this.v1 = v1;
  21558. this.v2 = v2;
  21559. }
  21560. getPoint(t, optionalTarget = new Vector3()) {
  21561. const point = optionalTarget;
  21562. const v0 = this.v0,
  21563. v1 = this.v1,
  21564. v2 = this.v2;
  21565. 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));
  21566. return point;
  21567. }
  21568. copy(source) {
  21569. super.copy(source);
  21570. this.v0.copy(source.v0);
  21571. this.v1.copy(source.v1);
  21572. this.v2.copy(source.v2);
  21573. return this;
  21574. }
  21575. toJSON() {
  21576. const data = super.toJSON();
  21577. data.v0 = this.v0.toArray();
  21578. data.v1 = this.v1.toArray();
  21579. data.v2 = this.v2.toArray();
  21580. return data;
  21581. }
  21582. fromJSON(json) {
  21583. super.fromJSON(json);
  21584. this.v0.fromArray(json.v0);
  21585. this.v1.fromArray(json.v1);
  21586. this.v2.fromArray(json.v2);
  21587. return this;
  21588. }
  21589. }
  21590. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  21591. class SplineCurve extends Curve {
  21592. constructor(points = []) {
  21593. super();
  21594. this.type = 'SplineCurve';
  21595. this.points = points;
  21596. }
  21597. getPoint(t, optionalTarget = new Vector2()) {
  21598. const point = optionalTarget;
  21599. const points = this.points;
  21600. const p = (points.length - 1) * t;
  21601. const intPoint = Math.floor(p);
  21602. const weight = p - intPoint;
  21603. const p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
  21604. const p1 = points[intPoint];
  21605. const p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
  21606. const p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
  21607. point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
  21608. return point;
  21609. }
  21610. copy(source) {
  21611. super.copy(source);
  21612. this.points = [];
  21613. for (let i = 0, l = source.points.length; i < l; i++) {
  21614. const point = source.points[i];
  21615. this.points.push(point.clone());
  21616. }
  21617. return this;
  21618. }
  21619. toJSON() {
  21620. const data = super.toJSON();
  21621. data.points = [];
  21622. for (let i = 0, l = this.points.length; i < l; i++) {
  21623. const point = this.points[i];
  21624. data.points.push(point.toArray());
  21625. }
  21626. return data;
  21627. }
  21628. fromJSON(json) {
  21629. super.fromJSON(json);
  21630. this.points = [];
  21631. for (let i = 0, l = json.points.length; i < l; i++) {
  21632. const point = json.points[i];
  21633. this.points.push(new Vector2().fromArray(point));
  21634. }
  21635. return this;
  21636. }
  21637. }
  21638. SplineCurve.prototype.isSplineCurve = true;
  21639. var Curves = /*#__PURE__*/Object.freeze({
  21640. __proto__: null,
  21641. ArcCurve: ArcCurve,
  21642. CatmullRomCurve3: CatmullRomCurve3,
  21643. CubicBezierCurve: CubicBezierCurve,
  21644. CubicBezierCurve3: CubicBezierCurve3,
  21645. EllipseCurve: EllipseCurve,
  21646. LineCurve: LineCurve,
  21647. LineCurve3: LineCurve3,
  21648. QuadraticBezierCurve: QuadraticBezierCurve,
  21649. QuadraticBezierCurve3: QuadraticBezierCurve3,
  21650. SplineCurve: SplineCurve
  21651. });
  21652. /**************************************************************
  21653. * Curved Path - a curve path is simply a array of connected
  21654. * curves, but retains the api of a curve
  21655. **************************************************************/
  21656. class CurvePath extends Curve {
  21657. constructor() {
  21658. super();
  21659. this.type = 'CurvePath';
  21660. this.curves = [];
  21661. this.autoClose = false; // Automatically closes the path
  21662. }
  21663. add(curve) {
  21664. this.curves.push(curve);
  21665. }
  21666. closePath() {
  21667. // Add a line curve if start and end of lines are not connected
  21668. const startPoint = this.curves[0].getPoint(0);
  21669. const endPoint = this.curves[this.curves.length - 1].getPoint(1);
  21670. if (!startPoint.equals(endPoint)) {
  21671. this.curves.push(new LineCurve(endPoint, startPoint));
  21672. }
  21673. } // To get accurate point with reference to
  21674. // entire path distance at time t,
  21675. // following has to be done:
  21676. // 1. Length of each sub path have to be known
  21677. // 2. Locate and identify type of curve
  21678. // 3. Get t for the curve
  21679. // 4. Return curve.getPointAt(t')
  21680. getPoint(t) {
  21681. const d = t * this.getLength();
  21682. const curveLengths = this.getCurveLengths();
  21683. let i = 0; // To think about boundaries points.
  21684. while (i < curveLengths.length) {
  21685. if (curveLengths[i] >= d) {
  21686. const diff = curveLengths[i] - d;
  21687. const curve = this.curves[i];
  21688. const segmentLength = curve.getLength();
  21689. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  21690. return curve.getPointAt(u);
  21691. }
  21692. i++;
  21693. }
  21694. return null; // loop where sum != 0, sum > d , sum+1 <d
  21695. } // We cannot use the default THREE.Curve getPoint() with getLength() because in
  21696. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  21697. // getPoint() depends on getLength
  21698. getLength() {
  21699. const lens = this.getCurveLengths();
  21700. return lens[lens.length - 1];
  21701. } // cacheLengths must be recalculated.
  21702. updateArcLengths() {
  21703. this.needsUpdate = true;
  21704. this.cacheLengths = null;
  21705. this.getCurveLengths();
  21706. } // Compute lengths and cache them
  21707. // We cannot overwrite getLengths() because UtoT mapping uses it.
  21708. getCurveLengths() {
  21709. // We use cache values if curves and cache array are same length
  21710. if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
  21711. return this.cacheLengths;
  21712. } // Get length of sub-curve
  21713. // Push sums into cached array
  21714. const lengths = [];
  21715. let sums = 0;
  21716. for (let i = 0, l = this.curves.length; i < l; i++) {
  21717. sums += this.curves[i].getLength();
  21718. lengths.push(sums);
  21719. }
  21720. this.cacheLengths = lengths;
  21721. return lengths;
  21722. }
  21723. getSpacedPoints(divisions = 40) {
  21724. const points = [];
  21725. for (let i = 0; i <= divisions; i++) {
  21726. points.push(this.getPoint(i / divisions));
  21727. }
  21728. if (this.autoClose) {
  21729. points.push(points[0]);
  21730. }
  21731. return points;
  21732. }
  21733. getPoints(divisions = 12) {
  21734. const points = [];
  21735. let last;
  21736. for (let i = 0, curves = this.curves; i < curves.length; i++) {
  21737. const curve = curves[i];
  21738. const resolution = curve && curve.isEllipseCurve ? divisions * 2 : curve && (curve.isLineCurve || curve.isLineCurve3) ? 1 : curve && curve.isSplineCurve ? divisions * curve.points.length : divisions;
  21739. const pts = curve.getPoints(resolution);
  21740. for (let j = 0; j < pts.length; j++) {
  21741. const point = pts[j];
  21742. if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
  21743. points.push(point);
  21744. last = point;
  21745. }
  21746. }
  21747. if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
  21748. points.push(points[0]);
  21749. }
  21750. return points;
  21751. }
  21752. copy(source) {
  21753. super.copy(source);
  21754. this.curves = [];
  21755. for (let i = 0, l = source.curves.length; i < l; i++) {
  21756. const curve = source.curves[i];
  21757. this.curves.push(curve.clone());
  21758. }
  21759. this.autoClose = source.autoClose;
  21760. return this;
  21761. }
  21762. toJSON() {
  21763. const data = super.toJSON();
  21764. data.autoClose = this.autoClose;
  21765. data.curves = [];
  21766. for (let i = 0, l = this.curves.length; i < l; i++) {
  21767. const curve = this.curves[i];
  21768. data.curves.push(curve.toJSON());
  21769. }
  21770. return data;
  21771. }
  21772. fromJSON(json) {
  21773. super.fromJSON(json);
  21774. this.autoClose = json.autoClose;
  21775. this.curves = [];
  21776. for (let i = 0, l = json.curves.length; i < l; i++) {
  21777. const curve = json.curves[i];
  21778. this.curves.push(new Curves[curve.type]().fromJSON(curve));
  21779. }
  21780. return this;
  21781. }
  21782. }
  21783. class Path extends CurvePath {
  21784. constructor(points) {
  21785. super();
  21786. this.type = 'Path';
  21787. this.currentPoint = new Vector2();
  21788. if (points) {
  21789. this.setFromPoints(points);
  21790. }
  21791. }
  21792. setFromPoints(points) {
  21793. this.moveTo(points[0].x, points[0].y);
  21794. for (let i = 1, l = points.length; i < l; i++) {
  21795. this.lineTo(points[i].x, points[i].y);
  21796. }
  21797. return this;
  21798. }
  21799. moveTo(x, y) {
  21800. this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
  21801. return this;
  21802. }
  21803. lineTo(x, y) {
  21804. const curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));
  21805. this.curves.push(curve);
  21806. this.currentPoint.set(x, y);
  21807. return this;
  21808. }
  21809. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  21810. const curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));
  21811. this.curves.push(curve);
  21812. this.currentPoint.set(aX, aY);
  21813. return this;
  21814. }
  21815. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  21816. const curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));
  21817. this.curves.push(curve);
  21818. this.currentPoint.set(aX, aY);
  21819. return this;
  21820. }
  21821. splineThru(pts
  21822. /*Array of Vector*/
  21823. ) {
  21824. const npts = [this.currentPoint.clone()].concat(pts);
  21825. const curve = new SplineCurve(npts);
  21826. this.curves.push(curve);
  21827. this.currentPoint.copy(pts[pts.length - 1]);
  21828. return this;
  21829. }
  21830. arc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  21831. const x0 = this.currentPoint.x;
  21832. const y0 = this.currentPoint.y;
  21833. this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);
  21834. return this;
  21835. }
  21836. absarc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  21837. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  21838. return this;
  21839. }
  21840. ellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  21841. const x0 = this.currentPoint.x;
  21842. const y0 = this.currentPoint.y;
  21843. this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  21844. return this;
  21845. }
  21846. absellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  21847. const curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  21848. if (this.curves.length > 0) {
  21849. // if a previous curve is present, attempt to join
  21850. const firstPoint = curve.getPoint(0);
  21851. if (!firstPoint.equals(this.currentPoint)) {
  21852. this.lineTo(firstPoint.x, firstPoint.y);
  21853. }
  21854. }
  21855. this.curves.push(curve);
  21856. const lastPoint = curve.getPoint(1);
  21857. this.currentPoint.copy(lastPoint);
  21858. return this;
  21859. }
  21860. copy(source) {
  21861. super.copy(source);
  21862. this.currentPoint.copy(source.currentPoint);
  21863. return this;
  21864. }
  21865. toJSON() {
  21866. const data = super.toJSON();
  21867. data.currentPoint = this.currentPoint.toArray();
  21868. return data;
  21869. }
  21870. fromJSON(json) {
  21871. super.fromJSON(json);
  21872. this.currentPoint.fromArray(json.currentPoint);
  21873. return this;
  21874. }
  21875. }
  21876. class Shape extends Path {
  21877. constructor(points) {
  21878. super(points);
  21879. this.uuid = generateUUID();
  21880. this.type = 'Shape';
  21881. this.holes = [];
  21882. }
  21883. getPointsHoles(divisions) {
  21884. const holesPts = [];
  21885. for (let i = 0, l = this.holes.length; i < l; i++) {
  21886. holesPts[i] = this.holes[i].getPoints(divisions);
  21887. }
  21888. return holesPts;
  21889. } // get points of shape and holes (keypoints based on segments parameter)
  21890. extractPoints(divisions) {
  21891. return {
  21892. shape: this.getPoints(divisions),
  21893. holes: this.getPointsHoles(divisions)
  21894. };
  21895. }
  21896. copy(source) {
  21897. super.copy(source);
  21898. this.holes = [];
  21899. for (let i = 0, l = source.holes.length; i < l; i++) {
  21900. const hole = source.holes[i];
  21901. this.holes.push(hole.clone());
  21902. }
  21903. return this;
  21904. }
  21905. toJSON() {
  21906. const data = super.toJSON();
  21907. data.uuid = this.uuid;
  21908. data.holes = [];
  21909. for (let i = 0, l = this.holes.length; i < l; i++) {
  21910. const hole = this.holes[i];
  21911. data.holes.push(hole.toJSON());
  21912. }
  21913. return data;
  21914. }
  21915. fromJSON(json) {
  21916. super.fromJSON(json);
  21917. this.uuid = json.uuid;
  21918. this.holes = [];
  21919. for (let i = 0, l = json.holes.length; i < l; i++) {
  21920. const hole = json.holes[i];
  21921. this.holes.push(new Path().fromJSON(hole));
  21922. }
  21923. return this;
  21924. }
  21925. }
  21926. class Light extends Object3D {
  21927. constructor(color, intensity = 1) {
  21928. super();
  21929. this.type = 'Light';
  21930. this.color = new Color(color);
  21931. this.intensity = intensity;
  21932. }
  21933. dispose() {// Empty here in base class; some subclasses override.
  21934. }
  21935. copy(source) {
  21936. super.copy(source);
  21937. this.color.copy(source.color);
  21938. this.intensity = source.intensity;
  21939. return this;
  21940. }
  21941. toJSON(meta) {
  21942. const data = super.toJSON(meta);
  21943. data.object.color = this.color.getHex();
  21944. data.object.intensity = this.intensity;
  21945. if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
  21946. if (this.distance !== undefined) data.object.distance = this.distance;
  21947. if (this.angle !== undefined) data.object.angle = this.angle;
  21948. if (this.decay !== undefined) data.object.decay = this.decay;
  21949. if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
  21950. if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
  21951. return data;
  21952. }
  21953. }
  21954. Light.prototype.isLight = true;
  21955. class HemisphereLight extends Light {
  21956. constructor(skyColor, groundColor, intensity) {
  21957. super(skyColor, intensity);
  21958. this.type = 'HemisphereLight';
  21959. this.position.copy(Object3D.DefaultUp);
  21960. this.updateMatrix();
  21961. this.groundColor = new Color(groundColor);
  21962. }
  21963. copy(source) {
  21964. Light.prototype.copy.call(this, source);
  21965. this.groundColor.copy(source.groundColor);
  21966. return this;
  21967. }
  21968. }
  21969. HemisphereLight.prototype.isHemisphereLight = true;
  21970. const _projScreenMatrix$1 = /*@__PURE__*/new Matrix4();
  21971. const _lightPositionWorld$1 = /*@__PURE__*/new Vector3();
  21972. const _lookTarget$1 = /*@__PURE__*/new Vector3();
  21973. class LightShadow {
  21974. constructor(camera) {
  21975. this.camera = camera;
  21976. this.bias = 0;
  21977. this.normalBias = 0;
  21978. this.radius = 1;
  21979. this.mapSize = new Vector2(512, 512);
  21980. this.map = null;
  21981. this.mapPass = null;
  21982. this.matrix = new Matrix4();
  21983. this.autoUpdate = true;
  21984. this.needsUpdate = false;
  21985. this._frustum = new Frustum();
  21986. this._frameExtents = new Vector2(1, 1);
  21987. this._viewportCount = 1;
  21988. this._viewports = [new Vector4(0, 0, 1, 1)];
  21989. }
  21990. getViewportCount() {
  21991. return this._viewportCount;
  21992. }
  21993. getFrustum() {
  21994. return this._frustum;
  21995. }
  21996. updateMatrices(light) {
  21997. const shadowCamera = this.camera;
  21998. const shadowMatrix = this.matrix;
  21999. _lightPositionWorld$1.setFromMatrixPosition(light.matrixWorld);
  22000. shadowCamera.position.copy(_lightPositionWorld$1);
  22001. _lookTarget$1.setFromMatrixPosition(light.target.matrixWorld);
  22002. shadowCamera.lookAt(_lookTarget$1);
  22003. shadowCamera.updateMatrixWorld();
  22004. _projScreenMatrix$1.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
  22005. this._frustum.setFromProjectionMatrix(_projScreenMatrix$1);
  22006. 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);
  22007. shadowMatrix.multiply(shadowCamera.projectionMatrix);
  22008. shadowMatrix.multiply(shadowCamera.matrixWorldInverse);
  22009. }
  22010. getViewport(viewportIndex) {
  22011. return this._viewports[viewportIndex];
  22012. }
  22013. getFrameExtents() {
  22014. return this._frameExtents;
  22015. }
  22016. dispose() {
  22017. if (this.map) {
  22018. this.map.dispose();
  22019. }
  22020. if (this.mapPass) {
  22021. this.mapPass.dispose();
  22022. }
  22023. }
  22024. copy(source) {
  22025. this.camera = source.camera.clone();
  22026. this.bias = source.bias;
  22027. this.radius = source.radius;
  22028. this.mapSize.copy(source.mapSize);
  22029. return this;
  22030. }
  22031. clone() {
  22032. return new this.constructor().copy(this);
  22033. }
  22034. toJSON() {
  22035. const object = {};
  22036. if (this.bias !== 0) object.bias = this.bias;
  22037. if (this.normalBias !== 0) object.normalBias = this.normalBias;
  22038. if (this.radius !== 1) object.radius = this.radius;
  22039. if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
  22040. object.camera = this.camera.toJSON(false).object;
  22041. delete object.camera.matrix;
  22042. return object;
  22043. }
  22044. }
  22045. class SpotLightShadow extends LightShadow {
  22046. constructor() {
  22047. super(new PerspectiveCamera(50, 1, 0.5, 500));
  22048. this.focus = 1;
  22049. }
  22050. updateMatrices(light) {
  22051. const camera = this.camera;
  22052. const fov = RAD2DEG * 2 * light.angle * this.focus;
  22053. const aspect = this.mapSize.width / this.mapSize.height;
  22054. const far = light.distance || camera.far;
  22055. if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
  22056. camera.fov = fov;
  22057. camera.aspect = aspect;
  22058. camera.far = far;
  22059. camera.updateProjectionMatrix();
  22060. }
  22061. super.updateMatrices(light);
  22062. }
  22063. copy(source) {
  22064. super.copy(source);
  22065. this.focus = source.focus;
  22066. return this;
  22067. }
  22068. }
  22069. SpotLightShadow.prototype.isSpotLightShadow = true;
  22070. class SpotLight extends Light {
  22071. constructor(color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 1) {
  22072. super(color, intensity);
  22073. this.type = 'SpotLight';
  22074. this.position.copy(Object3D.DefaultUp);
  22075. this.updateMatrix();
  22076. this.target = new Object3D();
  22077. this.distance = distance;
  22078. this.angle = angle;
  22079. this.penumbra = penumbra;
  22080. this.decay = decay; // for physically correct lights, should be 2.
  22081. this.shadow = new SpotLightShadow();
  22082. }
  22083. get power() {
  22084. // intensity = power per solid angle.
  22085. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  22086. return this.intensity * Math.PI;
  22087. }
  22088. set power(power) {
  22089. // intensity = power per solid angle.
  22090. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  22091. this.intensity = power / Math.PI;
  22092. }
  22093. dispose() {
  22094. this.shadow.dispose();
  22095. }
  22096. copy(source) {
  22097. super.copy(source);
  22098. this.distance = source.distance;
  22099. this.angle = source.angle;
  22100. this.penumbra = source.penumbra;
  22101. this.decay = source.decay;
  22102. this.target = source.target.clone();
  22103. this.shadow = source.shadow.clone();
  22104. return this;
  22105. }
  22106. }
  22107. SpotLight.prototype.isSpotLight = true;
  22108. const _projScreenMatrix = /*@__PURE__*/new Matrix4();
  22109. const _lightPositionWorld = /*@__PURE__*/new Vector3();
  22110. const _lookTarget = /*@__PURE__*/new Vector3();
  22111. class PointLightShadow extends LightShadow {
  22112. constructor() {
  22113. super(new PerspectiveCamera(90, 1, 0.5, 500));
  22114. this._frameExtents = new Vector2(4, 2);
  22115. this._viewportCount = 6;
  22116. this._viewports = [// These viewports map a cube-map onto a 2D texture with the
  22117. // following orientation:
  22118. //
  22119. // xzXZ
  22120. // y Y
  22121. //
  22122. // X - Positive x direction
  22123. // x - Negative x direction
  22124. // Y - Positive y direction
  22125. // y - Negative y direction
  22126. // Z - Positive z direction
  22127. // z - Negative z direction
  22128. // positive X
  22129. new Vector4(2, 1, 1, 1), // negative X
  22130. new Vector4(0, 1, 1, 1), // positive Z
  22131. new Vector4(3, 1, 1, 1), // negative Z
  22132. new Vector4(1, 1, 1, 1), // positive Y
  22133. new Vector4(3, 0, 1, 1), // negative Y
  22134. new Vector4(1, 0, 1, 1)];
  22135. 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)];
  22136. 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)];
  22137. }
  22138. updateMatrices(light, viewportIndex = 0) {
  22139. const camera = this.camera;
  22140. const shadowMatrix = this.matrix;
  22141. const far = light.distance || camera.far;
  22142. if (far !== camera.far) {
  22143. camera.far = far;
  22144. camera.updateProjectionMatrix();
  22145. }
  22146. _lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  22147. camera.position.copy(_lightPositionWorld);
  22148. _lookTarget.copy(camera.position);
  22149. _lookTarget.add(this._cubeDirections[viewportIndex]);
  22150. camera.up.copy(this._cubeUps[viewportIndex]);
  22151. camera.lookAt(_lookTarget);
  22152. camera.updateMatrixWorld();
  22153. shadowMatrix.makeTranslation(-_lightPositionWorld.x, -_lightPositionWorld.y, -_lightPositionWorld.z);
  22154. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  22155. this._frustum.setFromProjectionMatrix(_projScreenMatrix);
  22156. }
  22157. }
  22158. PointLightShadow.prototype.isPointLightShadow = true;
  22159. class PointLight extends Light {
  22160. constructor(color, intensity, distance = 0, decay = 1) {
  22161. super(color, intensity);
  22162. this.type = 'PointLight';
  22163. this.distance = distance;
  22164. this.decay = decay; // for physically correct lights, should be 2.
  22165. this.shadow = new PointLightShadow();
  22166. }
  22167. get power() {
  22168. // intensity = power per solid angle.
  22169. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  22170. return this.intensity * 4 * Math.PI;
  22171. }
  22172. set power(power) {
  22173. // intensity = power per solid angle.
  22174. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  22175. this.intensity = power / (4 * Math.PI);
  22176. }
  22177. dispose() {
  22178. this.shadow.dispose();
  22179. }
  22180. copy(source) {
  22181. super.copy(source);
  22182. this.distance = source.distance;
  22183. this.decay = source.decay;
  22184. this.shadow = source.shadow.clone();
  22185. return this;
  22186. }
  22187. }
  22188. PointLight.prototype.isPointLight = true;
  22189. class OrthographicCamera extends Camera {
  22190. constructor(left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000) {
  22191. super();
  22192. this.type = 'OrthographicCamera';
  22193. this.zoom = 1;
  22194. this.view = null;
  22195. this.left = left;
  22196. this.right = right;
  22197. this.top = top;
  22198. this.bottom = bottom;
  22199. this.near = near;
  22200. this.far = far;
  22201. this.updateProjectionMatrix();
  22202. }
  22203. copy(source, recursive) {
  22204. super.copy(source, recursive);
  22205. this.left = source.left;
  22206. this.right = source.right;
  22207. this.top = source.top;
  22208. this.bottom = source.bottom;
  22209. this.near = source.near;
  22210. this.far = source.far;
  22211. this.zoom = source.zoom;
  22212. this.view = source.view === null ? null : Object.assign({}, source.view);
  22213. return this;
  22214. }
  22215. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  22216. if (this.view === null) {
  22217. this.view = {
  22218. enabled: true,
  22219. fullWidth: 1,
  22220. fullHeight: 1,
  22221. offsetX: 0,
  22222. offsetY: 0,
  22223. width: 1,
  22224. height: 1
  22225. };
  22226. }
  22227. this.view.enabled = true;
  22228. this.view.fullWidth = fullWidth;
  22229. this.view.fullHeight = fullHeight;
  22230. this.view.offsetX = x;
  22231. this.view.offsetY = y;
  22232. this.view.width = width;
  22233. this.view.height = height;
  22234. this.updateProjectionMatrix();
  22235. }
  22236. clearViewOffset() {
  22237. if (this.view !== null) {
  22238. this.view.enabled = false;
  22239. }
  22240. this.updateProjectionMatrix();
  22241. }
  22242. updateProjectionMatrix() {
  22243. const dx = (this.right - this.left) / (2 * this.zoom);
  22244. const dy = (this.top - this.bottom) / (2 * this.zoom);
  22245. const cx = (this.right + this.left) / 2;
  22246. const cy = (this.top + this.bottom) / 2;
  22247. let left = cx - dx;
  22248. let right = cx + dx;
  22249. let top = cy + dy;
  22250. let bottom = cy - dy;
  22251. if (this.view !== null && this.view.enabled) {
  22252. const scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom;
  22253. const scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
  22254. left += scaleW * this.view.offsetX;
  22255. right = left + scaleW * this.view.width;
  22256. top -= scaleH * this.view.offsetY;
  22257. bottom = top - scaleH * this.view.height;
  22258. }
  22259. this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);
  22260. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  22261. }
  22262. toJSON(meta) {
  22263. const data = super.toJSON(meta);
  22264. data.object.zoom = this.zoom;
  22265. data.object.left = this.left;
  22266. data.object.right = this.right;
  22267. data.object.top = this.top;
  22268. data.object.bottom = this.bottom;
  22269. data.object.near = this.near;
  22270. data.object.far = this.far;
  22271. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  22272. return data;
  22273. }
  22274. }
  22275. OrthographicCamera.prototype.isOrthographicCamera = true;
  22276. class DirectionalLightShadow extends LightShadow {
  22277. constructor() {
  22278. super(new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
  22279. }
  22280. }
  22281. DirectionalLightShadow.prototype.isDirectionalLightShadow = true;
  22282. class DirectionalLight extends Light {
  22283. constructor(color, intensity) {
  22284. super(color, intensity);
  22285. this.type = 'DirectionalLight';
  22286. this.position.copy(Object3D.DefaultUp);
  22287. this.updateMatrix();
  22288. this.target = new Object3D();
  22289. this.shadow = new DirectionalLightShadow();
  22290. }
  22291. dispose() {
  22292. this.shadow.dispose();
  22293. }
  22294. copy(source) {
  22295. super.copy(source);
  22296. this.target = source.target.clone();
  22297. this.shadow = source.shadow.clone();
  22298. return this;
  22299. }
  22300. }
  22301. DirectionalLight.prototype.isDirectionalLight = true;
  22302. class AmbientLight extends Light {
  22303. constructor(color, intensity) {
  22304. super(color, intensity);
  22305. this.type = 'AmbientLight';
  22306. }
  22307. }
  22308. AmbientLight.prototype.isAmbientLight = true;
  22309. class RectAreaLight extends Light {
  22310. constructor(color, intensity, width = 10, height = 10) {
  22311. super(color, intensity);
  22312. this.type = 'RectAreaLight';
  22313. this.width = width;
  22314. this.height = height;
  22315. }
  22316. copy(source) {
  22317. super.copy(source);
  22318. this.width = source.width;
  22319. this.height = source.height;
  22320. return this;
  22321. }
  22322. toJSON(meta) {
  22323. const data = super.toJSON(meta);
  22324. data.object.width = this.width;
  22325. data.object.height = this.height;
  22326. return data;
  22327. }
  22328. }
  22329. RectAreaLight.prototype.isRectAreaLight = true;
  22330. /**
  22331. * Primary reference:
  22332. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  22333. *
  22334. * Secondary reference:
  22335. * https://www.ppsloan.org/publications/StupidSH36.pdf
  22336. */
  22337. // 3-band SH defined by 9 coefficients
  22338. class SphericalHarmonics3 {
  22339. constructor() {
  22340. this.coefficients = [];
  22341. for (let i = 0; i < 9; i++) {
  22342. this.coefficients.push(new Vector3());
  22343. }
  22344. }
  22345. set(coefficients) {
  22346. for (let i = 0; i < 9; i++) {
  22347. this.coefficients[i].copy(coefficients[i]);
  22348. }
  22349. return this;
  22350. }
  22351. zero() {
  22352. for (let i = 0; i < 9; i++) {
  22353. this.coefficients[i].set(0, 0, 0);
  22354. }
  22355. return this;
  22356. } // get the radiance in the direction of the normal
  22357. // target is a Vector3
  22358. getAt(normal, target) {
  22359. // normal is assumed to be unit length
  22360. const x = normal.x,
  22361. y = normal.y,
  22362. z = normal.z;
  22363. const coeff = this.coefficients; // band 0
  22364. target.copy(coeff[0]).multiplyScalar(0.282095); // band 1
  22365. target.addScaledVector(coeff[1], 0.488603 * y);
  22366. target.addScaledVector(coeff[2], 0.488603 * z);
  22367. target.addScaledVector(coeff[3], 0.488603 * x); // band 2
  22368. target.addScaledVector(coeff[4], 1.092548 * (x * y));
  22369. target.addScaledVector(coeff[5], 1.092548 * (y * z));
  22370. target.addScaledVector(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
  22371. target.addScaledVector(coeff[7], 1.092548 * (x * z));
  22372. target.addScaledVector(coeff[8], 0.546274 * (x * x - y * y));
  22373. return target;
  22374. } // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  22375. // target is a Vector3
  22376. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  22377. getIrradianceAt(normal, target) {
  22378. // normal is assumed to be unit length
  22379. const x = normal.x,
  22380. y = normal.y,
  22381. z = normal.z;
  22382. const coeff = this.coefficients; // band 0
  22383. target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
  22384. // band 1
  22385. target.addScaledVector(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
  22386. target.addScaledVector(coeff[2], 2.0 * 0.511664 * z);
  22387. target.addScaledVector(coeff[3], 2.0 * 0.511664 * x); // band 2
  22388. target.addScaledVector(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
  22389. target.addScaledVector(coeff[5], 2.0 * 0.429043 * y * z);
  22390. target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
  22391. target.addScaledVector(coeff[7], 2.0 * 0.429043 * x * z);
  22392. target.addScaledVector(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
  22393. return target;
  22394. }
  22395. add(sh) {
  22396. for (let i = 0; i < 9; i++) {
  22397. this.coefficients[i].add(sh.coefficients[i]);
  22398. }
  22399. return this;
  22400. }
  22401. addScaledSH(sh, s) {
  22402. for (let i = 0; i < 9; i++) {
  22403. this.coefficients[i].addScaledVector(sh.coefficients[i], s);
  22404. }
  22405. return this;
  22406. }
  22407. scale(s) {
  22408. for (let i = 0; i < 9; i++) {
  22409. this.coefficients[i].multiplyScalar(s);
  22410. }
  22411. return this;
  22412. }
  22413. lerp(sh, alpha) {
  22414. for (let i = 0; i < 9; i++) {
  22415. this.coefficients[i].lerp(sh.coefficients[i], alpha);
  22416. }
  22417. return this;
  22418. }
  22419. equals(sh) {
  22420. for (let i = 0; i < 9; i++) {
  22421. if (!this.coefficients[i].equals(sh.coefficients[i])) {
  22422. return false;
  22423. }
  22424. }
  22425. return true;
  22426. }
  22427. copy(sh) {
  22428. return this.set(sh.coefficients);
  22429. }
  22430. clone() {
  22431. return new this.constructor().copy(this);
  22432. }
  22433. fromArray(array, offset = 0) {
  22434. const coefficients = this.coefficients;
  22435. for (let i = 0; i < 9; i++) {
  22436. coefficients[i].fromArray(array, offset + i * 3);
  22437. }
  22438. return this;
  22439. }
  22440. toArray(array = [], offset = 0) {
  22441. const coefficients = this.coefficients;
  22442. for (let i = 0; i < 9; i++) {
  22443. coefficients[i].toArray(array, offset + i * 3);
  22444. }
  22445. return array;
  22446. } // evaluate the basis functions
  22447. // shBasis is an Array[ 9 ]
  22448. static getBasisAt(normal, shBasis) {
  22449. // normal is assumed to be unit length
  22450. const x = normal.x,
  22451. y = normal.y,
  22452. z = normal.z; // band 0
  22453. shBasis[0] = 0.282095; // band 1
  22454. shBasis[1] = 0.488603 * y;
  22455. shBasis[2] = 0.488603 * z;
  22456. shBasis[3] = 0.488603 * x; // band 2
  22457. shBasis[4] = 1.092548 * x * y;
  22458. shBasis[5] = 1.092548 * y * z;
  22459. shBasis[6] = 0.315392 * (3 * z * z - 1);
  22460. shBasis[7] = 1.092548 * x * z;
  22461. shBasis[8] = 0.546274 * (x * x - y * y);
  22462. }
  22463. }
  22464. SphericalHarmonics3.prototype.isSphericalHarmonics3 = true;
  22465. class LightProbe extends Light {
  22466. constructor(sh = new SphericalHarmonics3(), intensity = 1) {
  22467. super(undefined, intensity);
  22468. this.sh = sh;
  22469. }
  22470. copy(source) {
  22471. super.copy(source);
  22472. this.sh.copy(source.sh);
  22473. return this;
  22474. }
  22475. fromJSON(json) {
  22476. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  22477. this.sh.fromArray(json.sh);
  22478. return this;
  22479. }
  22480. toJSON(meta) {
  22481. const data = super.toJSON(meta);
  22482. data.object.sh = this.sh.toArray();
  22483. return data;
  22484. }
  22485. }
  22486. LightProbe.prototype.isLightProbe = true;
  22487. class MaterialLoader extends Loader {
  22488. constructor(manager) {
  22489. super(manager);
  22490. this.textures = {};
  22491. }
  22492. load(url, onLoad, onProgress, onError) {
  22493. const scope = this;
  22494. const loader = new FileLoader(scope.manager);
  22495. loader.setPath(scope.path);
  22496. loader.setRequestHeader(scope.requestHeader);
  22497. loader.setWithCredentials(scope.withCredentials);
  22498. loader.load(url, function (text) {
  22499. try {
  22500. onLoad(scope.parse(JSON.parse(text)));
  22501. } catch (e) {
  22502. if (onError) {
  22503. onError(e);
  22504. } else {
  22505. console.error(e);
  22506. }
  22507. scope.manager.itemError(url);
  22508. }
  22509. }, onProgress, onError);
  22510. }
  22511. parse(json) {
  22512. const textures = this.textures;
  22513. function getTexture(name) {
  22514. if (textures[name] === undefined) {
  22515. console.warn('THREE.MaterialLoader: Undefined texture', name);
  22516. }
  22517. return textures[name];
  22518. }
  22519. const material = new Materials[json.type]();
  22520. if (json.uuid !== undefined) material.uuid = json.uuid;
  22521. if (json.name !== undefined) material.name = json.name;
  22522. if (json.color !== undefined && material.color !== undefined) material.color.setHex(json.color);
  22523. if (json.roughness !== undefined) material.roughness = json.roughness;
  22524. if (json.metalness !== undefined) material.metalness = json.metalness;
  22525. if (json.sheen !== undefined) material.sheen = new Color().setHex(json.sheen);
  22526. if (json.emissive !== undefined && material.emissive !== undefined) material.emissive.setHex(json.emissive);
  22527. if (json.specular !== undefined && material.specular !== undefined) material.specular.setHex(json.specular);
  22528. if (json.shininess !== undefined) material.shininess = json.shininess;
  22529. if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
  22530. if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
  22531. if (json.fog !== undefined) material.fog = json.fog;
  22532. if (json.flatShading !== undefined) material.flatShading = json.flatShading;
  22533. if (json.blending !== undefined) material.blending = json.blending;
  22534. if (json.combine !== undefined) material.combine = json.combine;
  22535. if (json.side !== undefined) material.side = json.side;
  22536. if (json.shadowSide !== undefined) material.shadowSide = json.shadowSide;
  22537. if (json.opacity !== undefined) material.opacity = json.opacity;
  22538. if (json.transparent !== undefined) material.transparent = json.transparent;
  22539. if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
  22540. if (json.depthTest !== undefined) material.depthTest = json.depthTest;
  22541. if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
  22542. if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
  22543. if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
  22544. if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
  22545. if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
  22546. if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
  22547. if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
  22548. if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
  22549. if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
  22550. if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
  22551. if (json.wireframe !== undefined) material.wireframe = json.wireframe;
  22552. if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
  22553. if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
  22554. if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
  22555. if (json.rotation !== undefined) material.rotation = json.rotation;
  22556. if (json.linewidth !== 1) material.linewidth = json.linewidth;
  22557. if (json.dashSize !== undefined) material.dashSize = json.dashSize;
  22558. if (json.gapSize !== undefined) material.gapSize = json.gapSize;
  22559. if (json.scale !== undefined) material.scale = json.scale;
  22560. if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
  22561. if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
  22562. if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
  22563. if (json.morphTargets !== undefined) material.morphTargets = json.morphTargets;
  22564. if (json.morphNormals !== undefined) material.morphNormals = json.morphNormals;
  22565. if (json.dithering !== undefined) material.dithering = json.dithering;
  22566. if (json.alphaToCoverage !== undefined) material.alphaToCoverage = json.alphaToCoverage;
  22567. if (json.premultipliedAlpha !== undefined) material.premultipliedAlpha = json.premultipliedAlpha;
  22568. if (json.vertexTangents !== undefined) material.vertexTangents = json.vertexTangents;
  22569. if (json.visible !== undefined) material.visible = json.visible;
  22570. if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
  22571. if (json.userData !== undefined) material.userData = json.userData;
  22572. if (json.vertexColors !== undefined) {
  22573. if (typeof json.vertexColors === 'number') {
  22574. material.vertexColors = json.vertexColors > 0 ? true : false;
  22575. } else {
  22576. material.vertexColors = json.vertexColors;
  22577. }
  22578. } // Shader Material
  22579. if (json.uniforms !== undefined) {
  22580. for (const name in json.uniforms) {
  22581. const uniform = json.uniforms[name];
  22582. material.uniforms[name] = {};
  22583. switch (uniform.type) {
  22584. case 't':
  22585. material.uniforms[name].value = getTexture(uniform.value);
  22586. break;
  22587. case 'c':
  22588. material.uniforms[name].value = new Color().setHex(uniform.value);
  22589. break;
  22590. case 'v2':
  22591. material.uniforms[name].value = new Vector2().fromArray(uniform.value);
  22592. break;
  22593. case 'v3':
  22594. material.uniforms[name].value = new Vector3().fromArray(uniform.value);
  22595. break;
  22596. case 'v4':
  22597. material.uniforms[name].value = new Vector4().fromArray(uniform.value);
  22598. break;
  22599. case 'm3':
  22600. material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
  22601. break;
  22602. case 'm4':
  22603. material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
  22604. break;
  22605. default:
  22606. material.uniforms[name].value = uniform.value;
  22607. }
  22608. }
  22609. }
  22610. if (json.defines !== undefined) material.defines = json.defines;
  22611. if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
  22612. if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
  22613. if (json.extensions !== undefined) {
  22614. for (const key in json.extensions) {
  22615. material.extensions[key] = json.extensions[key];
  22616. }
  22617. } // Deprecated
  22618. if (json.shading !== undefined) material.flatShading = json.shading === 1; // THREE.FlatShading
  22619. // for PointsMaterial
  22620. if (json.size !== undefined) material.size = json.size;
  22621. if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // maps
  22622. if (json.map !== undefined) material.map = getTexture(json.map);
  22623. if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
  22624. if (json.alphaMap !== undefined) material.alphaMap = getTexture(json.alphaMap);
  22625. if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
  22626. if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
  22627. if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
  22628. if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
  22629. if (json.normalScale !== undefined) {
  22630. let normalScale = json.normalScale;
  22631. if (Array.isArray(normalScale) === false) {
  22632. // Blender exporter used to export a scalar. See #7459
  22633. normalScale = [normalScale, normalScale];
  22634. }
  22635. material.normalScale = new Vector2().fromArray(normalScale);
  22636. }
  22637. if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
  22638. if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
  22639. if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
  22640. if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
  22641. if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
  22642. if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
  22643. if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
  22644. if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
  22645. if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
  22646. if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
  22647. if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
  22648. if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
  22649. if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
  22650. if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
  22651. if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
  22652. if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
  22653. if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
  22654. if (json.clearcoatMap !== undefined) material.clearcoatMap = getTexture(json.clearcoatMap);
  22655. if (json.clearcoatRoughnessMap !== undefined) material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap);
  22656. if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
  22657. if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
  22658. if (json.transmission !== undefined) material.transmission = json.transmission;
  22659. if (json.transmissionMap !== undefined) material.transmissionMap = getTexture(json.transmissionMap);
  22660. return material;
  22661. }
  22662. setTextures(value) {
  22663. this.textures = value;
  22664. return this;
  22665. }
  22666. }
  22667. class LoaderUtils {
  22668. static decodeText(array) {
  22669. if (typeof TextDecoder !== 'undefined') {
  22670. return new TextDecoder().decode(array);
  22671. } // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  22672. // throws a "maximum call stack size exceeded" error for large arrays.
  22673. let s = '';
  22674. for (let i = 0, il = array.length; i < il; i++) {
  22675. // Implicitly assumes little-endian.
  22676. s += String.fromCharCode(array[i]);
  22677. }
  22678. try {
  22679. // merges multi-byte utf-8 characters.
  22680. return decodeURIComponent(escape(s));
  22681. } catch (e) {
  22682. // see #16358
  22683. return s;
  22684. }
  22685. }
  22686. static extractUrlBase(url) {
  22687. const index = url.lastIndexOf('/');
  22688. if (index === -1) return './';
  22689. return url.substr(0, index + 1);
  22690. }
  22691. }
  22692. class InstancedBufferGeometry extends BufferGeometry {
  22693. constructor() {
  22694. super();
  22695. this.type = 'InstancedBufferGeometry';
  22696. this.instanceCount = Infinity;
  22697. }
  22698. copy(source) {
  22699. super.copy(source);
  22700. this.instanceCount = source.instanceCount;
  22701. return this;
  22702. }
  22703. clone() {
  22704. return new this.constructor().copy(this);
  22705. }
  22706. toJSON() {
  22707. const data = super.toJSON(this);
  22708. data.instanceCount = this.instanceCount;
  22709. data.isInstancedBufferGeometry = true;
  22710. return data;
  22711. }
  22712. }
  22713. InstancedBufferGeometry.prototype.isInstancedBufferGeometry = true;
  22714. class InstancedBufferAttribute extends BufferAttribute {
  22715. constructor(array, itemSize, normalized, meshPerAttribute) {
  22716. if (typeof normalized === 'number') {
  22717. meshPerAttribute = normalized;
  22718. normalized = false;
  22719. console.error('THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.');
  22720. }
  22721. super(array, itemSize, normalized);
  22722. this.meshPerAttribute = meshPerAttribute || 1;
  22723. }
  22724. copy(source) {
  22725. super.copy(source);
  22726. this.meshPerAttribute = source.meshPerAttribute;
  22727. return this;
  22728. }
  22729. toJSON() {
  22730. const data = super.toJSON();
  22731. data.meshPerAttribute = this.meshPerAttribute;
  22732. data.isInstancedBufferAttribute = true;
  22733. return data;
  22734. }
  22735. }
  22736. InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true;
  22737. class BufferGeometryLoader extends Loader {
  22738. constructor(manager) {
  22739. super(manager);
  22740. }
  22741. load(url, onLoad, onProgress, onError) {
  22742. const scope = this;
  22743. const loader = new FileLoader(scope.manager);
  22744. loader.setPath(scope.path);
  22745. loader.setRequestHeader(scope.requestHeader);
  22746. loader.setWithCredentials(scope.withCredentials);
  22747. loader.load(url, function (text) {
  22748. try {
  22749. onLoad(scope.parse(JSON.parse(text)));
  22750. } catch (e) {
  22751. if (onError) {
  22752. onError(e);
  22753. } else {
  22754. console.error(e);
  22755. }
  22756. scope.manager.itemError(url);
  22757. }
  22758. }, onProgress, onError);
  22759. }
  22760. parse(json) {
  22761. const interleavedBufferMap = {};
  22762. const arrayBufferMap = {};
  22763. function getInterleavedBuffer(json, uuid) {
  22764. if (interleavedBufferMap[uuid] !== undefined) return interleavedBufferMap[uuid];
  22765. const interleavedBuffers = json.interleavedBuffers;
  22766. const interleavedBuffer = interleavedBuffers[uuid];
  22767. const buffer = getArrayBuffer(json, interleavedBuffer.buffer);
  22768. const array = getTypedArray(interleavedBuffer.type, buffer);
  22769. const ib = new InterleavedBuffer(array, interleavedBuffer.stride);
  22770. ib.uuid = interleavedBuffer.uuid;
  22771. interleavedBufferMap[uuid] = ib;
  22772. return ib;
  22773. }
  22774. function getArrayBuffer(json, uuid) {
  22775. if (arrayBufferMap[uuid] !== undefined) return arrayBufferMap[uuid];
  22776. const arrayBuffers = json.arrayBuffers;
  22777. const arrayBuffer = arrayBuffers[uuid];
  22778. const ab = new Uint32Array(arrayBuffer).buffer;
  22779. arrayBufferMap[uuid] = ab;
  22780. return ab;
  22781. }
  22782. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  22783. const index = json.data.index;
  22784. if (index !== undefined) {
  22785. const typedArray = getTypedArray(index.type, index.array);
  22786. geometry.setIndex(new BufferAttribute(typedArray, 1));
  22787. }
  22788. const attributes = json.data.attributes;
  22789. for (const key in attributes) {
  22790. const attribute = attributes[key];
  22791. let bufferAttribute;
  22792. if (attribute.isInterleavedBufferAttribute) {
  22793. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  22794. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  22795. } else {
  22796. const typedArray = getTypedArray(attribute.type, attribute.array);
  22797. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  22798. bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized);
  22799. }
  22800. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  22801. if (attribute.usage !== undefined) bufferAttribute.setUsage(attribute.usage);
  22802. if (attribute.updateRange !== undefined) {
  22803. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  22804. bufferAttribute.updateRange.count = attribute.updateRange.count;
  22805. }
  22806. geometry.setAttribute(key, bufferAttribute);
  22807. }
  22808. const morphAttributes = json.data.morphAttributes;
  22809. if (morphAttributes) {
  22810. for (const key in morphAttributes) {
  22811. const attributeArray = morphAttributes[key];
  22812. const array = [];
  22813. for (let i = 0, il = attributeArray.length; i < il; i++) {
  22814. const attribute = attributeArray[i];
  22815. let bufferAttribute;
  22816. if (attribute.isInterleavedBufferAttribute) {
  22817. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  22818. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  22819. } else {
  22820. const typedArray = getTypedArray(attribute.type, attribute.array);
  22821. bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized);
  22822. }
  22823. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  22824. array.push(bufferAttribute);
  22825. }
  22826. geometry.morphAttributes[key] = array;
  22827. }
  22828. }
  22829. const morphTargetsRelative = json.data.morphTargetsRelative;
  22830. if (morphTargetsRelative) {
  22831. geometry.morphTargetsRelative = true;
  22832. }
  22833. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  22834. if (groups !== undefined) {
  22835. for (let i = 0, n = groups.length; i !== n; ++i) {
  22836. const group = groups[i];
  22837. geometry.addGroup(group.start, group.count, group.materialIndex);
  22838. }
  22839. }
  22840. const boundingSphere = json.data.boundingSphere;
  22841. if (boundingSphere !== undefined) {
  22842. const center = new Vector3();
  22843. if (boundingSphere.center !== undefined) {
  22844. center.fromArray(boundingSphere.center);
  22845. }
  22846. geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
  22847. }
  22848. if (json.name) geometry.name = json.name;
  22849. if (json.userData) geometry.userData = json.userData;
  22850. return geometry;
  22851. }
  22852. }
  22853. class ObjectLoader extends Loader {
  22854. constructor(manager) {
  22855. super(manager);
  22856. }
  22857. load(url, onLoad, onProgress, onError) {
  22858. const scope = this;
  22859. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  22860. this.resourcePath = this.resourcePath || path;
  22861. const loader = new FileLoader(this.manager);
  22862. loader.setPath(this.path);
  22863. loader.setRequestHeader(this.requestHeader);
  22864. loader.setWithCredentials(this.withCredentials);
  22865. loader.load(url, function (text) {
  22866. let json = null;
  22867. try {
  22868. json = JSON.parse(text);
  22869. } catch (error) {
  22870. if (onError !== undefined) onError(error);
  22871. console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
  22872. return;
  22873. }
  22874. const metadata = json.metadata;
  22875. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  22876. console.error('THREE.ObjectLoader: Can\'t load ' + url);
  22877. return;
  22878. }
  22879. scope.parse(json, onLoad);
  22880. }, onProgress, onError);
  22881. }
  22882. parse(json, onLoad) {
  22883. const animations = this.parseAnimations(json.animations);
  22884. const shapes = this.parseShapes(json.shapes);
  22885. const geometries = this.parseGeometries(json.geometries, shapes);
  22886. const images = this.parseImages(json.images, function () {
  22887. if (onLoad !== undefined) onLoad(object);
  22888. });
  22889. const textures = this.parseTextures(json.textures, images);
  22890. const materials = this.parseMaterials(json.materials, textures);
  22891. const object = this.parseObject(json.object, geometries, materials, animations);
  22892. const skeletons = this.parseSkeletons(json.skeletons, object);
  22893. this.bindSkeletons(object, skeletons); //
  22894. if (onLoad !== undefined) {
  22895. let hasImages = false;
  22896. for (const uuid in images) {
  22897. if (images[uuid] instanceof HTMLImageElement) {
  22898. hasImages = true;
  22899. break;
  22900. }
  22901. }
  22902. if (hasImages === false) onLoad(object);
  22903. }
  22904. return object;
  22905. }
  22906. parseShapes(json) {
  22907. const shapes = {};
  22908. if (json !== undefined) {
  22909. for (let i = 0, l = json.length; i < l; i++) {
  22910. const shape = new Shape().fromJSON(json[i]);
  22911. shapes[shape.uuid] = shape;
  22912. }
  22913. }
  22914. return shapes;
  22915. }
  22916. parseSkeletons(json, object) {
  22917. const skeletons = {};
  22918. const bones = {}; // generate bone lookup table
  22919. object.traverse(function (child) {
  22920. if (child.isBone) bones[child.uuid] = child;
  22921. }); // create skeletons
  22922. if (json !== undefined) {
  22923. for (let i = 0, l = json.length; i < l; i++) {
  22924. const skeleton = new Skeleton().fromJSON(json[i], bones);
  22925. skeletons[skeleton.uuid] = skeleton;
  22926. }
  22927. }
  22928. return skeletons;
  22929. }
  22930. parseGeometries(json, shapes) {
  22931. const geometries = {};
  22932. let geometryShapes;
  22933. if (json !== undefined) {
  22934. const bufferGeometryLoader = new BufferGeometryLoader();
  22935. for (let i = 0, l = json.length; i < l; i++) {
  22936. let geometry;
  22937. const data = json[i];
  22938. switch (data.type) {
  22939. case 'PlaneGeometry':
  22940. case 'PlaneBufferGeometry':
  22941. geometry = new Geometries[data.type](data.width, data.height, data.widthSegments, data.heightSegments);
  22942. break;
  22943. case 'BoxGeometry':
  22944. case 'BoxBufferGeometry':
  22945. geometry = new Geometries[data.type](data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
  22946. break;
  22947. case 'CircleGeometry':
  22948. case 'CircleBufferGeometry':
  22949. geometry = new Geometries[data.type](data.radius, data.segments, data.thetaStart, data.thetaLength);
  22950. break;
  22951. case 'CylinderGeometry':
  22952. case 'CylinderBufferGeometry':
  22953. geometry = new Geometries[data.type](data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  22954. break;
  22955. case 'ConeGeometry':
  22956. case 'ConeBufferGeometry':
  22957. geometry = new Geometries[data.type](data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  22958. break;
  22959. case 'SphereGeometry':
  22960. case 'SphereBufferGeometry':
  22961. geometry = new Geometries[data.type](data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
  22962. break;
  22963. case 'DodecahedronGeometry':
  22964. case 'DodecahedronBufferGeometry':
  22965. case 'IcosahedronGeometry':
  22966. case 'IcosahedronBufferGeometry':
  22967. case 'OctahedronGeometry':
  22968. case 'OctahedronBufferGeometry':
  22969. case 'TetrahedronGeometry':
  22970. case 'TetrahedronBufferGeometry':
  22971. geometry = new Geometries[data.type](data.radius, data.detail);
  22972. break;
  22973. case 'RingGeometry':
  22974. case 'RingBufferGeometry':
  22975. geometry = new Geometries[data.type](data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
  22976. break;
  22977. case 'TorusGeometry':
  22978. case 'TorusBufferGeometry':
  22979. geometry = new Geometries[data.type](data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
  22980. break;
  22981. case 'TorusKnotGeometry':
  22982. case 'TorusKnotBufferGeometry':
  22983. geometry = new Geometries[data.type](data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
  22984. break;
  22985. case 'TubeGeometry':
  22986. case 'TubeBufferGeometry':
  22987. // This only works for built-in curves (e.g. CatmullRomCurve3).
  22988. // User defined curves or instances of CurvePath will not be deserialized.
  22989. geometry = new Geometries[data.type](new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
  22990. break;
  22991. case 'LatheGeometry':
  22992. case 'LatheBufferGeometry':
  22993. geometry = new Geometries[data.type](data.points, data.segments, data.phiStart, data.phiLength);
  22994. break;
  22995. case 'PolyhedronGeometry':
  22996. case 'PolyhedronBufferGeometry':
  22997. geometry = new Geometries[data.type](data.vertices, data.indices, data.radius, data.details);
  22998. break;
  22999. case 'ShapeGeometry':
  23000. case 'ShapeBufferGeometry':
  23001. geometryShapes = [];
  23002. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  23003. const shape = shapes[data.shapes[j]];
  23004. geometryShapes.push(shape);
  23005. }
  23006. geometry = new Geometries[data.type](geometryShapes, data.curveSegments);
  23007. break;
  23008. case 'ExtrudeGeometry':
  23009. case 'ExtrudeBufferGeometry':
  23010. geometryShapes = [];
  23011. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  23012. const shape = shapes[data.shapes[j]];
  23013. geometryShapes.push(shape);
  23014. }
  23015. const extrudePath = data.options.extrudePath;
  23016. if (extrudePath !== undefined) {
  23017. data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
  23018. }
  23019. geometry = new Geometries[data.type](geometryShapes, data.options);
  23020. break;
  23021. case 'BufferGeometry':
  23022. case 'InstancedBufferGeometry':
  23023. geometry = bufferGeometryLoader.parse(data);
  23024. break;
  23025. case 'Geometry':
  23026. console.error('THREE.ObjectLoader: Loading "Geometry" is not supported anymore.');
  23027. break;
  23028. default:
  23029. console.warn('THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"');
  23030. continue;
  23031. }
  23032. geometry.uuid = data.uuid;
  23033. if (data.name !== undefined) geometry.name = data.name;
  23034. if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
  23035. geometries[data.uuid] = geometry;
  23036. }
  23037. }
  23038. return geometries;
  23039. }
  23040. parseMaterials(json, textures) {
  23041. const cache = {}; // MultiMaterial
  23042. const materials = {};
  23043. if (json !== undefined) {
  23044. const loader = new MaterialLoader();
  23045. loader.setTextures(textures);
  23046. for (let i = 0, l = json.length; i < l; i++) {
  23047. const data = json[i];
  23048. if (data.type === 'MultiMaterial') {
  23049. // Deprecated
  23050. const array = [];
  23051. for (let j = 0; j < data.materials.length; j++) {
  23052. const material = data.materials[j];
  23053. if (cache[material.uuid] === undefined) {
  23054. cache[material.uuid] = loader.parse(material);
  23055. }
  23056. array.push(cache[material.uuid]);
  23057. }
  23058. materials[data.uuid] = array;
  23059. } else {
  23060. if (cache[data.uuid] === undefined) {
  23061. cache[data.uuid] = loader.parse(data);
  23062. }
  23063. materials[data.uuid] = cache[data.uuid];
  23064. }
  23065. }
  23066. }
  23067. return materials;
  23068. }
  23069. parseAnimations(json) {
  23070. const animations = {};
  23071. if (json !== undefined) {
  23072. for (let i = 0; i < json.length; i++) {
  23073. const data = json[i];
  23074. const clip = AnimationClip.parse(data);
  23075. animations[clip.uuid] = clip;
  23076. }
  23077. }
  23078. return animations;
  23079. }
  23080. parseImages(json, onLoad) {
  23081. const scope = this;
  23082. const images = {};
  23083. let loader;
  23084. function loadImage(url) {
  23085. scope.manager.itemStart(url);
  23086. return loader.load(url, function () {
  23087. scope.manager.itemEnd(url);
  23088. }, undefined, function () {
  23089. scope.manager.itemError(url);
  23090. scope.manager.itemEnd(url);
  23091. });
  23092. }
  23093. function deserializeImage(image) {
  23094. if (typeof image === 'string') {
  23095. const url = image;
  23096. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  23097. return loadImage(path);
  23098. } else {
  23099. if (image.data) {
  23100. return {
  23101. data: getTypedArray(image.type, image.data),
  23102. width: image.width,
  23103. height: image.height
  23104. };
  23105. } else {
  23106. return null;
  23107. }
  23108. }
  23109. }
  23110. if (json !== undefined && json.length > 0) {
  23111. const manager = new LoadingManager(onLoad);
  23112. loader = new ImageLoader(manager);
  23113. loader.setCrossOrigin(this.crossOrigin);
  23114. for (let i = 0, il = json.length; i < il; i++) {
  23115. const image = json[i];
  23116. const url = image.url;
  23117. if (Array.isArray(url)) {
  23118. // load array of images e.g CubeTexture
  23119. images[image.uuid] = [];
  23120. for (let j = 0, jl = url.length; j < jl; j++) {
  23121. const currentUrl = url[j];
  23122. const deserializedImage = deserializeImage(currentUrl);
  23123. if (deserializedImage !== null) {
  23124. if (deserializedImage instanceof HTMLImageElement) {
  23125. images[image.uuid].push(deserializedImage);
  23126. } else {
  23127. // special case: handle array of data textures for cube textures
  23128. images[image.uuid].push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  23129. }
  23130. }
  23131. }
  23132. } else {
  23133. // load single image
  23134. const deserializedImage = deserializeImage(image.url);
  23135. if (deserializedImage !== null) {
  23136. images[image.uuid] = deserializedImage;
  23137. }
  23138. }
  23139. }
  23140. }
  23141. return images;
  23142. }
  23143. parseTextures(json, images) {
  23144. function parseConstant(value, type) {
  23145. if (typeof value === 'number') return value;
  23146. console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
  23147. return type[value];
  23148. }
  23149. const textures = {};
  23150. if (json !== undefined) {
  23151. for (let i = 0, l = json.length; i < l; i++) {
  23152. const data = json[i];
  23153. if (data.image === undefined) {
  23154. console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
  23155. }
  23156. if (images[data.image] === undefined) {
  23157. console.warn('THREE.ObjectLoader: Undefined image', data.image);
  23158. }
  23159. let texture;
  23160. const image = images[data.image];
  23161. if (Array.isArray(image)) {
  23162. texture = new CubeTexture(image);
  23163. if (image.length === 6) texture.needsUpdate = true;
  23164. } else {
  23165. if (image && image.data) {
  23166. texture = new DataTexture(image.data, image.width, image.height);
  23167. } else {
  23168. texture = new Texture(image);
  23169. }
  23170. if (image) texture.needsUpdate = true; // textures can have undefined image data
  23171. }
  23172. texture.uuid = data.uuid;
  23173. if (data.name !== undefined) texture.name = data.name;
  23174. if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
  23175. if (data.offset !== undefined) texture.offset.fromArray(data.offset);
  23176. if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
  23177. if (data.center !== undefined) texture.center.fromArray(data.center);
  23178. if (data.rotation !== undefined) texture.rotation = data.rotation;
  23179. if (data.wrap !== undefined) {
  23180. texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
  23181. texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
  23182. }
  23183. if (data.format !== undefined) texture.format = data.format;
  23184. if (data.type !== undefined) texture.type = data.type;
  23185. if (data.encoding !== undefined) texture.encoding = data.encoding;
  23186. if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
  23187. if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
  23188. if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
  23189. if (data.flipY !== undefined) texture.flipY = data.flipY;
  23190. if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
  23191. if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
  23192. textures[data.uuid] = texture;
  23193. }
  23194. }
  23195. return textures;
  23196. }
  23197. parseObject(data, geometries, materials, animations) {
  23198. let object;
  23199. function getGeometry(name) {
  23200. if (geometries[name] === undefined) {
  23201. console.warn('THREE.ObjectLoader: Undefined geometry', name);
  23202. }
  23203. return geometries[name];
  23204. }
  23205. function getMaterial(name) {
  23206. if (name === undefined) return undefined;
  23207. if (Array.isArray(name)) {
  23208. const array = [];
  23209. for (let i = 0, l = name.length; i < l; i++) {
  23210. const uuid = name[i];
  23211. if (materials[uuid] === undefined) {
  23212. console.warn('THREE.ObjectLoader: Undefined material', uuid);
  23213. }
  23214. array.push(materials[uuid]);
  23215. }
  23216. return array;
  23217. }
  23218. if (materials[name] === undefined) {
  23219. console.warn('THREE.ObjectLoader: Undefined material', name);
  23220. }
  23221. return materials[name];
  23222. }
  23223. let geometry, material;
  23224. switch (data.type) {
  23225. case 'Scene':
  23226. object = new Scene();
  23227. if (data.background !== undefined) {
  23228. if (Number.isInteger(data.background)) {
  23229. object.background = new Color(data.background);
  23230. }
  23231. }
  23232. if (data.fog !== undefined) {
  23233. if (data.fog.type === 'Fog') {
  23234. object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
  23235. } else if (data.fog.type === 'FogExp2') {
  23236. object.fog = new FogExp2(data.fog.color, data.fog.density);
  23237. }
  23238. }
  23239. break;
  23240. case 'PerspectiveCamera':
  23241. object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
  23242. if (data.focus !== undefined) object.focus = data.focus;
  23243. if (data.zoom !== undefined) object.zoom = data.zoom;
  23244. if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
  23245. if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
  23246. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  23247. break;
  23248. case 'OrthographicCamera':
  23249. object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
  23250. if (data.zoom !== undefined) object.zoom = data.zoom;
  23251. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  23252. break;
  23253. case 'AmbientLight':
  23254. object = new AmbientLight(data.color, data.intensity);
  23255. break;
  23256. case 'DirectionalLight':
  23257. object = new DirectionalLight(data.color, data.intensity);
  23258. break;
  23259. case 'PointLight':
  23260. object = new PointLight(data.color, data.intensity, data.distance, data.decay);
  23261. break;
  23262. case 'RectAreaLight':
  23263. object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
  23264. break;
  23265. case 'SpotLight':
  23266. object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
  23267. break;
  23268. case 'HemisphereLight':
  23269. object = new HemisphereLight(data.color, data.groundColor, data.intensity);
  23270. break;
  23271. case 'LightProbe':
  23272. object = new LightProbe().fromJSON(data);
  23273. break;
  23274. case 'SkinnedMesh':
  23275. geometry = getGeometry(data.geometry);
  23276. material = getMaterial(data.material);
  23277. object = new SkinnedMesh(geometry, material);
  23278. if (data.bindMode !== undefined) object.bindMode = data.bindMode;
  23279. if (data.bindMatrix !== undefined) object.bindMatrix.fromArray(data.bindMatrix);
  23280. if (data.skeleton !== undefined) object.skeleton = data.skeleton;
  23281. break;
  23282. case 'Mesh':
  23283. geometry = getGeometry(data.geometry);
  23284. material = getMaterial(data.material);
  23285. object = new Mesh(geometry, material);
  23286. break;
  23287. case 'InstancedMesh':
  23288. geometry = getGeometry(data.geometry);
  23289. material = getMaterial(data.material);
  23290. const count = data.count;
  23291. const instanceMatrix = data.instanceMatrix;
  23292. const instanceColor = data.instanceColor;
  23293. object = new InstancedMesh(geometry, material, count);
  23294. object.instanceMatrix = new BufferAttribute(new Float32Array(instanceMatrix.array), 16);
  23295. if (instanceColor !== undefined) object.instanceColor = new BufferAttribute(new Float32Array(instanceColor.array), instanceColor.itemSize);
  23296. break;
  23297. case 'LOD':
  23298. object = new LOD();
  23299. break;
  23300. case 'Line':
  23301. object = new Line(getGeometry(data.geometry), getMaterial(data.material));
  23302. break;
  23303. case 'LineLoop':
  23304. object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
  23305. break;
  23306. case 'LineSegments':
  23307. object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
  23308. break;
  23309. case 'PointCloud':
  23310. case 'Points':
  23311. object = new Points(getGeometry(data.geometry), getMaterial(data.material));
  23312. break;
  23313. case 'Sprite':
  23314. object = new Sprite(getMaterial(data.material));
  23315. break;
  23316. case 'Group':
  23317. object = new Group();
  23318. break;
  23319. case 'Bone':
  23320. object = new Bone();
  23321. break;
  23322. default:
  23323. object = new Object3D();
  23324. }
  23325. object.uuid = data.uuid;
  23326. if (data.name !== undefined) object.name = data.name;
  23327. if (data.matrix !== undefined) {
  23328. object.matrix.fromArray(data.matrix);
  23329. if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
  23330. if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
  23331. } else {
  23332. if (data.position !== undefined) object.position.fromArray(data.position);
  23333. if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
  23334. if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
  23335. if (data.scale !== undefined) object.scale.fromArray(data.scale);
  23336. }
  23337. if (data.castShadow !== undefined) object.castShadow = data.castShadow;
  23338. if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
  23339. if (data.shadow) {
  23340. if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
  23341. if (data.shadow.normalBias !== undefined) object.shadow.normalBias = data.shadow.normalBias;
  23342. if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
  23343. if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
  23344. if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
  23345. }
  23346. if (data.visible !== undefined) object.visible = data.visible;
  23347. if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
  23348. if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
  23349. if (data.userData !== undefined) object.userData = data.userData;
  23350. if (data.layers !== undefined) object.layers.mask = data.layers;
  23351. if (data.children !== undefined) {
  23352. const children = data.children;
  23353. for (let i = 0; i < children.length; i++) {
  23354. object.add(this.parseObject(children[i], geometries, materials, animations));
  23355. }
  23356. }
  23357. if (data.animations !== undefined) {
  23358. const objectAnimations = data.animations;
  23359. for (let i = 0; i < objectAnimations.length; i++) {
  23360. const uuid = objectAnimations[i];
  23361. object.animations.push(animations[uuid]);
  23362. }
  23363. }
  23364. if (data.type === 'LOD') {
  23365. if (data.autoUpdate !== undefined) object.autoUpdate = data.autoUpdate;
  23366. const levels = data.levels;
  23367. for (let l = 0; l < levels.length; l++) {
  23368. const level = levels[l];
  23369. const child = object.getObjectByProperty('uuid', level.object);
  23370. if (child !== undefined) {
  23371. object.addLevel(child, level.distance);
  23372. }
  23373. }
  23374. }
  23375. return object;
  23376. }
  23377. bindSkeletons(object, skeletons) {
  23378. if (Object.keys(skeletons).length === 0) return;
  23379. object.traverse(function (child) {
  23380. if (child.isSkinnedMesh === true && child.skeleton !== undefined) {
  23381. const skeleton = skeletons[child.skeleton];
  23382. if (skeleton === undefined) {
  23383. console.warn('THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton);
  23384. } else {
  23385. child.bind(skeleton, child.bindMatrix);
  23386. }
  23387. }
  23388. });
  23389. }
  23390. /* DEPRECATED */
  23391. setTexturePath(value) {
  23392. console.warn('THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().');
  23393. return this.setResourcePath(value);
  23394. }
  23395. }
  23396. const TEXTURE_MAPPING = {
  23397. UVMapping: UVMapping,
  23398. CubeReflectionMapping: CubeReflectionMapping,
  23399. CubeRefractionMapping: CubeRefractionMapping,
  23400. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  23401. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  23402. CubeUVReflectionMapping: CubeUVReflectionMapping,
  23403. CubeUVRefractionMapping: CubeUVRefractionMapping
  23404. };
  23405. const TEXTURE_WRAPPING = {
  23406. RepeatWrapping: RepeatWrapping,
  23407. ClampToEdgeWrapping: ClampToEdgeWrapping,
  23408. MirroredRepeatWrapping: MirroredRepeatWrapping
  23409. };
  23410. const TEXTURE_FILTER = {
  23411. NearestFilter: NearestFilter,
  23412. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  23413. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  23414. LinearFilter: LinearFilter,
  23415. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  23416. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  23417. };
  23418. class ImageBitmapLoader extends Loader {
  23419. constructor(manager) {
  23420. super(manager);
  23421. if (typeof createImageBitmap === 'undefined') {
  23422. console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
  23423. }
  23424. if (typeof fetch === 'undefined') {
  23425. console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
  23426. }
  23427. this.options = {
  23428. premultiplyAlpha: 'none'
  23429. };
  23430. }
  23431. setOptions(options) {
  23432. this.options = options;
  23433. return this;
  23434. }
  23435. load(url, onLoad, onProgress, onError) {
  23436. if (url === undefined) url = '';
  23437. if (this.path !== undefined) url = this.path + url;
  23438. url = this.manager.resolveURL(url);
  23439. const scope = this;
  23440. const cached = Cache.get(url);
  23441. if (cached !== undefined) {
  23442. scope.manager.itemStart(url);
  23443. setTimeout(function () {
  23444. if (onLoad) onLoad(cached);
  23445. scope.manager.itemEnd(url);
  23446. }, 0);
  23447. return cached;
  23448. }
  23449. const fetchOptions = {};
  23450. fetchOptions.credentials = this.crossOrigin === 'anonymous' ? 'same-origin' : 'include';
  23451. fetchOptions.headers = this.requestHeader;
  23452. fetch(url, fetchOptions).then(function (res) {
  23453. return res.blob();
  23454. }).then(function (blob) {
  23455. return createImageBitmap(blob, Object.assign(scope.options, {
  23456. colorSpaceConversion: 'none'
  23457. }));
  23458. }).then(function (imageBitmap) {
  23459. Cache.add(url, imageBitmap);
  23460. if (onLoad) onLoad(imageBitmap);
  23461. scope.manager.itemEnd(url);
  23462. }).catch(function (e) {
  23463. if (onError) onError(e);
  23464. scope.manager.itemError(url);
  23465. scope.manager.itemEnd(url);
  23466. });
  23467. scope.manager.itemStart(url);
  23468. }
  23469. }
  23470. ImageBitmapLoader.prototype.isImageBitmapLoader = true;
  23471. class ShapePath {
  23472. constructor() {
  23473. this.type = 'ShapePath';
  23474. this.color = new Color();
  23475. this.subPaths = [];
  23476. this.currentPath = null;
  23477. }
  23478. moveTo(x, y) {
  23479. this.currentPath = new Path();
  23480. this.subPaths.push(this.currentPath);
  23481. this.currentPath.moveTo(x, y);
  23482. return this;
  23483. }
  23484. lineTo(x, y) {
  23485. this.currentPath.lineTo(x, y);
  23486. return this;
  23487. }
  23488. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  23489. this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
  23490. return this;
  23491. }
  23492. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  23493. this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
  23494. return this;
  23495. }
  23496. splineThru(pts) {
  23497. this.currentPath.splineThru(pts);
  23498. return this;
  23499. }
  23500. toShapes(isCCW, noHoles) {
  23501. function toShapesNoHoles(inSubpaths) {
  23502. const shapes = [];
  23503. for (let i = 0, l = inSubpaths.length; i < l; i++) {
  23504. const tmpPath = inSubpaths[i];
  23505. const tmpShape = new Shape();
  23506. tmpShape.curves = tmpPath.curves;
  23507. shapes.push(tmpShape);
  23508. }
  23509. return shapes;
  23510. }
  23511. function isPointInsidePolygon(inPt, inPolygon) {
  23512. const polyLen = inPolygon.length; // inPt on polygon contour => immediate success or
  23513. // toggling of inside/outside at every single! intersection point of an edge
  23514. // with the horizontal line through inPt, left of inPt
  23515. // not counting lowerY endpoints of edges and whole edges on that line
  23516. let inside = false;
  23517. for (let p = polyLen - 1, q = 0; q < polyLen; p = q++) {
  23518. let edgeLowPt = inPolygon[p];
  23519. let edgeHighPt = inPolygon[q];
  23520. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  23521. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  23522. if (Math.abs(edgeDy) > Number.EPSILON) {
  23523. // not parallel
  23524. if (edgeDy < 0) {
  23525. edgeLowPt = inPolygon[q];
  23526. edgeDx = -edgeDx;
  23527. edgeHighPt = inPolygon[p];
  23528. edgeDy = -edgeDy;
  23529. }
  23530. if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
  23531. if (inPt.y === edgeLowPt.y) {
  23532. if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
  23533. // continue; // no intersection or edgeLowPt => doesn't count !!!
  23534. } else {
  23535. const perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  23536. if (perpEdge === 0) return true; // inPt is on contour ?
  23537. if (perpEdge < 0) continue;
  23538. inside = !inside; // true intersection left of inPt
  23539. }
  23540. } else {
  23541. // parallel or collinear
  23542. if (inPt.y !== edgeLowPt.y) continue; // parallel
  23543. // edge lies on the same horizontal line as inPt
  23544. if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
  23545. // continue;
  23546. }
  23547. }
  23548. return inside;
  23549. }
  23550. const isClockWise = ShapeUtils.isClockWise;
  23551. const subPaths = this.subPaths;
  23552. if (subPaths.length === 0) return [];
  23553. if (noHoles === true) return toShapesNoHoles(subPaths);
  23554. let solid, tmpPath, tmpShape;
  23555. const shapes = [];
  23556. if (subPaths.length === 1) {
  23557. tmpPath = subPaths[0];
  23558. tmpShape = new Shape();
  23559. tmpShape.curves = tmpPath.curves;
  23560. shapes.push(tmpShape);
  23561. return shapes;
  23562. }
  23563. let holesFirst = !isClockWise(subPaths[0].getPoints());
  23564. holesFirst = isCCW ? !holesFirst : holesFirst; // console.log("Holes first", holesFirst);
  23565. const betterShapeHoles = [];
  23566. const newShapes = [];
  23567. let newShapeHoles = [];
  23568. let mainIdx = 0;
  23569. let tmpPoints;
  23570. newShapes[mainIdx] = undefined;
  23571. newShapeHoles[mainIdx] = [];
  23572. for (let i = 0, l = subPaths.length; i < l; i++) {
  23573. tmpPath = subPaths[i];
  23574. tmpPoints = tmpPath.getPoints();
  23575. solid = isClockWise(tmpPoints);
  23576. solid = isCCW ? !solid : solid;
  23577. if (solid) {
  23578. if (!holesFirst && newShapes[mainIdx]) mainIdx++;
  23579. newShapes[mainIdx] = {
  23580. s: new Shape(),
  23581. p: tmpPoints
  23582. };
  23583. newShapes[mainIdx].s.curves = tmpPath.curves;
  23584. if (holesFirst) mainIdx++;
  23585. newShapeHoles[mainIdx] = []; //console.log('cw', i);
  23586. } else {
  23587. newShapeHoles[mainIdx].push({
  23588. h: tmpPath,
  23589. p: tmpPoints[0]
  23590. }); //console.log('ccw', i);
  23591. }
  23592. } // only Holes? -> probably all Shapes with wrong orientation
  23593. if (!newShapes[0]) return toShapesNoHoles(subPaths);
  23594. if (newShapes.length > 1) {
  23595. let ambiguous = false;
  23596. const toChange = [];
  23597. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  23598. betterShapeHoles[sIdx] = [];
  23599. }
  23600. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  23601. const sho = newShapeHoles[sIdx];
  23602. for (let hIdx = 0; hIdx < sho.length; hIdx++) {
  23603. const ho = sho[hIdx];
  23604. let hole_unassigned = true;
  23605. for (let s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
  23606. if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
  23607. if (sIdx !== s2Idx) toChange.push({
  23608. froms: sIdx,
  23609. tos: s2Idx,
  23610. hole: hIdx
  23611. });
  23612. if (hole_unassigned) {
  23613. hole_unassigned = false;
  23614. betterShapeHoles[s2Idx].push(ho);
  23615. } else {
  23616. ambiguous = true;
  23617. }
  23618. }
  23619. }
  23620. if (hole_unassigned) {
  23621. betterShapeHoles[sIdx].push(ho);
  23622. }
  23623. }
  23624. } // console.log("ambiguous: ", ambiguous);
  23625. if (toChange.length > 0) {
  23626. // console.log("to change: ", toChange);
  23627. if (!ambiguous) newShapeHoles = betterShapeHoles;
  23628. }
  23629. }
  23630. let tmpHoles;
  23631. for (let i = 0, il = newShapes.length; i < il; i++) {
  23632. tmpShape = newShapes[i].s;
  23633. shapes.push(tmpShape);
  23634. tmpHoles = newShapeHoles[i];
  23635. for (let j = 0, jl = tmpHoles.length; j < jl; j++) {
  23636. tmpShape.holes.push(tmpHoles[j].h);
  23637. }
  23638. } //console.log("shape", shapes);
  23639. return shapes;
  23640. }
  23641. }
  23642. class Font {
  23643. constructor(data) {
  23644. this.type = 'Font';
  23645. this.data = data;
  23646. }
  23647. generateShapes(text, size = 100) {
  23648. const shapes = [];
  23649. const paths = createPaths(text, size, this.data);
  23650. for (let p = 0, pl = paths.length; p < pl; p++) {
  23651. Array.prototype.push.apply(shapes, paths[p].toShapes());
  23652. }
  23653. return shapes;
  23654. }
  23655. }
  23656. function createPaths(text, size, data) {
  23657. const chars = Array.from(text);
  23658. const scale = size / data.resolution;
  23659. const line_height = (data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness) * scale;
  23660. const paths = [];
  23661. let offsetX = 0,
  23662. offsetY = 0;
  23663. for (let i = 0; i < chars.length; i++) {
  23664. const char = chars[i];
  23665. if (char === '\n') {
  23666. offsetX = 0;
  23667. offsetY -= line_height;
  23668. } else {
  23669. const ret = createPath(char, scale, offsetX, offsetY, data);
  23670. offsetX += ret.offsetX;
  23671. paths.push(ret.path);
  23672. }
  23673. }
  23674. return paths;
  23675. }
  23676. function createPath(char, scale, offsetX, offsetY, data) {
  23677. const glyph = data.glyphs[char] || data.glyphs['?'];
  23678. if (!glyph) {
  23679. console.error('THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.');
  23680. return;
  23681. }
  23682. const path = new ShapePath();
  23683. let x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  23684. if (glyph.o) {
  23685. const outline = glyph._cachedOutline || (glyph._cachedOutline = glyph.o.split(' '));
  23686. for (let i = 0, l = outline.length; i < l;) {
  23687. const action = outline[i++];
  23688. switch (action) {
  23689. case 'm':
  23690. // moveTo
  23691. x = outline[i++] * scale + offsetX;
  23692. y = outline[i++] * scale + offsetY;
  23693. path.moveTo(x, y);
  23694. break;
  23695. case 'l':
  23696. // lineTo
  23697. x = outline[i++] * scale + offsetX;
  23698. y = outline[i++] * scale + offsetY;
  23699. path.lineTo(x, y);
  23700. break;
  23701. case 'q':
  23702. // quadraticCurveTo
  23703. cpx = outline[i++] * scale + offsetX;
  23704. cpy = outline[i++] * scale + offsetY;
  23705. cpx1 = outline[i++] * scale + offsetX;
  23706. cpy1 = outline[i++] * scale + offsetY;
  23707. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  23708. break;
  23709. case 'b':
  23710. // bezierCurveTo
  23711. cpx = outline[i++] * scale + offsetX;
  23712. cpy = outline[i++] * scale + offsetY;
  23713. cpx1 = outline[i++] * scale + offsetX;
  23714. cpy1 = outline[i++] * scale + offsetY;
  23715. cpx2 = outline[i++] * scale + offsetX;
  23716. cpy2 = outline[i++] * scale + offsetY;
  23717. path.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy);
  23718. break;
  23719. }
  23720. }
  23721. }
  23722. return {
  23723. offsetX: glyph.ha * scale,
  23724. path: path
  23725. };
  23726. }
  23727. Font.prototype.isFont = true;
  23728. class FontLoader extends Loader {
  23729. constructor(manager) {
  23730. super(manager);
  23731. }
  23732. load(url, onLoad, onProgress, onError) {
  23733. const scope = this;
  23734. const loader = new FileLoader(this.manager);
  23735. loader.setPath(this.path);
  23736. loader.setRequestHeader(this.requestHeader);
  23737. loader.setWithCredentials(scope.withCredentials);
  23738. loader.load(url, function (text) {
  23739. let json;
  23740. try {
  23741. json = JSON.parse(text);
  23742. } catch (e) {
  23743. console.warn('THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.');
  23744. json = JSON.parse(text.substring(65, text.length - 2));
  23745. }
  23746. const font = scope.parse(json);
  23747. if (onLoad) onLoad(font);
  23748. }, onProgress, onError);
  23749. }
  23750. parse(json) {
  23751. return new Font(json);
  23752. }
  23753. }
  23754. let _context;
  23755. const AudioContext = {
  23756. getContext: function () {
  23757. if (_context === undefined) {
  23758. _context = new (window.AudioContext || window.webkitAudioContext)();
  23759. }
  23760. return _context;
  23761. },
  23762. setContext: function (value) {
  23763. _context = value;
  23764. }
  23765. };
  23766. class AudioLoader extends Loader {
  23767. constructor(manager) {
  23768. super(manager);
  23769. }
  23770. load(url, onLoad, onProgress, onError) {
  23771. const scope = this;
  23772. const loader = new FileLoader(this.manager);
  23773. loader.setResponseType('arraybuffer');
  23774. loader.setPath(this.path);
  23775. loader.setRequestHeader(this.requestHeader);
  23776. loader.setWithCredentials(this.withCredentials);
  23777. loader.load(url, function (buffer) {
  23778. try {
  23779. // Create a copy of the buffer. The `decodeAudioData` method
  23780. // detaches the buffer when complete, preventing reuse.
  23781. const bufferCopy = buffer.slice(0);
  23782. const context = AudioContext.getContext();
  23783. context.decodeAudioData(bufferCopy, function (audioBuffer) {
  23784. onLoad(audioBuffer);
  23785. });
  23786. } catch (e) {
  23787. if (onError) {
  23788. onError(e);
  23789. } else {
  23790. console.error(e);
  23791. }
  23792. scope.manager.itemError(url);
  23793. }
  23794. }, onProgress, onError);
  23795. }
  23796. }
  23797. class HemisphereLightProbe extends LightProbe {
  23798. constructor(skyColor, groundColor, intensity = 1) {
  23799. super(undefined, intensity);
  23800. const color1 = new Color().set(skyColor);
  23801. const color2 = new Color().set(groundColor);
  23802. const sky = new Vector3(color1.r, color1.g, color1.b);
  23803. const ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  23804. const c0 = Math.sqrt(Math.PI);
  23805. const c1 = c0 * Math.sqrt(0.75);
  23806. this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
  23807. this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
  23808. }
  23809. }
  23810. HemisphereLightProbe.prototype.isHemisphereLightProbe = true;
  23811. class AmbientLightProbe extends LightProbe {
  23812. constructor(color, intensity = 1) {
  23813. super(undefined, intensity);
  23814. const color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  23815. this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
  23816. }
  23817. }
  23818. AmbientLightProbe.prototype.isAmbientLightProbe = true;
  23819. const _eyeRight = /*@__PURE__*/new Matrix4();
  23820. const _eyeLeft = /*@__PURE__*/new Matrix4();
  23821. class StereoCamera {
  23822. constructor() {
  23823. this.type = 'StereoCamera';
  23824. this.aspect = 1;
  23825. this.eyeSep = 0.064;
  23826. this.cameraL = new PerspectiveCamera();
  23827. this.cameraL.layers.enable(1);
  23828. this.cameraL.matrixAutoUpdate = false;
  23829. this.cameraR = new PerspectiveCamera();
  23830. this.cameraR.layers.enable(2);
  23831. this.cameraR.matrixAutoUpdate = false;
  23832. this._cache = {
  23833. focus: null,
  23834. fov: null,
  23835. aspect: null,
  23836. near: null,
  23837. far: null,
  23838. zoom: null,
  23839. eyeSep: null
  23840. };
  23841. }
  23842. update(camera) {
  23843. const cache = this._cache;
  23844. 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;
  23845. if (needsUpdate) {
  23846. cache.focus = camera.focus;
  23847. cache.fov = camera.fov;
  23848. cache.aspect = camera.aspect * this.aspect;
  23849. cache.near = camera.near;
  23850. cache.far = camera.far;
  23851. cache.zoom = camera.zoom;
  23852. cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based on
  23853. // http://paulbourke.net/stereographics/stereorender/
  23854. const projectionMatrix = camera.projectionMatrix.clone();
  23855. const eyeSepHalf = cache.eyeSep / 2;
  23856. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  23857. const ymax = cache.near * Math.tan(DEG2RAD * cache.fov * 0.5) / cache.zoom;
  23858. let xmin, xmax; // translate xOffset
  23859. _eyeLeft.elements[12] = -eyeSepHalf;
  23860. _eyeRight.elements[12] = eyeSepHalf; // for left eye
  23861. xmin = -ymax * cache.aspect + eyeSepOnProjection;
  23862. xmax = ymax * cache.aspect + eyeSepOnProjection;
  23863. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  23864. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  23865. this.cameraL.projectionMatrix.copy(projectionMatrix); // for right eye
  23866. xmin = -ymax * cache.aspect - eyeSepOnProjection;
  23867. xmax = ymax * cache.aspect - eyeSepOnProjection;
  23868. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  23869. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  23870. this.cameraR.projectionMatrix.copy(projectionMatrix);
  23871. }
  23872. this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
  23873. this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
  23874. }
  23875. }
  23876. class Clock {
  23877. constructor(autoStart = true) {
  23878. this.autoStart = autoStart;
  23879. this.startTime = 0;
  23880. this.oldTime = 0;
  23881. this.elapsedTime = 0;
  23882. this.running = false;
  23883. }
  23884. start() {
  23885. this.startTime = now();
  23886. this.oldTime = this.startTime;
  23887. this.elapsedTime = 0;
  23888. this.running = true;
  23889. }
  23890. stop() {
  23891. this.getElapsedTime();
  23892. this.running = false;
  23893. this.autoStart = false;
  23894. }
  23895. getElapsedTime() {
  23896. this.getDelta();
  23897. return this.elapsedTime;
  23898. }
  23899. getDelta() {
  23900. let diff = 0;
  23901. if (this.autoStart && !this.running) {
  23902. this.start();
  23903. return 0;
  23904. }
  23905. if (this.running) {
  23906. const newTime = now();
  23907. diff = (newTime - this.oldTime) / 1000;
  23908. this.oldTime = newTime;
  23909. this.elapsedTime += diff;
  23910. }
  23911. return diff;
  23912. }
  23913. }
  23914. function now() {
  23915. return (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
  23916. }
  23917. const _position$1 = /*@__PURE__*/new Vector3();
  23918. const _quaternion$1 = /*@__PURE__*/new Quaternion();
  23919. const _scale$1 = /*@__PURE__*/new Vector3();
  23920. const _orientation$1 = /*@__PURE__*/new Vector3();
  23921. class AudioListener extends Object3D {
  23922. constructor() {
  23923. super();
  23924. this.type = 'AudioListener';
  23925. this.context = AudioContext.getContext();
  23926. this.gain = this.context.createGain();
  23927. this.gain.connect(this.context.destination);
  23928. this.filter = null;
  23929. this.timeDelta = 0; // private
  23930. this._clock = new Clock();
  23931. }
  23932. getInput() {
  23933. return this.gain;
  23934. }
  23935. removeFilter() {
  23936. if (this.filter !== null) {
  23937. this.gain.disconnect(this.filter);
  23938. this.filter.disconnect(this.context.destination);
  23939. this.gain.connect(this.context.destination);
  23940. this.filter = null;
  23941. }
  23942. return this;
  23943. }
  23944. getFilter() {
  23945. return this.filter;
  23946. }
  23947. setFilter(value) {
  23948. if (this.filter !== null) {
  23949. this.gain.disconnect(this.filter);
  23950. this.filter.disconnect(this.context.destination);
  23951. } else {
  23952. this.gain.disconnect(this.context.destination);
  23953. }
  23954. this.filter = value;
  23955. this.gain.connect(this.filter);
  23956. this.filter.connect(this.context.destination);
  23957. return this;
  23958. }
  23959. getMasterVolume() {
  23960. return this.gain.gain.value;
  23961. }
  23962. setMasterVolume(value) {
  23963. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  23964. return this;
  23965. }
  23966. updateMatrixWorld(force) {
  23967. super.updateMatrixWorld(force);
  23968. const listener = this.context.listener;
  23969. const up = this.up;
  23970. this.timeDelta = this._clock.getDelta();
  23971. this.matrixWorld.decompose(_position$1, _quaternion$1, _scale$1);
  23972. _orientation$1.set(0, 0, -1).applyQuaternion(_quaternion$1);
  23973. if (listener.positionX) {
  23974. // code path for Chrome (see #14393)
  23975. const endTime = this.context.currentTime + this.timeDelta;
  23976. listener.positionX.linearRampToValueAtTime(_position$1.x, endTime);
  23977. listener.positionY.linearRampToValueAtTime(_position$1.y, endTime);
  23978. listener.positionZ.linearRampToValueAtTime(_position$1.z, endTime);
  23979. listener.forwardX.linearRampToValueAtTime(_orientation$1.x, endTime);
  23980. listener.forwardY.linearRampToValueAtTime(_orientation$1.y, endTime);
  23981. listener.forwardZ.linearRampToValueAtTime(_orientation$1.z, endTime);
  23982. listener.upX.linearRampToValueAtTime(up.x, endTime);
  23983. listener.upY.linearRampToValueAtTime(up.y, endTime);
  23984. listener.upZ.linearRampToValueAtTime(up.z, endTime);
  23985. } else {
  23986. listener.setPosition(_position$1.x, _position$1.y, _position$1.z);
  23987. listener.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z);
  23988. }
  23989. }
  23990. }
  23991. class Audio extends Object3D {
  23992. constructor(listener) {
  23993. super();
  23994. this.type = 'Audio';
  23995. this.listener = listener;
  23996. this.context = listener.context;
  23997. this.gain = this.context.createGain();
  23998. this.gain.connect(listener.getInput());
  23999. this.autoplay = false;
  24000. this.buffer = null;
  24001. this.detune = 0;
  24002. this.loop = false;
  24003. this.loopStart = 0;
  24004. this.loopEnd = 0;
  24005. this.offset = 0;
  24006. this.duration = undefined;
  24007. this.playbackRate = 1;
  24008. this.isPlaying = false;
  24009. this.hasPlaybackControl = true;
  24010. this.source = null;
  24011. this.sourceType = 'empty';
  24012. this._startedAt = 0;
  24013. this._progress = 0;
  24014. this._connected = false;
  24015. this.filters = [];
  24016. }
  24017. getOutput() {
  24018. return this.gain;
  24019. }
  24020. setNodeSource(audioNode) {
  24021. this.hasPlaybackControl = false;
  24022. this.sourceType = 'audioNode';
  24023. this.source = audioNode;
  24024. this.connect();
  24025. return this;
  24026. }
  24027. setMediaElementSource(mediaElement) {
  24028. this.hasPlaybackControl = false;
  24029. this.sourceType = 'mediaNode';
  24030. this.source = this.context.createMediaElementSource(mediaElement);
  24031. this.connect();
  24032. return this;
  24033. }
  24034. setMediaStreamSource(mediaStream) {
  24035. this.hasPlaybackControl = false;
  24036. this.sourceType = 'mediaStreamNode';
  24037. this.source = this.context.createMediaStreamSource(mediaStream);
  24038. this.connect();
  24039. return this;
  24040. }
  24041. setBuffer(audioBuffer) {
  24042. this.buffer = audioBuffer;
  24043. this.sourceType = 'buffer';
  24044. if (this.autoplay) this.play();
  24045. return this;
  24046. }
  24047. play(delay = 0) {
  24048. if (this.isPlaying === true) {
  24049. console.warn('THREE.Audio: Audio is already playing.');
  24050. return;
  24051. }
  24052. if (this.hasPlaybackControl === false) {
  24053. console.warn('THREE.Audio: this Audio has no playback control.');
  24054. return;
  24055. }
  24056. this._startedAt = this.context.currentTime + delay;
  24057. const source = this.context.createBufferSource();
  24058. source.buffer = this.buffer;
  24059. source.loop = this.loop;
  24060. source.loopStart = this.loopStart;
  24061. source.loopEnd = this.loopEnd;
  24062. source.onended = this.onEnded.bind(this);
  24063. source.start(this._startedAt, this._progress + this.offset, this.duration);
  24064. this.isPlaying = true;
  24065. this.source = source;
  24066. this.setDetune(this.detune);
  24067. this.setPlaybackRate(this.playbackRate);
  24068. return this.connect();
  24069. }
  24070. pause() {
  24071. if (this.hasPlaybackControl === false) {
  24072. console.warn('THREE.Audio: this Audio has no playback control.');
  24073. return;
  24074. }
  24075. if (this.isPlaying === true) {
  24076. // update current progress
  24077. this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate;
  24078. if (this.loop === true) {
  24079. // ensure _progress does not exceed duration with looped audios
  24080. this._progress = this._progress % (this.duration || this.buffer.duration);
  24081. }
  24082. this.source.stop();
  24083. this.source.onended = null;
  24084. this.isPlaying = false;
  24085. }
  24086. return this;
  24087. }
  24088. stop() {
  24089. if (this.hasPlaybackControl === false) {
  24090. console.warn('THREE.Audio: this Audio has no playback control.');
  24091. return;
  24092. }
  24093. this._progress = 0;
  24094. this.source.stop();
  24095. this.source.onended = null;
  24096. this.isPlaying = false;
  24097. return this;
  24098. }
  24099. connect() {
  24100. if (this.filters.length > 0) {
  24101. this.source.connect(this.filters[0]);
  24102. for (let i = 1, l = this.filters.length; i < l; i++) {
  24103. this.filters[i - 1].connect(this.filters[i]);
  24104. }
  24105. this.filters[this.filters.length - 1].connect(this.getOutput());
  24106. } else {
  24107. this.source.connect(this.getOutput());
  24108. }
  24109. this._connected = true;
  24110. return this;
  24111. }
  24112. disconnect() {
  24113. if (this.filters.length > 0) {
  24114. this.source.disconnect(this.filters[0]);
  24115. for (let i = 1, l = this.filters.length; i < l; i++) {
  24116. this.filters[i - 1].disconnect(this.filters[i]);
  24117. }
  24118. this.filters[this.filters.length - 1].disconnect(this.getOutput());
  24119. } else {
  24120. this.source.disconnect(this.getOutput());
  24121. }
  24122. this._connected = false;
  24123. return this;
  24124. }
  24125. getFilters() {
  24126. return this.filters;
  24127. }
  24128. setFilters(value) {
  24129. if (!value) value = [];
  24130. if (this._connected === true) {
  24131. this.disconnect();
  24132. this.filters = value.slice();
  24133. this.connect();
  24134. } else {
  24135. this.filters = value.slice();
  24136. }
  24137. return this;
  24138. }
  24139. setDetune(value) {
  24140. this.detune = value;
  24141. if (this.source.detune === undefined) return; // only set detune when available
  24142. if (this.isPlaying === true) {
  24143. this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
  24144. }
  24145. return this;
  24146. }
  24147. getDetune() {
  24148. return this.detune;
  24149. }
  24150. getFilter() {
  24151. return this.getFilters()[0];
  24152. }
  24153. setFilter(filter) {
  24154. return this.setFilters(filter ? [filter] : []);
  24155. }
  24156. setPlaybackRate(value) {
  24157. if (this.hasPlaybackControl === false) {
  24158. console.warn('THREE.Audio: this Audio has no playback control.');
  24159. return;
  24160. }
  24161. this.playbackRate = value;
  24162. if (this.isPlaying === true) {
  24163. this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
  24164. }
  24165. return this;
  24166. }
  24167. getPlaybackRate() {
  24168. return this.playbackRate;
  24169. }
  24170. onEnded() {
  24171. this.isPlaying = false;
  24172. }
  24173. getLoop() {
  24174. if (this.hasPlaybackControl === false) {
  24175. console.warn('THREE.Audio: this Audio has no playback control.');
  24176. return false;
  24177. }
  24178. return this.loop;
  24179. }
  24180. setLoop(value) {
  24181. if (this.hasPlaybackControl === false) {
  24182. console.warn('THREE.Audio: this Audio has no playback control.');
  24183. return;
  24184. }
  24185. this.loop = value;
  24186. if (this.isPlaying === true) {
  24187. this.source.loop = this.loop;
  24188. }
  24189. return this;
  24190. }
  24191. setLoopStart(value) {
  24192. this.loopStart = value;
  24193. return this;
  24194. }
  24195. setLoopEnd(value) {
  24196. this.loopEnd = value;
  24197. return this;
  24198. }
  24199. getVolume() {
  24200. return this.gain.gain.value;
  24201. }
  24202. setVolume(value) {
  24203. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  24204. return this;
  24205. }
  24206. }
  24207. const _position = /*@__PURE__*/new Vector3();
  24208. const _quaternion = /*@__PURE__*/new Quaternion();
  24209. const _scale = /*@__PURE__*/new Vector3();
  24210. const _orientation = /*@__PURE__*/new Vector3();
  24211. class PositionalAudio extends Audio {
  24212. constructor(listener) {
  24213. super(listener);
  24214. this.panner = this.context.createPanner();
  24215. this.panner.panningModel = 'HRTF';
  24216. this.panner.connect(this.gain);
  24217. }
  24218. getOutput() {
  24219. return this.panner;
  24220. }
  24221. getRefDistance() {
  24222. return this.panner.refDistance;
  24223. }
  24224. setRefDistance(value) {
  24225. this.panner.refDistance = value;
  24226. return this;
  24227. }
  24228. getRolloffFactor() {
  24229. return this.panner.rolloffFactor;
  24230. }
  24231. setRolloffFactor(value) {
  24232. this.panner.rolloffFactor = value;
  24233. return this;
  24234. }
  24235. getDistanceModel() {
  24236. return this.panner.distanceModel;
  24237. }
  24238. setDistanceModel(value) {
  24239. this.panner.distanceModel = value;
  24240. return this;
  24241. }
  24242. getMaxDistance() {
  24243. return this.panner.maxDistance;
  24244. }
  24245. setMaxDistance(value) {
  24246. this.panner.maxDistance = value;
  24247. return this;
  24248. }
  24249. setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) {
  24250. this.panner.coneInnerAngle = coneInnerAngle;
  24251. this.panner.coneOuterAngle = coneOuterAngle;
  24252. this.panner.coneOuterGain = coneOuterGain;
  24253. return this;
  24254. }
  24255. updateMatrixWorld(force) {
  24256. super.updateMatrixWorld(force);
  24257. if (this.hasPlaybackControl === true && this.isPlaying === false) return;
  24258. this.matrixWorld.decompose(_position, _quaternion, _scale);
  24259. _orientation.set(0, 0, 1).applyQuaternion(_quaternion);
  24260. const panner = this.panner;
  24261. if (panner.positionX) {
  24262. // code path for Chrome and Firefox (see #14393)
  24263. const endTime = this.context.currentTime + this.listener.timeDelta;
  24264. panner.positionX.linearRampToValueAtTime(_position.x, endTime);
  24265. panner.positionY.linearRampToValueAtTime(_position.y, endTime);
  24266. panner.positionZ.linearRampToValueAtTime(_position.z, endTime);
  24267. panner.orientationX.linearRampToValueAtTime(_orientation.x, endTime);
  24268. panner.orientationY.linearRampToValueAtTime(_orientation.y, endTime);
  24269. panner.orientationZ.linearRampToValueAtTime(_orientation.z, endTime);
  24270. } else {
  24271. panner.setPosition(_position.x, _position.y, _position.z);
  24272. panner.setOrientation(_orientation.x, _orientation.y, _orientation.z);
  24273. }
  24274. }
  24275. }
  24276. class AudioAnalyser {
  24277. constructor(audio, fftSize = 2048) {
  24278. this.analyser = audio.context.createAnalyser();
  24279. this.analyser.fftSize = fftSize;
  24280. this.data = new Uint8Array(this.analyser.frequencyBinCount);
  24281. audio.getOutput().connect(this.analyser);
  24282. }
  24283. getFrequencyData() {
  24284. this.analyser.getByteFrequencyData(this.data);
  24285. return this.data;
  24286. }
  24287. getAverageFrequency() {
  24288. let value = 0;
  24289. const data = this.getFrequencyData();
  24290. for (let i = 0; i < data.length; i++) {
  24291. value += data[i];
  24292. }
  24293. return value / data.length;
  24294. }
  24295. }
  24296. class PropertyMixer {
  24297. constructor(binding, typeName, valueSize) {
  24298. this.binding = binding;
  24299. this.valueSize = valueSize;
  24300. let mixFunction, mixFunctionAdditive, setIdentity; // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  24301. //
  24302. // interpolators can use .buffer as their .result
  24303. // the data then goes to 'incoming'
  24304. //
  24305. // 'accu0' and 'accu1' are used frame-interleaved for
  24306. // the cumulative result and are compared to detect
  24307. // changes
  24308. //
  24309. // 'orig' stores the original state of the property
  24310. //
  24311. // 'add' is used for additive cumulative results
  24312. //
  24313. // 'work' is optional and is only present for quaternion types. It is used
  24314. // to store intermediate quaternion multiplication results
  24315. switch (typeName) {
  24316. case 'quaternion':
  24317. mixFunction = this._slerp;
  24318. mixFunctionAdditive = this._slerpAdditive;
  24319. setIdentity = this._setAdditiveIdentityQuaternion;
  24320. this.buffer = new Float64Array(valueSize * 6);
  24321. this._workIndex = 5;
  24322. break;
  24323. case 'string':
  24324. case 'bool':
  24325. mixFunction = this._select; // Use the regular mix function and for additive on these types,
  24326. // additive is not relevant for non-numeric types
  24327. mixFunctionAdditive = this._select;
  24328. setIdentity = this._setAdditiveIdentityOther;
  24329. this.buffer = new Array(valueSize * 5);
  24330. break;
  24331. default:
  24332. mixFunction = this._lerp;
  24333. mixFunctionAdditive = this._lerpAdditive;
  24334. setIdentity = this._setAdditiveIdentityNumeric;
  24335. this.buffer = new Float64Array(valueSize * 5);
  24336. }
  24337. this._mixBufferRegion = mixFunction;
  24338. this._mixBufferRegionAdditive = mixFunctionAdditive;
  24339. this._setIdentity = setIdentity;
  24340. this._origIndex = 3;
  24341. this._addIndex = 4;
  24342. this.cumulativeWeight = 0;
  24343. this.cumulativeWeightAdditive = 0;
  24344. this.useCount = 0;
  24345. this.referenceCount = 0;
  24346. } // accumulate data in the 'incoming' region into 'accu<i>'
  24347. accumulate(accuIndex, weight) {
  24348. // note: happily accumulating nothing when weight = 0, the caller knows
  24349. // the weight and shouldn't have made the call in the first place
  24350. const buffer = this.buffer,
  24351. stride = this.valueSize,
  24352. offset = accuIndex * stride + stride;
  24353. let currentWeight = this.cumulativeWeight;
  24354. if (currentWeight === 0) {
  24355. // accuN := incoming * weight
  24356. for (let i = 0; i !== stride; ++i) {
  24357. buffer[offset + i] = buffer[i];
  24358. }
  24359. currentWeight = weight;
  24360. } else {
  24361. // accuN := accuN + incoming * weight
  24362. currentWeight += weight;
  24363. const mix = weight / currentWeight;
  24364. this._mixBufferRegion(buffer, offset, 0, mix, stride);
  24365. }
  24366. this.cumulativeWeight = currentWeight;
  24367. } // accumulate data in the 'incoming' region into 'add'
  24368. accumulateAdditive(weight) {
  24369. const buffer = this.buffer,
  24370. stride = this.valueSize,
  24371. offset = stride * this._addIndex;
  24372. if (this.cumulativeWeightAdditive === 0) {
  24373. // add = identity
  24374. this._setIdentity();
  24375. } // add := add + incoming * weight
  24376. this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride);
  24377. this.cumulativeWeightAdditive += weight;
  24378. } // apply the state of 'accu<i>' to the binding when accus differ
  24379. apply(accuIndex) {
  24380. const stride = this.valueSize,
  24381. buffer = this.buffer,
  24382. offset = accuIndex * stride + stride,
  24383. weight = this.cumulativeWeight,
  24384. weightAdditive = this.cumulativeWeightAdditive,
  24385. binding = this.binding;
  24386. this.cumulativeWeight = 0;
  24387. this.cumulativeWeightAdditive = 0;
  24388. if (weight < 1) {
  24389. // accuN := accuN + original * ( 1 - cumulativeWeight )
  24390. const originalValueOffset = stride * this._origIndex;
  24391. this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
  24392. }
  24393. if (weightAdditive > 0) {
  24394. // accuN := accuN + additive accuN
  24395. this._mixBufferRegionAdditive(buffer, offset, this._addIndex * stride, 1, stride);
  24396. }
  24397. for (let i = stride, e = stride + stride; i !== e; ++i) {
  24398. if (buffer[i] !== buffer[i + stride]) {
  24399. // value has changed -> update scene graph
  24400. binding.setValue(buffer, offset);
  24401. break;
  24402. }
  24403. }
  24404. } // remember the state of the bound property and copy it to both accus
  24405. saveOriginalState() {
  24406. const binding = this.binding;
  24407. const buffer = this.buffer,
  24408. stride = this.valueSize,
  24409. originalValueOffset = stride * this._origIndex;
  24410. binding.getValue(buffer, originalValueOffset); // accu[0..1] := orig -- initially detect changes against the original
  24411. for (let i = stride, e = originalValueOffset; i !== e; ++i) {
  24412. buffer[i] = buffer[originalValueOffset + i % stride];
  24413. } // Add to identity for additive
  24414. this._setIdentity();
  24415. this.cumulativeWeight = 0;
  24416. this.cumulativeWeightAdditive = 0;
  24417. } // apply the state previously taken via 'saveOriginalState' to the binding
  24418. restoreOriginalState() {
  24419. const originalValueOffset = this.valueSize * 3;
  24420. this.binding.setValue(this.buffer, originalValueOffset);
  24421. }
  24422. _setAdditiveIdentityNumeric() {
  24423. const startIndex = this._addIndex * this.valueSize;
  24424. const endIndex = startIndex + this.valueSize;
  24425. for (let i = startIndex; i < endIndex; i++) {
  24426. this.buffer[i] = 0;
  24427. }
  24428. }
  24429. _setAdditiveIdentityQuaternion() {
  24430. this._setAdditiveIdentityNumeric();
  24431. this.buffer[this._addIndex * this.valueSize + 3] = 1;
  24432. }
  24433. _setAdditiveIdentityOther() {
  24434. const startIndex = this._origIndex * this.valueSize;
  24435. const targetIndex = this._addIndex * this.valueSize;
  24436. for (let i = 0; i < this.valueSize; i++) {
  24437. this.buffer[targetIndex + i] = this.buffer[startIndex + i];
  24438. }
  24439. } // mix functions
  24440. _select(buffer, dstOffset, srcOffset, t, stride) {
  24441. if (t >= 0.5) {
  24442. for (let i = 0; i !== stride; ++i) {
  24443. buffer[dstOffset + i] = buffer[srcOffset + i];
  24444. }
  24445. }
  24446. }
  24447. _slerp(buffer, dstOffset, srcOffset, t) {
  24448. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
  24449. }
  24450. _slerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  24451. const workOffset = this._workIndex * stride; // Store result in intermediate buffer offset
  24452. Quaternion.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset); // Slerp to the intermediate result
  24453. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t);
  24454. }
  24455. _lerp(buffer, dstOffset, srcOffset, t, stride) {
  24456. const s = 1 - t;
  24457. for (let i = 0; i !== stride; ++i) {
  24458. const j = dstOffset + i;
  24459. buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
  24460. }
  24461. }
  24462. _lerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  24463. for (let i = 0; i !== stride; ++i) {
  24464. const j = dstOffset + i;
  24465. buffer[j] = buffer[j] + buffer[srcOffset + i] * t;
  24466. }
  24467. }
  24468. }
  24469. // Characters [].:/ are reserved for track binding syntax.
  24470. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  24471. const _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matches
  24472. // only latin characters, and the unicode \p{L} is not yet supported. So
  24473. // instead, we exclude reserved characters and match everything else.
  24474. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  24475. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must
  24476. // be matched to parse the rest of the track name.
  24477. const _directoryRe = /((?:WC+[\/:])*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  24478. const _nodeRe = /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object on target node, and accessor. May not contain reserved
  24479. // characters. Accessor may contain any character except closing bracket.
  24480. const _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor may
  24481. // contain any non-bracket characters.
  24482. const _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
  24483. const _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
  24484. const _supportedObjectNames = ['material', 'materials', 'bones'];
  24485. class Composite {
  24486. constructor(targetGroup, path, optionalParsedPath) {
  24487. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
  24488. this._targetGroup = targetGroup;
  24489. this._bindings = targetGroup.subscribe_(path, parsedPath);
  24490. }
  24491. getValue(array, offset) {
  24492. this.bind(); // bind all binding
  24493. const firstValidIndex = this._targetGroup.nCachedObjects_,
  24494. binding = this._bindings[firstValidIndex]; // and only call .getValue on the first
  24495. if (binding !== undefined) binding.getValue(array, offset);
  24496. }
  24497. setValue(array, offset) {
  24498. const bindings = this._bindings;
  24499. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  24500. bindings[i].setValue(array, offset);
  24501. }
  24502. }
  24503. bind() {
  24504. const bindings = this._bindings;
  24505. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  24506. bindings[i].bind();
  24507. }
  24508. }
  24509. unbind() {
  24510. const bindings = this._bindings;
  24511. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  24512. bindings[i].unbind();
  24513. }
  24514. }
  24515. } // Note: This class uses a State pattern on a per-method basis:
  24516. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  24517. // prototype version of these methods with one that represents
  24518. // the bound state. When the property is not found, the methods
  24519. // become no-ops.
  24520. class PropertyBinding {
  24521. constructor(rootNode, path, parsedPath) {
  24522. this.path = path;
  24523. this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
  24524. this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
  24525. this.rootNode = rootNode; // initial state of these methods that calls 'bind'
  24526. this.getValue = this._getValue_unbound;
  24527. this.setValue = this._setValue_unbound;
  24528. }
  24529. static create(root, path, parsedPath) {
  24530. if (!(root && root.isAnimationObjectGroup)) {
  24531. return new PropertyBinding(root, path, parsedPath);
  24532. } else {
  24533. return new PropertyBinding.Composite(root, path, parsedPath);
  24534. }
  24535. }
  24536. /**
  24537. * Replaces spaces with underscores and removes unsupported characters from
  24538. * node names, to ensure compatibility with parseTrackName().
  24539. *
  24540. * @param {string} name Node name to be sanitized.
  24541. * @return {string}
  24542. */
  24543. static sanitizeNodeName(name) {
  24544. return name.replace(/\s/g, '_').replace(_reservedRe, '');
  24545. }
  24546. static parseTrackName(trackName) {
  24547. const matches = _trackRe.exec(trackName);
  24548. if (!matches) {
  24549. throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
  24550. }
  24551. const results = {
  24552. // directoryName: matches[ 1 ], // (tschw) currently unused
  24553. nodeName: matches[2],
  24554. objectName: matches[3],
  24555. objectIndex: matches[4],
  24556. propertyName: matches[5],
  24557. // required
  24558. propertyIndex: matches[6]
  24559. };
  24560. const lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
  24561. if (lastDot !== undefined && lastDot !== -1) {
  24562. const objectName = results.nodeName.substring(lastDot + 1); // Object names must be checked against an allowlist. Otherwise, there
  24563. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  24564. // 'bar' could be the objectName, or part of a nodeName (which can
  24565. // include '.' characters).
  24566. if (_supportedObjectNames.indexOf(objectName) !== -1) {
  24567. results.nodeName = results.nodeName.substring(0, lastDot);
  24568. results.objectName = objectName;
  24569. }
  24570. }
  24571. if (results.propertyName === null || results.propertyName.length === 0) {
  24572. throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
  24573. }
  24574. return results;
  24575. }
  24576. static findNode(root, nodeName) {
  24577. if (!nodeName || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
  24578. return root;
  24579. } // search into skeleton bones.
  24580. if (root.skeleton) {
  24581. const bone = root.skeleton.getBoneByName(nodeName);
  24582. if (bone !== undefined) {
  24583. return bone;
  24584. }
  24585. } // search into node subtree.
  24586. if (root.children) {
  24587. const searchNodeSubtree = function (children) {
  24588. for (let i = 0; i < children.length; i++) {
  24589. const childNode = children[i];
  24590. if (childNode.name === nodeName || childNode.uuid === nodeName) {
  24591. return childNode;
  24592. }
  24593. const result = searchNodeSubtree(childNode.children);
  24594. if (result) return result;
  24595. }
  24596. return null;
  24597. };
  24598. const subTreeNode = searchNodeSubtree(root.children);
  24599. if (subTreeNode) {
  24600. return subTreeNode;
  24601. }
  24602. }
  24603. return null;
  24604. } // these are used to "bind" a nonexistent property
  24605. _getValue_unavailable() {}
  24606. _setValue_unavailable() {} // Getters
  24607. _getValue_direct(buffer, offset) {
  24608. buffer[offset] = this.node[this.propertyName];
  24609. }
  24610. _getValue_array(buffer, offset) {
  24611. const source = this.resolvedProperty;
  24612. for (let i = 0, n = source.length; i !== n; ++i) {
  24613. buffer[offset++] = source[i];
  24614. }
  24615. }
  24616. _getValue_arrayElement(buffer, offset) {
  24617. buffer[offset] = this.resolvedProperty[this.propertyIndex];
  24618. }
  24619. _getValue_toArray(buffer, offset) {
  24620. this.resolvedProperty.toArray(buffer, offset);
  24621. } // Direct
  24622. _setValue_direct(buffer, offset) {
  24623. this.targetObject[this.propertyName] = buffer[offset];
  24624. }
  24625. _setValue_direct_setNeedsUpdate(buffer, offset) {
  24626. this.targetObject[this.propertyName] = buffer[offset];
  24627. this.targetObject.needsUpdate = true;
  24628. }
  24629. _setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
  24630. this.targetObject[this.propertyName] = buffer[offset];
  24631. this.targetObject.matrixWorldNeedsUpdate = true;
  24632. } // EntireArray
  24633. _setValue_array(buffer, offset) {
  24634. const dest = this.resolvedProperty;
  24635. for (let i = 0, n = dest.length; i !== n; ++i) {
  24636. dest[i] = buffer[offset++];
  24637. }
  24638. }
  24639. _setValue_array_setNeedsUpdate(buffer, offset) {
  24640. const dest = this.resolvedProperty;
  24641. for (let i = 0, n = dest.length; i !== n; ++i) {
  24642. dest[i] = buffer[offset++];
  24643. }
  24644. this.targetObject.needsUpdate = true;
  24645. }
  24646. _setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
  24647. const dest = this.resolvedProperty;
  24648. for (let i = 0, n = dest.length; i !== n; ++i) {
  24649. dest[i] = buffer[offset++];
  24650. }
  24651. this.targetObject.matrixWorldNeedsUpdate = true;
  24652. } // ArrayElement
  24653. _setValue_arrayElement(buffer, offset) {
  24654. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  24655. }
  24656. _setValue_arrayElement_setNeedsUpdate(buffer, offset) {
  24657. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  24658. this.targetObject.needsUpdate = true;
  24659. }
  24660. _setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
  24661. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  24662. this.targetObject.matrixWorldNeedsUpdate = true;
  24663. } // HasToFromArray
  24664. _setValue_fromArray(buffer, offset) {
  24665. this.resolvedProperty.fromArray(buffer, offset);
  24666. }
  24667. _setValue_fromArray_setNeedsUpdate(buffer, offset) {
  24668. this.resolvedProperty.fromArray(buffer, offset);
  24669. this.targetObject.needsUpdate = true;
  24670. }
  24671. _setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
  24672. this.resolvedProperty.fromArray(buffer, offset);
  24673. this.targetObject.matrixWorldNeedsUpdate = true;
  24674. }
  24675. _getValue_unbound(targetArray, offset) {
  24676. this.bind();
  24677. this.getValue(targetArray, offset);
  24678. }
  24679. _setValue_unbound(sourceArray, offset) {
  24680. this.bind();
  24681. this.setValue(sourceArray, offset);
  24682. } // create getter / setter pair for a property in the scene graph
  24683. bind() {
  24684. let targetObject = this.node;
  24685. const parsedPath = this.parsedPath;
  24686. const objectName = parsedPath.objectName;
  24687. const propertyName = parsedPath.propertyName;
  24688. let propertyIndex = parsedPath.propertyIndex;
  24689. if (!targetObject) {
  24690. targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
  24691. this.node = targetObject;
  24692. } // set fail state so we can just 'return' on error
  24693. this.getValue = this._getValue_unavailable;
  24694. this.setValue = this._setValue_unavailable; // ensure there is a value node
  24695. if (!targetObject) {
  24696. console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
  24697. return;
  24698. }
  24699. if (objectName) {
  24700. let objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials....
  24701. switch (objectName) {
  24702. case 'materials':
  24703. if (!targetObject.material) {
  24704. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  24705. return;
  24706. }
  24707. if (!targetObject.material.materials) {
  24708. console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
  24709. return;
  24710. }
  24711. targetObject = targetObject.material.materials;
  24712. break;
  24713. case 'bones':
  24714. if (!targetObject.skeleton) {
  24715. console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
  24716. return;
  24717. } // potential future optimization: skip this if propertyIndex is already an integer
  24718. // and convert the integer string to a true integer.
  24719. targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.
  24720. for (let i = 0; i < targetObject.length; i++) {
  24721. if (targetObject[i].name === objectIndex) {
  24722. objectIndex = i;
  24723. break;
  24724. }
  24725. }
  24726. break;
  24727. default:
  24728. if (targetObject[objectName] === undefined) {
  24729. console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
  24730. return;
  24731. }
  24732. targetObject = targetObject[objectName];
  24733. }
  24734. if (objectIndex !== undefined) {
  24735. if (targetObject[objectIndex] === undefined) {
  24736. console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
  24737. return;
  24738. }
  24739. targetObject = targetObject[objectIndex];
  24740. }
  24741. } // resolve property
  24742. const nodeProperty = targetObject[propertyName];
  24743. if (nodeProperty === undefined) {
  24744. const nodeName = parsedPath.nodeName;
  24745. console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
  24746. return;
  24747. } // determine versioning scheme
  24748. let versioning = this.Versioning.None;
  24749. this.targetObject = targetObject;
  24750. if (targetObject.needsUpdate !== undefined) {
  24751. // material
  24752. versioning = this.Versioning.NeedsUpdate;
  24753. } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
  24754. // node transform
  24755. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  24756. } // determine how the property gets bound
  24757. let bindingType = this.BindingType.Direct;
  24758. if (propertyIndex !== undefined) {
  24759. // access a sub element of the property array (only primitives are supported right now)
  24760. if (propertyName === 'morphTargetInfluences') {
  24761. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  24762. // support resolving morphTarget names into indices.
  24763. if (!targetObject.geometry) {
  24764. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
  24765. return;
  24766. }
  24767. if (targetObject.geometry.isBufferGeometry) {
  24768. if (!targetObject.geometry.morphAttributes) {
  24769. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
  24770. return;
  24771. }
  24772. if (targetObject.morphTargetDictionary[propertyIndex] !== undefined) {
  24773. propertyIndex = targetObject.morphTargetDictionary[propertyIndex];
  24774. }
  24775. } else {
  24776. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this);
  24777. return;
  24778. }
  24779. }
  24780. bindingType = this.BindingType.ArrayElement;
  24781. this.resolvedProperty = nodeProperty;
  24782. this.propertyIndex = propertyIndex;
  24783. } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
  24784. // must use copy for Object3D.Euler/Quaternion
  24785. bindingType = this.BindingType.HasFromToArray;
  24786. this.resolvedProperty = nodeProperty;
  24787. } else if (Array.isArray(nodeProperty)) {
  24788. bindingType = this.BindingType.EntireArray;
  24789. this.resolvedProperty = nodeProperty;
  24790. } else {
  24791. this.propertyName = propertyName;
  24792. } // select getter / setter
  24793. this.getValue = this.GetterByBindingType[bindingType];
  24794. this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  24795. }
  24796. unbind() {
  24797. this.node = null; // back to the prototype version of getValue / setValue
  24798. // note: avoiding to mutate the shape of 'this' via 'delete'
  24799. this.getValue = this._getValue_unbound;
  24800. this.setValue = this._setValue_unbound;
  24801. }
  24802. }
  24803. PropertyBinding.Composite = Composite;
  24804. PropertyBinding.prototype.BindingType = {
  24805. Direct: 0,
  24806. EntireArray: 1,
  24807. ArrayElement: 2,
  24808. HasFromToArray: 3
  24809. };
  24810. PropertyBinding.prototype.Versioning = {
  24811. None: 0,
  24812. NeedsUpdate: 1,
  24813. MatrixWorldNeedsUpdate: 2
  24814. };
  24815. PropertyBinding.prototype.GetterByBindingType = [PropertyBinding.prototype._getValue_direct, PropertyBinding.prototype._getValue_array, PropertyBinding.prototype._getValue_arrayElement, PropertyBinding.prototype._getValue_toArray];
  24816. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [[// Direct
  24817. PropertyBinding.prototype._setValue_direct, PropertyBinding.prototype._setValue_direct_setNeedsUpdate, PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate], [// EntireArray
  24818. PropertyBinding.prototype._setValue_array, PropertyBinding.prototype._setValue_array_setNeedsUpdate, PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate], [// ArrayElement
  24819. PropertyBinding.prototype._setValue_arrayElement, PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate, PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate], [// HasToFromArray
  24820. PropertyBinding.prototype._setValue_fromArray, PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate, PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];
  24821. /**
  24822. *
  24823. * A group of objects that receives a shared animation state.
  24824. *
  24825. * Usage:
  24826. *
  24827. * - Add objects you would otherwise pass as 'root' to the
  24828. * constructor or the .clipAction method of AnimationMixer.
  24829. *
  24830. * - Instead pass this object as 'root'.
  24831. *
  24832. * - You can also add and remove objects later when the mixer
  24833. * is running.
  24834. *
  24835. * Note:
  24836. *
  24837. * Objects of this class appear as one object to the mixer,
  24838. * so cache control of the individual objects must be done
  24839. * on the group.
  24840. *
  24841. * Limitation:
  24842. *
  24843. * - The animated properties must be compatible among the
  24844. * all objects in the group.
  24845. *
  24846. * - A single property can either be controlled through a
  24847. * target group or directly, but not both.
  24848. */
  24849. class AnimationObjectGroup {
  24850. constructor() {
  24851. this.uuid = generateUUID(); // cached objects followed by the active ones
  24852. this._objects = Array.prototype.slice.call(arguments);
  24853. this.nCachedObjects_ = 0; // threshold
  24854. // note: read by PropertyBinding.Composite
  24855. const indices = {};
  24856. this._indicesByUUID = indices; // for bookkeeping
  24857. for (let i = 0, n = arguments.length; i !== n; ++i) {
  24858. indices[arguments[i].uuid] = i;
  24859. }
  24860. this._paths = []; // inside: string
  24861. this._parsedPaths = []; // inside: { we don't care, here }
  24862. this._bindings = []; // inside: Array< PropertyBinding >
  24863. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  24864. const scope = this;
  24865. this.stats = {
  24866. objects: {
  24867. get total() {
  24868. return scope._objects.length;
  24869. },
  24870. get inUse() {
  24871. return this.total - scope.nCachedObjects_;
  24872. }
  24873. },
  24874. get bindingsPerObject() {
  24875. return scope._bindings.length;
  24876. }
  24877. };
  24878. }
  24879. add() {
  24880. const objects = this._objects,
  24881. indicesByUUID = this._indicesByUUID,
  24882. paths = this._paths,
  24883. parsedPaths = this._parsedPaths,
  24884. bindings = this._bindings,
  24885. nBindings = bindings.length;
  24886. let knownObject = undefined,
  24887. nObjects = objects.length,
  24888. nCachedObjects = this.nCachedObjects_;
  24889. for (let i = 0, n = arguments.length; i !== n; ++i) {
  24890. const object = arguments[i],
  24891. uuid = object.uuid;
  24892. let index = indicesByUUID[uuid];
  24893. if (index === undefined) {
  24894. // unknown object -> add it to the ACTIVE region
  24895. index = nObjects++;
  24896. indicesByUUID[uuid] = index;
  24897. objects.push(object); // accounting is done, now do the same for all bindings
  24898. for (let j = 0, m = nBindings; j !== m; ++j) {
  24899. bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
  24900. }
  24901. } else if (index < nCachedObjects) {
  24902. knownObject = objects[index]; // move existing object to the ACTIVE region
  24903. const firstActiveIndex = --nCachedObjects,
  24904. lastCachedObject = objects[firstActiveIndex];
  24905. indicesByUUID[lastCachedObject.uuid] = index;
  24906. objects[index] = lastCachedObject;
  24907. indicesByUUID[uuid] = firstActiveIndex;
  24908. objects[firstActiveIndex] = object; // accounting is done, now do the same for all bindings
  24909. for (let j = 0, m = nBindings; j !== m; ++j) {
  24910. const bindingsForPath = bindings[j],
  24911. lastCached = bindingsForPath[firstActiveIndex];
  24912. let binding = bindingsForPath[index];
  24913. bindingsForPath[index] = lastCached;
  24914. if (binding === undefined) {
  24915. // since we do not bother to create new bindings
  24916. // for objects that are cached, the binding may
  24917. // or may not exist
  24918. binding = new PropertyBinding(object, paths[j], parsedPaths[j]);
  24919. }
  24920. bindingsForPath[firstActiveIndex] = binding;
  24921. }
  24922. } else if (objects[index] !== knownObject) {
  24923. console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
  24924. } // else the object is already where we want it to be
  24925. } // for arguments
  24926. this.nCachedObjects_ = nCachedObjects;
  24927. }
  24928. remove() {
  24929. const objects = this._objects,
  24930. indicesByUUID = this._indicesByUUID,
  24931. bindings = this._bindings,
  24932. nBindings = bindings.length;
  24933. let nCachedObjects = this.nCachedObjects_;
  24934. for (let i = 0, n = arguments.length; i !== n; ++i) {
  24935. const object = arguments[i],
  24936. uuid = object.uuid,
  24937. index = indicesByUUID[uuid];
  24938. if (index !== undefined && index >= nCachedObjects) {
  24939. // move existing object into the CACHED region
  24940. const lastCachedIndex = nCachedObjects++,
  24941. firstActiveObject = objects[lastCachedIndex];
  24942. indicesByUUID[firstActiveObject.uuid] = index;
  24943. objects[index] = firstActiveObject;
  24944. indicesByUUID[uuid] = lastCachedIndex;
  24945. objects[lastCachedIndex] = object; // accounting is done, now do the same for all bindings
  24946. for (let j = 0, m = nBindings; j !== m; ++j) {
  24947. const bindingsForPath = bindings[j],
  24948. firstActive = bindingsForPath[lastCachedIndex],
  24949. binding = bindingsForPath[index];
  24950. bindingsForPath[index] = firstActive;
  24951. bindingsForPath[lastCachedIndex] = binding;
  24952. }
  24953. }
  24954. } // for arguments
  24955. this.nCachedObjects_ = nCachedObjects;
  24956. } // remove & forget
  24957. uncache() {
  24958. const objects = this._objects,
  24959. indicesByUUID = this._indicesByUUID,
  24960. bindings = this._bindings,
  24961. nBindings = bindings.length;
  24962. let nCachedObjects = this.nCachedObjects_,
  24963. nObjects = objects.length;
  24964. for (let i = 0, n = arguments.length; i !== n; ++i) {
  24965. const object = arguments[i],
  24966. uuid = object.uuid,
  24967. index = indicesByUUID[uuid];
  24968. if (index !== undefined) {
  24969. delete indicesByUUID[uuid];
  24970. if (index < nCachedObjects) {
  24971. // object is cached, shrink the CACHED region
  24972. const firstActiveIndex = --nCachedObjects,
  24973. lastCachedObject = objects[firstActiveIndex],
  24974. lastIndex = --nObjects,
  24975. lastObject = objects[lastIndex]; // last cached object takes this object's place
  24976. indicesByUUID[lastCachedObject.uuid] = index;
  24977. objects[index] = lastCachedObject; // last object goes to the activated slot and pop
  24978. indicesByUUID[lastObject.uuid] = firstActiveIndex;
  24979. objects[firstActiveIndex] = lastObject;
  24980. objects.pop(); // accounting is done, now do the same for all bindings
  24981. for (let j = 0, m = nBindings; j !== m; ++j) {
  24982. const bindingsForPath = bindings[j],
  24983. lastCached = bindingsForPath[firstActiveIndex],
  24984. last = bindingsForPath[lastIndex];
  24985. bindingsForPath[index] = lastCached;
  24986. bindingsForPath[firstActiveIndex] = last;
  24987. bindingsForPath.pop();
  24988. }
  24989. } else {
  24990. // object is active, just swap with the last and pop
  24991. const lastIndex = --nObjects,
  24992. lastObject = objects[lastIndex];
  24993. if (lastIndex > 0) {
  24994. indicesByUUID[lastObject.uuid] = index;
  24995. }
  24996. objects[index] = lastObject;
  24997. objects.pop(); // accounting is done, now do the same for all bindings
  24998. for (let j = 0, m = nBindings; j !== m; ++j) {
  24999. const bindingsForPath = bindings[j];
  25000. bindingsForPath[index] = bindingsForPath[lastIndex];
  25001. bindingsForPath.pop();
  25002. }
  25003. } // cached or active
  25004. } // if object is known
  25005. } // for arguments
  25006. this.nCachedObjects_ = nCachedObjects;
  25007. } // Internal interface used by befriended PropertyBinding.Composite:
  25008. subscribe_(path, parsedPath) {
  25009. // returns an array of bindings for the given path that is changed
  25010. // according to the contained objects in the group
  25011. const indicesByPath = this._bindingsIndicesByPath;
  25012. let index = indicesByPath[path];
  25013. const bindings = this._bindings;
  25014. if (index !== undefined) return bindings[index];
  25015. const paths = this._paths,
  25016. parsedPaths = this._parsedPaths,
  25017. objects = this._objects,
  25018. nObjects = objects.length,
  25019. nCachedObjects = this.nCachedObjects_,
  25020. bindingsForPath = new Array(nObjects);
  25021. index = bindings.length;
  25022. indicesByPath[path] = index;
  25023. paths.push(path);
  25024. parsedPaths.push(parsedPath);
  25025. bindings.push(bindingsForPath);
  25026. for (let i = nCachedObjects, n = objects.length; i !== n; ++i) {
  25027. const object = objects[i];
  25028. bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
  25029. }
  25030. return bindingsForPath;
  25031. }
  25032. unsubscribe_(path) {
  25033. // tells the group to forget about a property path and no longer
  25034. // update the array previously obtained with 'subscribe_'
  25035. const indicesByPath = this._bindingsIndicesByPath,
  25036. index = indicesByPath[path];
  25037. if (index !== undefined) {
  25038. const paths = this._paths,
  25039. parsedPaths = this._parsedPaths,
  25040. bindings = this._bindings,
  25041. lastBindingsIndex = bindings.length - 1,
  25042. lastBindings = bindings[lastBindingsIndex],
  25043. lastBindingsPath = path[lastBindingsIndex];
  25044. indicesByPath[lastBindingsPath] = index;
  25045. bindings[index] = lastBindings;
  25046. bindings.pop();
  25047. parsedPaths[index] = parsedPaths[lastBindingsIndex];
  25048. parsedPaths.pop();
  25049. paths[index] = paths[lastBindingsIndex];
  25050. paths.pop();
  25051. }
  25052. }
  25053. }
  25054. AnimationObjectGroup.prototype.isAnimationObjectGroup = true;
  25055. class AnimationAction {
  25056. constructor(mixer, clip, localRoot = null, blendMode = clip.blendMode) {
  25057. this._mixer = mixer;
  25058. this._clip = clip;
  25059. this._localRoot = localRoot;
  25060. this.blendMode = blendMode;
  25061. const tracks = clip.tracks,
  25062. nTracks = tracks.length,
  25063. interpolants = new Array(nTracks);
  25064. const interpolantSettings = {
  25065. endingStart: ZeroCurvatureEnding,
  25066. endingEnd: ZeroCurvatureEnding
  25067. };
  25068. for (let i = 0; i !== nTracks; ++i) {
  25069. const interpolant = tracks[i].createInterpolant(null);
  25070. interpolants[i] = interpolant;
  25071. interpolant.settings = interpolantSettings;
  25072. }
  25073. this._interpolantSettings = interpolantSettings;
  25074. this._interpolants = interpolants; // bound by the mixer
  25075. // inside: PropertyMixer (managed by the mixer)
  25076. this._propertyBindings = new Array(nTracks);
  25077. this._cacheIndex = null; // for the memory manager
  25078. this._byClipCacheIndex = null; // for the memory manager
  25079. this._timeScaleInterpolant = null;
  25080. this._weightInterpolant = null;
  25081. this.loop = LoopRepeat;
  25082. this._loopCount = -1; // global mixer time when the action is to be started
  25083. // it's set back to 'null' upon start of the action
  25084. this._startTime = null; // scaled local time of the action
  25085. // gets clamped or wrapped to 0..clip.duration according to loop
  25086. this.time = 0;
  25087. this.timeScale = 1;
  25088. this._effectiveTimeScale = 1;
  25089. this.weight = 1;
  25090. this._effectiveWeight = 1;
  25091. this.repetitions = Infinity; // no. of repetitions when looping
  25092. this.paused = false; // true -> zero effective time scale
  25093. this.enabled = true; // false -> zero effective weight
  25094. this.clampWhenFinished = false; // keep feeding the last frame?
  25095. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  25096. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  25097. } // State & Scheduling
  25098. play() {
  25099. this._mixer._activateAction(this);
  25100. return this;
  25101. }
  25102. stop() {
  25103. this._mixer._deactivateAction(this);
  25104. return this.reset();
  25105. }
  25106. reset() {
  25107. this.paused = false;
  25108. this.enabled = true;
  25109. this.time = 0; // restart clip
  25110. this._loopCount = -1; // forget previous loops
  25111. this._startTime = null; // forget scheduling
  25112. return this.stopFading().stopWarping();
  25113. }
  25114. isRunning() {
  25115. return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  25116. } // return true when play has been called
  25117. isScheduled() {
  25118. return this._mixer._isActiveAction(this);
  25119. }
  25120. startAt(time) {
  25121. this._startTime = time;
  25122. return this;
  25123. }
  25124. setLoop(mode, repetitions) {
  25125. this.loop = mode;
  25126. this.repetitions = repetitions;
  25127. return this;
  25128. } // Weight
  25129. // set the weight stopping any scheduled fading
  25130. // although .enabled = false yields an effective weight of zero, this
  25131. // method does *not* change .enabled, because it would be confusing
  25132. setEffectiveWeight(weight) {
  25133. this.weight = weight; // note: same logic as when updated at runtime
  25134. this._effectiveWeight = this.enabled ? weight : 0;
  25135. return this.stopFading();
  25136. } // return the weight considering fading and .enabled
  25137. getEffectiveWeight() {
  25138. return this._effectiveWeight;
  25139. }
  25140. fadeIn(duration) {
  25141. return this._scheduleFading(duration, 0, 1);
  25142. }
  25143. fadeOut(duration) {
  25144. return this._scheduleFading(duration, 1, 0);
  25145. }
  25146. crossFadeFrom(fadeOutAction, duration, warp) {
  25147. fadeOutAction.fadeOut(duration);
  25148. this.fadeIn(duration);
  25149. if (warp) {
  25150. const fadeInDuration = this._clip.duration,
  25151. fadeOutDuration = fadeOutAction._clip.duration,
  25152. startEndRatio = fadeOutDuration / fadeInDuration,
  25153. endStartRatio = fadeInDuration / fadeOutDuration;
  25154. fadeOutAction.warp(1.0, startEndRatio, duration);
  25155. this.warp(endStartRatio, 1.0, duration);
  25156. }
  25157. return this;
  25158. }
  25159. crossFadeTo(fadeInAction, duration, warp) {
  25160. return fadeInAction.crossFadeFrom(this, duration, warp);
  25161. }
  25162. stopFading() {
  25163. const weightInterpolant = this._weightInterpolant;
  25164. if (weightInterpolant !== null) {
  25165. this._weightInterpolant = null;
  25166. this._mixer._takeBackControlInterpolant(weightInterpolant);
  25167. }
  25168. return this;
  25169. } // Time Scale Control
  25170. // set the time scale stopping any scheduled warping
  25171. // although .paused = true yields an effective time scale of zero, this
  25172. // method does *not* change .paused, because it would be confusing
  25173. setEffectiveTimeScale(timeScale) {
  25174. this.timeScale = timeScale;
  25175. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  25176. return this.stopWarping();
  25177. } // return the time scale considering warping and .paused
  25178. getEffectiveTimeScale() {
  25179. return this._effectiveTimeScale;
  25180. }
  25181. setDuration(duration) {
  25182. this.timeScale = this._clip.duration / duration;
  25183. return this.stopWarping();
  25184. }
  25185. syncWith(action) {
  25186. this.time = action.time;
  25187. this.timeScale = action.timeScale;
  25188. return this.stopWarping();
  25189. }
  25190. halt(duration) {
  25191. return this.warp(this._effectiveTimeScale, 0, duration);
  25192. }
  25193. warp(startTimeScale, endTimeScale, duration) {
  25194. const mixer = this._mixer,
  25195. now = mixer.time,
  25196. timeScale = this.timeScale;
  25197. let interpolant = this._timeScaleInterpolant;
  25198. if (interpolant === null) {
  25199. interpolant = mixer._lendControlInterpolant();
  25200. this._timeScaleInterpolant = interpolant;
  25201. }
  25202. const times = interpolant.parameterPositions,
  25203. values = interpolant.sampleValues;
  25204. times[0] = now;
  25205. times[1] = now + duration;
  25206. values[0] = startTimeScale / timeScale;
  25207. values[1] = endTimeScale / timeScale;
  25208. return this;
  25209. }
  25210. stopWarping() {
  25211. const timeScaleInterpolant = this._timeScaleInterpolant;
  25212. if (timeScaleInterpolant !== null) {
  25213. this._timeScaleInterpolant = null;
  25214. this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
  25215. }
  25216. return this;
  25217. } // Object Accessors
  25218. getMixer() {
  25219. return this._mixer;
  25220. }
  25221. getClip() {
  25222. return this._clip;
  25223. }
  25224. getRoot() {
  25225. return this._localRoot || this._mixer._root;
  25226. } // Interna
  25227. _update(time, deltaTime, timeDirection, accuIndex) {
  25228. // called by the mixer
  25229. if (!this.enabled) {
  25230. // call ._updateWeight() to update ._effectiveWeight
  25231. this._updateWeight(time);
  25232. return;
  25233. }
  25234. const startTime = this._startTime;
  25235. if (startTime !== null) {
  25236. // check for scheduled start of action
  25237. const timeRunning = (time - startTime) * timeDirection;
  25238. if (timeRunning < 0 || timeDirection === 0) {
  25239. return; // yet to come / don't decide when delta = 0
  25240. } // start
  25241. this._startTime = null; // unschedule
  25242. deltaTime = timeDirection * timeRunning;
  25243. } // apply time scale and advance time
  25244. deltaTime *= this._updateTimeScale(time);
  25245. const clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting in
  25246. // an effective weight of 0
  25247. const weight = this._updateWeight(time);
  25248. if (weight > 0) {
  25249. const interpolants = this._interpolants;
  25250. const propertyMixers = this._propertyBindings;
  25251. switch (this.blendMode) {
  25252. case AdditiveAnimationBlendMode:
  25253. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  25254. interpolants[j].evaluate(clipTime);
  25255. propertyMixers[j].accumulateAdditive(weight);
  25256. }
  25257. break;
  25258. case NormalAnimationBlendMode:
  25259. default:
  25260. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  25261. interpolants[j].evaluate(clipTime);
  25262. propertyMixers[j].accumulate(accuIndex, weight);
  25263. }
  25264. }
  25265. }
  25266. }
  25267. _updateWeight(time) {
  25268. let weight = 0;
  25269. if (this.enabled) {
  25270. weight = this.weight;
  25271. const interpolant = this._weightInterpolant;
  25272. if (interpolant !== null) {
  25273. const interpolantValue = interpolant.evaluate(time)[0];
  25274. weight *= interpolantValue;
  25275. if (time > interpolant.parameterPositions[1]) {
  25276. this.stopFading();
  25277. if (interpolantValue === 0) {
  25278. // faded out, disable
  25279. this.enabled = false;
  25280. }
  25281. }
  25282. }
  25283. }
  25284. this._effectiveWeight = weight;
  25285. return weight;
  25286. }
  25287. _updateTimeScale(time) {
  25288. let timeScale = 0;
  25289. if (!this.paused) {
  25290. timeScale = this.timeScale;
  25291. const interpolant = this._timeScaleInterpolant;
  25292. if (interpolant !== null) {
  25293. const interpolantValue = interpolant.evaluate(time)[0];
  25294. timeScale *= interpolantValue;
  25295. if (time > interpolant.parameterPositions[1]) {
  25296. this.stopWarping();
  25297. if (timeScale === 0) {
  25298. // motion has halted, pause
  25299. this.paused = true;
  25300. } else {
  25301. // warp done - apply final time scale
  25302. this.timeScale = timeScale;
  25303. }
  25304. }
  25305. }
  25306. }
  25307. this._effectiveTimeScale = timeScale;
  25308. return timeScale;
  25309. }
  25310. _updateTime(deltaTime) {
  25311. const duration = this._clip.duration;
  25312. const loop = this.loop;
  25313. let time = this.time + deltaTime;
  25314. let loopCount = this._loopCount;
  25315. const pingPong = loop === LoopPingPong;
  25316. if (deltaTime === 0) {
  25317. if (loopCount === -1) return time;
  25318. return pingPong && (loopCount & 1) === 1 ? duration - time : time;
  25319. }
  25320. if (loop === LoopOnce) {
  25321. if (loopCount === -1) {
  25322. // just started
  25323. this._loopCount = 0;
  25324. this._setEndings(true, true, false);
  25325. }
  25326. handle_stop: {
  25327. if (time >= duration) {
  25328. time = duration;
  25329. } else if (time < 0) {
  25330. time = 0;
  25331. } else {
  25332. this.time = time;
  25333. break handle_stop;
  25334. }
  25335. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  25336. this.time = time;
  25337. this._mixer.dispatchEvent({
  25338. type: 'finished',
  25339. action: this,
  25340. direction: deltaTime < 0 ? -1 : 1
  25341. });
  25342. }
  25343. } else {
  25344. // repetitive Repeat or PingPong
  25345. if (loopCount === -1) {
  25346. // just started
  25347. if (deltaTime >= 0) {
  25348. loopCount = 0;
  25349. this._setEndings(true, this.repetitions === 0, pingPong);
  25350. } else {
  25351. // when looping in reverse direction, the initial
  25352. // transition through zero counts as a repetition,
  25353. // so leave loopCount at -1
  25354. this._setEndings(this.repetitions === 0, true, pingPong);
  25355. }
  25356. }
  25357. if (time >= duration || time < 0) {
  25358. // wrap around
  25359. const loopDelta = Math.floor(time / duration); // signed
  25360. time -= duration * loopDelta;
  25361. loopCount += Math.abs(loopDelta);
  25362. const pending = this.repetitions - loopCount;
  25363. if (pending <= 0) {
  25364. // have to stop (switch state, clamp time, fire event)
  25365. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  25366. time = deltaTime > 0 ? duration : 0;
  25367. this.time = time;
  25368. this._mixer.dispatchEvent({
  25369. type: 'finished',
  25370. action: this,
  25371. direction: deltaTime > 0 ? 1 : -1
  25372. });
  25373. } else {
  25374. // keep running
  25375. if (pending === 1) {
  25376. // entering the last round
  25377. const atStart = deltaTime < 0;
  25378. this._setEndings(atStart, !atStart, pingPong);
  25379. } else {
  25380. this._setEndings(false, false, pingPong);
  25381. }
  25382. this._loopCount = loopCount;
  25383. this.time = time;
  25384. this._mixer.dispatchEvent({
  25385. type: 'loop',
  25386. action: this,
  25387. loopDelta: loopDelta
  25388. });
  25389. }
  25390. } else {
  25391. this.time = time;
  25392. }
  25393. if (pingPong && (loopCount & 1) === 1) {
  25394. // invert time for the "pong round"
  25395. return duration - time;
  25396. }
  25397. }
  25398. return time;
  25399. }
  25400. _setEndings(atStart, atEnd, pingPong) {
  25401. const settings = this._interpolantSettings;
  25402. if (pingPong) {
  25403. settings.endingStart = ZeroSlopeEnding;
  25404. settings.endingEnd = ZeroSlopeEnding;
  25405. } else {
  25406. // assuming for LoopOnce atStart == atEnd == true
  25407. if (atStart) {
  25408. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  25409. } else {
  25410. settings.endingStart = WrapAroundEnding;
  25411. }
  25412. if (atEnd) {
  25413. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  25414. } else {
  25415. settings.endingEnd = WrapAroundEnding;
  25416. }
  25417. }
  25418. }
  25419. _scheduleFading(duration, weightNow, weightThen) {
  25420. const mixer = this._mixer,
  25421. now = mixer.time;
  25422. let interpolant = this._weightInterpolant;
  25423. if (interpolant === null) {
  25424. interpolant = mixer._lendControlInterpolant();
  25425. this._weightInterpolant = interpolant;
  25426. }
  25427. const times = interpolant.parameterPositions,
  25428. values = interpolant.sampleValues;
  25429. times[0] = now;
  25430. values[0] = weightNow;
  25431. times[1] = now + duration;
  25432. values[1] = weightThen;
  25433. return this;
  25434. }
  25435. }
  25436. class AnimationMixer extends EventDispatcher {
  25437. constructor(root) {
  25438. super();
  25439. this._root = root;
  25440. this._initMemoryManager();
  25441. this._accuIndex = 0;
  25442. this.time = 0;
  25443. this.timeScale = 1.0;
  25444. }
  25445. _bindAction(action, prototypeAction) {
  25446. const root = action._localRoot || this._root,
  25447. tracks = action._clip.tracks,
  25448. nTracks = tracks.length,
  25449. bindings = action._propertyBindings,
  25450. interpolants = action._interpolants,
  25451. rootUuid = root.uuid,
  25452. bindingsByRoot = this._bindingsByRootAndName;
  25453. let bindingsByName = bindingsByRoot[rootUuid];
  25454. if (bindingsByName === undefined) {
  25455. bindingsByName = {};
  25456. bindingsByRoot[rootUuid] = bindingsByName;
  25457. }
  25458. for (let i = 0; i !== nTracks; ++i) {
  25459. const track = tracks[i],
  25460. trackName = track.name;
  25461. let binding = bindingsByName[trackName];
  25462. if (binding !== undefined) {
  25463. bindings[i] = binding;
  25464. } else {
  25465. binding = bindings[i];
  25466. if (binding !== undefined) {
  25467. // existing binding, make sure the cache knows
  25468. if (binding._cacheIndex === null) {
  25469. ++binding.referenceCount;
  25470. this._addInactiveBinding(binding, rootUuid, trackName);
  25471. }
  25472. continue;
  25473. }
  25474. const path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
  25475. binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
  25476. ++binding.referenceCount;
  25477. this._addInactiveBinding(binding, rootUuid, trackName);
  25478. bindings[i] = binding;
  25479. }
  25480. interpolants[i].resultBuffer = binding.buffer;
  25481. }
  25482. }
  25483. _activateAction(action) {
  25484. if (!this._isActiveAction(action)) {
  25485. if (action._cacheIndex === null) {
  25486. // this action has been forgotten by the cache, but the user
  25487. // appears to be still using it -> rebind
  25488. const rootUuid = (action._localRoot || this._root).uuid,
  25489. clipUuid = action._clip.uuid,
  25490. actionsForClip = this._actionsByClip[clipUuid];
  25491. this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
  25492. this._addInactiveAction(action, clipUuid, rootUuid);
  25493. }
  25494. const bindings = action._propertyBindings; // increment reference counts / sort out state
  25495. for (let i = 0, n = bindings.length; i !== n; ++i) {
  25496. const binding = bindings[i];
  25497. if (binding.useCount++ === 0) {
  25498. this._lendBinding(binding);
  25499. binding.saveOriginalState();
  25500. }
  25501. }
  25502. this._lendAction(action);
  25503. }
  25504. }
  25505. _deactivateAction(action) {
  25506. if (this._isActiveAction(action)) {
  25507. const bindings = action._propertyBindings; // decrement reference counts / sort out state
  25508. for (let i = 0, n = bindings.length; i !== n; ++i) {
  25509. const binding = bindings[i];
  25510. if (--binding.useCount === 0) {
  25511. binding.restoreOriginalState();
  25512. this._takeBackBinding(binding);
  25513. }
  25514. }
  25515. this._takeBackAction(action);
  25516. }
  25517. } // Memory manager
  25518. _initMemoryManager() {
  25519. this._actions = []; // 'nActiveActions' followed by inactive ones
  25520. this._nActiveActions = 0;
  25521. this._actionsByClip = {}; // inside:
  25522. // {
  25523. // knownActions: Array< AnimationAction > - used as prototypes
  25524. // actionByRoot: AnimationAction - lookup
  25525. // }
  25526. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  25527. this._nActiveBindings = 0;
  25528. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  25529. this._controlInterpolants = []; // same game as above
  25530. this._nActiveControlInterpolants = 0;
  25531. const scope = this;
  25532. this.stats = {
  25533. actions: {
  25534. get total() {
  25535. return scope._actions.length;
  25536. },
  25537. get inUse() {
  25538. return scope._nActiveActions;
  25539. }
  25540. },
  25541. bindings: {
  25542. get total() {
  25543. return scope._bindings.length;
  25544. },
  25545. get inUse() {
  25546. return scope._nActiveBindings;
  25547. }
  25548. },
  25549. controlInterpolants: {
  25550. get total() {
  25551. return scope._controlInterpolants.length;
  25552. },
  25553. get inUse() {
  25554. return scope._nActiveControlInterpolants;
  25555. }
  25556. }
  25557. };
  25558. } // Memory management for AnimationAction objects
  25559. _isActiveAction(action) {
  25560. const index = action._cacheIndex;
  25561. return index !== null && index < this._nActiveActions;
  25562. }
  25563. _addInactiveAction(action, clipUuid, rootUuid) {
  25564. const actions = this._actions,
  25565. actionsByClip = this._actionsByClip;
  25566. let actionsForClip = actionsByClip[clipUuid];
  25567. if (actionsForClip === undefined) {
  25568. actionsForClip = {
  25569. knownActions: [action],
  25570. actionByRoot: {}
  25571. };
  25572. action._byClipCacheIndex = 0;
  25573. actionsByClip[clipUuid] = actionsForClip;
  25574. } else {
  25575. const knownActions = actionsForClip.knownActions;
  25576. action._byClipCacheIndex = knownActions.length;
  25577. knownActions.push(action);
  25578. }
  25579. action._cacheIndex = actions.length;
  25580. actions.push(action);
  25581. actionsForClip.actionByRoot[rootUuid] = action;
  25582. }
  25583. _removeInactiveAction(action) {
  25584. const actions = this._actions,
  25585. lastInactiveAction = actions[actions.length - 1],
  25586. cacheIndex = action._cacheIndex;
  25587. lastInactiveAction._cacheIndex = cacheIndex;
  25588. actions[cacheIndex] = lastInactiveAction;
  25589. actions.pop();
  25590. action._cacheIndex = null;
  25591. const clipUuid = action._clip.uuid,
  25592. actionsByClip = this._actionsByClip,
  25593. actionsForClip = actionsByClip[clipUuid],
  25594. knownActionsForClip = actionsForClip.knownActions,
  25595. lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
  25596. byClipCacheIndex = action._byClipCacheIndex;
  25597. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  25598. knownActionsForClip[byClipCacheIndex] = lastKnownAction;
  25599. knownActionsForClip.pop();
  25600. action._byClipCacheIndex = null;
  25601. const actionByRoot = actionsForClip.actionByRoot,
  25602. rootUuid = (action._localRoot || this._root).uuid;
  25603. delete actionByRoot[rootUuid];
  25604. if (knownActionsForClip.length === 0) {
  25605. delete actionsByClip[clipUuid];
  25606. }
  25607. this._removeInactiveBindingsForAction(action);
  25608. }
  25609. _removeInactiveBindingsForAction(action) {
  25610. const bindings = action._propertyBindings;
  25611. for (let i = 0, n = bindings.length; i !== n; ++i) {
  25612. const binding = bindings[i];
  25613. if (--binding.referenceCount === 0) {
  25614. this._removeInactiveBinding(binding);
  25615. }
  25616. }
  25617. }
  25618. _lendAction(action) {
  25619. // [ active actions | inactive actions ]
  25620. // [ active actions >| inactive actions ]
  25621. // s a
  25622. // <-swap->
  25623. // a s
  25624. const actions = this._actions,
  25625. prevIndex = action._cacheIndex,
  25626. lastActiveIndex = this._nActiveActions++,
  25627. firstInactiveAction = actions[lastActiveIndex];
  25628. action._cacheIndex = lastActiveIndex;
  25629. actions[lastActiveIndex] = action;
  25630. firstInactiveAction._cacheIndex = prevIndex;
  25631. actions[prevIndex] = firstInactiveAction;
  25632. }
  25633. _takeBackAction(action) {
  25634. // [ active actions | inactive actions ]
  25635. // [ active actions |< inactive actions ]
  25636. // a s
  25637. // <-swap->
  25638. // s a
  25639. const actions = this._actions,
  25640. prevIndex = action._cacheIndex,
  25641. firstInactiveIndex = --this._nActiveActions,
  25642. lastActiveAction = actions[firstInactiveIndex];
  25643. action._cacheIndex = firstInactiveIndex;
  25644. actions[firstInactiveIndex] = action;
  25645. lastActiveAction._cacheIndex = prevIndex;
  25646. actions[prevIndex] = lastActiveAction;
  25647. } // Memory management for PropertyMixer objects
  25648. _addInactiveBinding(binding, rootUuid, trackName) {
  25649. const bindingsByRoot = this._bindingsByRootAndName,
  25650. bindings = this._bindings;
  25651. let bindingByName = bindingsByRoot[rootUuid];
  25652. if (bindingByName === undefined) {
  25653. bindingByName = {};
  25654. bindingsByRoot[rootUuid] = bindingByName;
  25655. }
  25656. bindingByName[trackName] = binding;
  25657. binding._cacheIndex = bindings.length;
  25658. bindings.push(binding);
  25659. }
  25660. _removeInactiveBinding(binding) {
  25661. const bindings = this._bindings,
  25662. propBinding = binding.binding,
  25663. rootUuid = propBinding.rootNode.uuid,
  25664. trackName = propBinding.path,
  25665. bindingsByRoot = this._bindingsByRootAndName,
  25666. bindingByName = bindingsByRoot[rootUuid],
  25667. lastInactiveBinding = bindings[bindings.length - 1],
  25668. cacheIndex = binding._cacheIndex;
  25669. lastInactiveBinding._cacheIndex = cacheIndex;
  25670. bindings[cacheIndex] = lastInactiveBinding;
  25671. bindings.pop();
  25672. delete bindingByName[trackName];
  25673. if (Object.keys(bindingByName).length === 0) {
  25674. delete bindingsByRoot[rootUuid];
  25675. }
  25676. }
  25677. _lendBinding(binding) {
  25678. const bindings = this._bindings,
  25679. prevIndex = binding._cacheIndex,
  25680. lastActiveIndex = this._nActiveBindings++,
  25681. firstInactiveBinding = bindings[lastActiveIndex];
  25682. binding._cacheIndex = lastActiveIndex;
  25683. bindings[lastActiveIndex] = binding;
  25684. firstInactiveBinding._cacheIndex = prevIndex;
  25685. bindings[prevIndex] = firstInactiveBinding;
  25686. }
  25687. _takeBackBinding(binding) {
  25688. const bindings = this._bindings,
  25689. prevIndex = binding._cacheIndex,
  25690. firstInactiveIndex = --this._nActiveBindings,
  25691. lastActiveBinding = bindings[firstInactiveIndex];
  25692. binding._cacheIndex = firstInactiveIndex;
  25693. bindings[firstInactiveIndex] = binding;
  25694. lastActiveBinding._cacheIndex = prevIndex;
  25695. bindings[prevIndex] = lastActiveBinding;
  25696. } // Memory management of Interpolants for weight and time scale
  25697. _lendControlInterpolant() {
  25698. const interpolants = this._controlInterpolants,
  25699. lastActiveIndex = this._nActiveControlInterpolants++;
  25700. let interpolant = interpolants[lastActiveIndex];
  25701. if (interpolant === undefined) {
  25702. interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, this._controlInterpolantsResultBuffer);
  25703. interpolant.__cacheIndex = lastActiveIndex;
  25704. interpolants[lastActiveIndex] = interpolant;
  25705. }
  25706. return interpolant;
  25707. }
  25708. _takeBackControlInterpolant(interpolant) {
  25709. const interpolants = this._controlInterpolants,
  25710. prevIndex = interpolant.__cacheIndex,
  25711. firstInactiveIndex = --this._nActiveControlInterpolants,
  25712. lastActiveInterpolant = interpolants[firstInactiveIndex];
  25713. interpolant.__cacheIndex = firstInactiveIndex;
  25714. interpolants[firstInactiveIndex] = interpolant;
  25715. lastActiveInterpolant.__cacheIndex = prevIndex;
  25716. interpolants[prevIndex] = lastActiveInterpolant;
  25717. } // return an action for a clip optionally using a custom root target
  25718. // object (this method allocates a lot of dynamic memory in case a
  25719. // previously unknown clip/root combination is specified)
  25720. clipAction(clip, optionalRoot, blendMode) {
  25721. const root = optionalRoot || this._root,
  25722. rootUuid = root.uuid;
  25723. let clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip;
  25724. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  25725. const actionsForClip = this._actionsByClip[clipUuid];
  25726. let prototypeAction = null;
  25727. if (blendMode === undefined) {
  25728. if (clipObject !== null) {
  25729. blendMode = clipObject.blendMode;
  25730. } else {
  25731. blendMode = NormalAnimationBlendMode;
  25732. }
  25733. }
  25734. if (actionsForClip !== undefined) {
  25735. const existingAction = actionsForClip.actionByRoot[rootUuid];
  25736. if (existingAction !== undefined && existingAction.blendMode === blendMode) {
  25737. return existingAction;
  25738. } // we know the clip, so we don't have to parse all
  25739. // the bindings again but can just copy
  25740. prototypeAction = actionsForClip.knownActions[0]; // also, take the clip from the prototype action
  25741. if (clipObject === null) clipObject = prototypeAction._clip;
  25742. } // clip must be known when specified via string
  25743. if (clipObject === null) return null; // allocate all resources required to run it
  25744. const newAction = new AnimationAction(this, clipObject, optionalRoot, blendMode);
  25745. this._bindAction(newAction, prototypeAction); // and make the action known to the memory manager
  25746. this._addInactiveAction(newAction, clipUuid, rootUuid);
  25747. return newAction;
  25748. } // get an existing action
  25749. existingAction(clip, optionalRoot) {
  25750. const root = optionalRoot || this._root,
  25751. rootUuid = root.uuid,
  25752. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  25753. clipUuid = clipObject ? clipObject.uuid : clip,
  25754. actionsForClip = this._actionsByClip[clipUuid];
  25755. if (actionsForClip !== undefined) {
  25756. return actionsForClip.actionByRoot[rootUuid] || null;
  25757. }
  25758. return null;
  25759. } // deactivates all previously scheduled actions
  25760. stopAllAction() {
  25761. const actions = this._actions,
  25762. nActions = this._nActiveActions;
  25763. for (let i = nActions - 1; i >= 0; --i) {
  25764. actions[i].stop();
  25765. }
  25766. return this;
  25767. } // advance the time and update apply the animation
  25768. update(deltaTime) {
  25769. deltaTime *= this.timeScale;
  25770. const actions = this._actions,
  25771. nActions = this._nActiveActions,
  25772. time = this.time += deltaTime,
  25773. timeDirection = Math.sign(deltaTime),
  25774. accuIndex = this._accuIndex ^= 1; // run active actions
  25775. for (let i = 0; i !== nActions; ++i) {
  25776. const action = actions[i];
  25777. action._update(time, deltaTime, timeDirection, accuIndex);
  25778. } // update scene graph
  25779. const bindings = this._bindings,
  25780. nBindings = this._nActiveBindings;
  25781. for (let i = 0; i !== nBindings; ++i) {
  25782. bindings[i].apply(accuIndex);
  25783. }
  25784. return this;
  25785. } // Allows you to seek to a specific time in an animation.
  25786. setTime(timeInSeconds) {
  25787. this.time = 0; // Zero out time attribute for AnimationMixer object;
  25788. for (let i = 0; i < this._actions.length; i++) {
  25789. this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  25790. }
  25791. return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
  25792. } // return this mixer's root target object
  25793. getRoot() {
  25794. return this._root;
  25795. } // free all resources specific to a particular clip
  25796. uncacheClip(clip) {
  25797. const actions = this._actions,
  25798. clipUuid = clip.uuid,
  25799. actionsByClip = this._actionsByClip,
  25800. actionsForClip = actionsByClip[clipUuid];
  25801. if (actionsForClip !== undefined) {
  25802. // note: just calling _removeInactiveAction would mess up the
  25803. // iteration state and also require updating the state we can
  25804. // just throw away
  25805. const actionsToRemove = actionsForClip.knownActions;
  25806. for (let i = 0, n = actionsToRemove.length; i !== n; ++i) {
  25807. const action = actionsToRemove[i];
  25808. this._deactivateAction(action);
  25809. const cacheIndex = action._cacheIndex,
  25810. lastInactiveAction = actions[actions.length - 1];
  25811. action._cacheIndex = null;
  25812. action._byClipCacheIndex = null;
  25813. lastInactiveAction._cacheIndex = cacheIndex;
  25814. actions[cacheIndex] = lastInactiveAction;
  25815. actions.pop();
  25816. this._removeInactiveBindingsForAction(action);
  25817. }
  25818. delete actionsByClip[clipUuid];
  25819. }
  25820. } // free all resources specific to a particular root target object
  25821. uncacheRoot(root) {
  25822. const rootUuid = root.uuid,
  25823. actionsByClip = this._actionsByClip;
  25824. for (const clipUuid in actionsByClip) {
  25825. const actionByRoot = actionsByClip[clipUuid].actionByRoot,
  25826. action = actionByRoot[rootUuid];
  25827. if (action !== undefined) {
  25828. this._deactivateAction(action);
  25829. this._removeInactiveAction(action);
  25830. }
  25831. }
  25832. const bindingsByRoot = this._bindingsByRootAndName,
  25833. bindingByName = bindingsByRoot[rootUuid];
  25834. if (bindingByName !== undefined) {
  25835. for (const trackName in bindingByName) {
  25836. const binding = bindingByName[trackName];
  25837. binding.restoreOriginalState();
  25838. this._removeInactiveBinding(binding);
  25839. }
  25840. }
  25841. } // remove a targeted clip from the cache
  25842. uncacheAction(clip, optionalRoot) {
  25843. const action = this.existingAction(clip, optionalRoot);
  25844. if (action !== null) {
  25845. this._deactivateAction(action);
  25846. this._removeInactiveAction(action);
  25847. }
  25848. }
  25849. }
  25850. AnimationMixer.prototype._controlInterpolantsResultBuffer = new Float32Array(1);
  25851. class Uniform {
  25852. constructor(value) {
  25853. if (typeof value === 'string') {
  25854. console.warn('THREE.Uniform: Type parameter is no longer needed.');
  25855. value = arguments[1];
  25856. }
  25857. this.value = value;
  25858. }
  25859. clone() {
  25860. return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
  25861. }
  25862. }
  25863. class InstancedInterleavedBuffer extends InterleavedBuffer {
  25864. constructor(array, stride, meshPerAttribute = 1) {
  25865. super(array, stride);
  25866. this.meshPerAttribute = meshPerAttribute || 1;
  25867. }
  25868. copy(source) {
  25869. super.copy(source);
  25870. this.meshPerAttribute = source.meshPerAttribute;
  25871. return this;
  25872. }
  25873. clone(data) {
  25874. const ib = super.clone(data);
  25875. ib.meshPerAttribute = this.meshPerAttribute;
  25876. return ib;
  25877. }
  25878. toJSON(data) {
  25879. const json = super.toJSON(data);
  25880. json.isInstancedInterleavedBuffer = true;
  25881. json.meshPerAttribute = this.meshPerAttribute;
  25882. return json;
  25883. }
  25884. }
  25885. InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true;
  25886. class GLBufferAttribute {
  25887. constructor(buffer, type, itemSize, elementSize, count) {
  25888. this.buffer = buffer;
  25889. this.type = type;
  25890. this.itemSize = itemSize;
  25891. this.elementSize = elementSize;
  25892. this.count = count;
  25893. this.version = 0;
  25894. }
  25895. set needsUpdate(value) {
  25896. if (value === true) this.version++;
  25897. }
  25898. setBuffer(buffer) {
  25899. this.buffer = buffer;
  25900. return this;
  25901. }
  25902. setType(type, elementSize) {
  25903. this.type = type;
  25904. this.elementSize = elementSize;
  25905. return this;
  25906. }
  25907. setItemSize(itemSize) {
  25908. this.itemSize = itemSize;
  25909. return this;
  25910. }
  25911. setCount(count) {
  25912. this.count = count;
  25913. return this;
  25914. }
  25915. }
  25916. GLBufferAttribute.prototype.isGLBufferAttribute = true;
  25917. class Raycaster {
  25918. constructor(origin, direction, near = 0, far = Infinity) {
  25919. this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)
  25920. this.near = near;
  25921. this.far = far;
  25922. this.camera = null;
  25923. this.layers = new Layers();
  25924. this.params = {
  25925. Mesh: {},
  25926. Line: {
  25927. threshold: 1
  25928. },
  25929. LOD: {},
  25930. Points: {
  25931. threshold: 1
  25932. },
  25933. Sprite: {}
  25934. };
  25935. }
  25936. set(origin, direction) {
  25937. // direction is assumed to be normalized (for accurate distance calculations)
  25938. this.ray.set(origin, direction);
  25939. }
  25940. setFromCamera(coords, camera) {
  25941. if (camera && camera.isPerspectiveCamera) {
  25942. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  25943. this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
  25944. this.camera = camera;
  25945. } else if (camera && camera.isOrthographicCamera) {
  25946. this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
  25947. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  25948. this.camera = camera;
  25949. } else {
  25950. console.error('THREE.Raycaster: Unsupported camera type: ' + camera.type);
  25951. }
  25952. }
  25953. intersectObject(object, recursive = false, intersects = []) {
  25954. intersectObject(object, this, intersects, recursive);
  25955. intersects.sort(ascSort);
  25956. return intersects;
  25957. }
  25958. intersectObjects(objects, recursive = false, intersects = []) {
  25959. for (let i = 0, l = objects.length; i < l; i++) {
  25960. intersectObject(objects[i], this, intersects, recursive);
  25961. }
  25962. intersects.sort(ascSort);
  25963. return intersects;
  25964. }
  25965. }
  25966. function ascSort(a, b) {
  25967. return a.distance - b.distance;
  25968. }
  25969. function intersectObject(object, raycaster, intersects, recursive) {
  25970. if (object.layers.test(raycaster.layers)) {
  25971. object.raycast(raycaster, intersects);
  25972. }
  25973. if (recursive === true) {
  25974. const children = object.children;
  25975. for (let i = 0, l = children.length; i < l; i++) {
  25976. intersectObject(children[i], raycaster, intersects, true);
  25977. }
  25978. }
  25979. }
  25980. /**
  25981. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  25982. *
  25983. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  25984. * The azimuthal angle (theta) is measured from the positive z-axis.
  25985. */
  25986. class Spherical {
  25987. constructor(radius = 1, phi = 0, theta = 0) {
  25988. this.radius = radius;
  25989. this.phi = phi; // polar angle
  25990. this.theta = theta; // azimuthal angle
  25991. return this;
  25992. }
  25993. set(radius, phi, theta) {
  25994. this.radius = radius;
  25995. this.phi = phi;
  25996. this.theta = theta;
  25997. return this;
  25998. }
  25999. copy(other) {
  26000. this.radius = other.radius;
  26001. this.phi = other.phi;
  26002. this.theta = other.theta;
  26003. return this;
  26004. } // restrict phi to be betwee EPS and PI-EPS
  26005. makeSafe() {
  26006. const EPS = 0.000001;
  26007. this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
  26008. return this;
  26009. }
  26010. setFromVector3(v) {
  26011. return this.setFromCartesianCoords(v.x, v.y, v.z);
  26012. }
  26013. setFromCartesianCoords(x, y, z) {
  26014. this.radius = Math.sqrt(x * x + y * y + z * z);
  26015. if (this.radius === 0) {
  26016. this.theta = 0;
  26017. this.phi = 0;
  26018. } else {
  26019. this.theta = Math.atan2(x, z);
  26020. this.phi = Math.acos(clamp(y / this.radius, -1, 1));
  26021. }
  26022. return this;
  26023. }
  26024. clone() {
  26025. return new this.constructor().copy(this);
  26026. }
  26027. }
  26028. /**
  26029. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  26030. */
  26031. class Cylindrical {
  26032. constructor(radius = 1, theta = 0, y = 0) {
  26033. this.radius = radius; // distance from the origin to a point in the x-z plane
  26034. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  26035. this.y = y; // height above the x-z plane
  26036. return this;
  26037. }
  26038. set(radius, theta, y) {
  26039. this.radius = radius;
  26040. this.theta = theta;
  26041. this.y = y;
  26042. return this;
  26043. }
  26044. copy(other) {
  26045. this.radius = other.radius;
  26046. this.theta = other.theta;
  26047. this.y = other.y;
  26048. return this;
  26049. }
  26050. setFromVector3(v) {
  26051. return this.setFromCartesianCoords(v.x, v.y, v.z);
  26052. }
  26053. setFromCartesianCoords(x, y, z) {
  26054. this.radius = Math.sqrt(x * x + z * z);
  26055. this.theta = Math.atan2(x, z);
  26056. this.y = y;
  26057. return this;
  26058. }
  26059. clone() {
  26060. return new this.constructor().copy(this);
  26061. }
  26062. }
  26063. const _vector$4 = /*@__PURE__*/new Vector2();
  26064. class Box2 {
  26065. constructor(min = new Vector2(+Infinity, +Infinity), max = new Vector2(-Infinity, -Infinity)) {
  26066. this.min = min;
  26067. this.max = max;
  26068. }
  26069. set(min, max) {
  26070. this.min.copy(min);
  26071. this.max.copy(max);
  26072. return this;
  26073. }
  26074. setFromPoints(points) {
  26075. this.makeEmpty();
  26076. for (let i = 0, il = points.length; i < il; i++) {
  26077. this.expandByPoint(points[i]);
  26078. }
  26079. return this;
  26080. }
  26081. setFromCenterAndSize(center, size) {
  26082. const halfSize = _vector$4.copy(size).multiplyScalar(0.5);
  26083. this.min.copy(center).sub(halfSize);
  26084. this.max.copy(center).add(halfSize);
  26085. return this;
  26086. }
  26087. clone() {
  26088. return new this.constructor().copy(this);
  26089. }
  26090. copy(box) {
  26091. this.min.copy(box.min);
  26092. this.max.copy(box.max);
  26093. return this;
  26094. }
  26095. makeEmpty() {
  26096. this.min.x = this.min.y = +Infinity;
  26097. this.max.x = this.max.y = -Infinity;
  26098. return this;
  26099. }
  26100. isEmpty() {
  26101. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  26102. return this.max.x < this.min.x || this.max.y < this.min.y;
  26103. }
  26104. getCenter(target) {
  26105. if (target === undefined) {
  26106. console.warn('THREE.Box2: .getCenter() target is now required');
  26107. target = new Vector2();
  26108. }
  26109. return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  26110. }
  26111. getSize(target) {
  26112. if (target === undefined) {
  26113. console.warn('THREE.Box2: .getSize() target is now required');
  26114. target = new Vector2();
  26115. }
  26116. return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  26117. }
  26118. expandByPoint(point) {
  26119. this.min.min(point);
  26120. this.max.max(point);
  26121. return this;
  26122. }
  26123. expandByVector(vector) {
  26124. this.min.sub(vector);
  26125. this.max.add(vector);
  26126. return this;
  26127. }
  26128. expandByScalar(scalar) {
  26129. this.min.addScalar(-scalar);
  26130. this.max.addScalar(scalar);
  26131. return this;
  26132. }
  26133. containsPoint(point) {
  26134. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
  26135. }
  26136. containsBox(box) {
  26137. 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;
  26138. }
  26139. getParameter(point, target) {
  26140. // This can potentially have a divide by zero if the box
  26141. // has a size dimension of 0.
  26142. if (target === undefined) {
  26143. console.warn('THREE.Box2: .getParameter() target is now required');
  26144. target = new Vector2();
  26145. }
  26146. 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));
  26147. }
  26148. intersectsBox(box) {
  26149. // using 4 splitting planes to rule out intersections
  26150. 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;
  26151. }
  26152. clampPoint(point, target) {
  26153. if (target === undefined) {
  26154. console.warn('THREE.Box2: .clampPoint() target is now required');
  26155. target = new Vector2();
  26156. }
  26157. return target.copy(point).clamp(this.min, this.max);
  26158. }
  26159. distanceToPoint(point) {
  26160. const clampedPoint = _vector$4.copy(point).clamp(this.min, this.max);
  26161. return clampedPoint.sub(point).length();
  26162. }
  26163. intersect(box) {
  26164. this.min.max(box.min);
  26165. this.max.min(box.max);
  26166. return this;
  26167. }
  26168. union(box) {
  26169. this.min.min(box.min);
  26170. this.max.max(box.max);
  26171. return this;
  26172. }
  26173. translate(offset) {
  26174. this.min.add(offset);
  26175. this.max.add(offset);
  26176. return this;
  26177. }
  26178. equals(box) {
  26179. return box.min.equals(this.min) && box.max.equals(this.max);
  26180. }
  26181. }
  26182. Box2.prototype.isBox2 = true;
  26183. const _startP = /*@__PURE__*/new Vector3();
  26184. const _startEnd = /*@__PURE__*/new Vector3();
  26185. class Line3 {
  26186. constructor(start = new Vector3(), end = new Vector3()) {
  26187. this.start = start;
  26188. this.end = end;
  26189. }
  26190. set(start, end) {
  26191. this.start.copy(start);
  26192. this.end.copy(end);
  26193. return this;
  26194. }
  26195. copy(line) {
  26196. this.start.copy(line.start);
  26197. this.end.copy(line.end);
  26198. return this;
  26199. }
  26200. getCenter(target) {
  26201. if (target === undefined) {
  26202. console.warn('THREE.Line3: .getCenter() target is now required');
  26203. target = new Vector3();
  26204. }
  26205. return target.addVectors(this.start, this.end).multiplyScalar(0.5);
  26206. }
  26207. delta(target) {
  26208. if (target === undefined) {
  26209. console.warn('THREE.Line3: .delta() target is now required');
  26210. target = new Vector3();
  26211. }
  26212. return target.subVectors(this.end, this.start);
  26213. }
  26214. distanceSq() {
  26215. return this.start.distanceToSquared(this.end);
  26216. }
  26217. distance() {
  26218. return this.start.distanceTo(this.end);
  26219. }
  26220. at(t, target) {
  26221. if (target === undefined) {
  26222. console.warn('THREE.Line3: .at() target is now required');
  26223. target = new Vector3();
  26224. }
  26225. return this.delta(target).multiplyScalar(t).add(this.start);
  26226. }
  26227. closestPointToPointParameter(point, clampToLine) {
  26228. _startP.subVectors(point, this.start);
  26229. _startEnd.subVectors(this.end, this.start);
  26230. const startEnd2 = _startEnd.dot(_startEnd);
  26231. const startEnd_startP = _startEnd.dot(_startP);
  26232. let t = startEnd_startP / startEnd2;
  26233. if (clampToLine) {
  26234. t = clamp(t, 0, 1);
  26235. }
  26236. return t;
  26237. }
  26238. closestPointToPoint(point, clampToLine, target) {
  26239. const t = this.closestPointToPointParameter(point, clampToLine);
  26240. if (target === undefined) {
  26241. console.warn('THREE.Line3: .closestPointToPoint() target is now required');
  26242. target = new Vector3();
  26243. }
  26244. return this.delta(target).multiplyScalar(t).add(this.start);
  26245. }
  26246. applyMatrix4(matrix) {
  26247. this.start.applyMatrix4(matrix);
  26248. this.end.applyMatrix4(matrix);
  26249. return this;
  26250. }
  26251. equals(line) {
  26252. return line.start.equals(this.start) && line.end.equals(this.end);
  26253. }
  26254. clone() {
  26255. return new this.constructor().copy(this);
  26256. }
  26257. }
  26258. class ImmediateRenderObject extends Object3D {
  26259. constructor(material) {
  26260. super();
  26261. this.material = material;
  26262. this.render = function ()
  26263. /* renderCallback */
  26264. {};
  26265. this.hasPositions = false;
  26266. this.hasNormals = false;
  26267. this.hasColors = false;
  26268. this.hasUvs = false;
  26269. this.positionArray = null;
  26270. this.normalArray = null;
  26271. this.colorArray = null;
  26272. this.uvArray = null;
  26273. this.count = 0;
  26274. }
  26275. }
  26276. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  26277. const _vector$3 = /*@__PURE__*/new Vector3();
  26278. class SpotLightHelper extends Object3D {
  26279. constructor(light, color) {
  26280. super();
  26281. this.light = light;
  26282. this.light.updateMatrixWorld();
  26283. this.matrix = light.matrixWorld;
  26284. this.matrixAutoUpdate = false;
  26285. this.color = color;
  26286. const geometry = new BufferGeometry();
  26287. 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];
  26288. for (let i = 0, j = 1, l = 32; i < l; i++, j++) {
  26289. const p1 = i / l * Math.PI * 2;
  26290. const p2 = j / l * Math.PI * 2;
  26291. positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
  26292. }
  26293. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  26294. const material = new LineBasicMaterial({
  26295. fog: false,
  26296. toneMapped: false
  26297. });
  26298. this.cone = new LineSegments(geometry, material);
  26299. this.add(this.cone);
  26300. this.update();
  26301. }
  26302. dispose() {
  26303. this.cone.geometry.dispose();
  26304. this.cone.material.dispose();
  26305. }
  26306. update() {
  26307. this.light.updateMatrixWorld();
  26308. const coneLength = this.light.distance ? this.light.distance : 1000;
  26309. const coneWidth = coneLength * Math.tan(this.light.angle);
  26310. this.cone.scale.set(coneWidth, coneWidth, coneLength);
  26311. _vector$3.setFromMatrixPosition(this.light.target.matrixWorld);
  26312. this.cone.lookAt(_vector$3);
  26313. if (this.color !== undefined) {
  26314. this.cone.material.color.set(this.color);
  26315. } else {
  26316. this.cone.material.color.copy(this.light.color);
  26317. }
  26318. }
  26319. }
  26320. const _vector$2 = /*@__PURE__*/new Vector3();
  26321. const _boneMatrix = /*@__PURE__*/new Matrix4();
  26322. const _matrixWorldInv = /*@__PURE__*/new Matrix4();
  26323. class SkeletonHelper extends LineSegments {
  26324. constructor(object) {
  26325. const bones = getBoneList(object);
  26326. const geometry = new BufferGeometry();
  26327. const vertices = [];
  26328. const colors = [];
  26329. const color1 = new Color(0, 0, 1);
  26330. const color2 = new Color(0, 1, 0);
  26331. for (let i = 0; i < bones.length; i++) {
  26332. const bone = bones[i];
  26333. if (bone.parent && bone.parent.isBone) {
  26334. vertices.push(0, 0, 0);
  26335. vertices.push(0, 0, 0);
  26336. colors.push(color1.r, color1.g, color1.b);
  26337. colors.push(color2.r, color2.g, color2.b);
  26338. }
  26339. }
  26340. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  26341. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  26342. const material = new LineBasicMaterial({
  26343. vertexColors: true,
  26344. depthTest: false,
  26345. depthWrite: false,
  26346. toneMapped: false,
  26347. transparent: true
  26348. });
  26349. super(geometry, material);
  26350. this.type = 'SkeletonHelper';
  26351. this.isSkeletonHelper = true;
  26352. this.root = object;
  26353. this.bones = bones;
  26354. this.matrix = object.matrixWorld;
  26355. this.matrixAutoUpdate = false;
  26356. }
  26357. updateMatrixWorld(force) {
  26358. const bones = this.bones;
  26359. const geometry = this.geometry;
  26360. const position = geometry.getAttribute('position');
  26361. _matrixWorldInv.copy(this.root.matrixWorld).invert();
  26362. for (let i = 0, j = 0; i < bones.length; i++) {
  26363. const bone = bones[i];
  26364. if (bone.parent && bone.parent.isBone) {
  26365. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
  26366. _vector$2.setFromMatrixPosition(_boneMatrix);
  26367. position.setXYZ(j, _vector$2.x, _vector$2.y, _vector$2.z);
  26368. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
  26369. _vector$2.setFromMatrixPosition(_boneMatrix);
  26370. position.setXYZ(j + 1, _vector$2.x, _vector$2.y, _vector$2.z);
  26371. j += 2;
  26372. }
  26373. }
  26374. geometry.getAttribute('position').needsUpdate = true;
  26375. super.updateMatrixWorld(force);
  26376. }
  26377. }
  26378. function getBoneList(object) {
  26379. const boneList = [];
  26380. if (object && object.isBone) {
  26381. boneList.push(object);
  26382. }
  26383. for (let i = 0; i < object.children.length; i++) {
  26384. boneList.push.apply(boneList, getBoneList(object.children[i]));
  26385. }
  26386. return boneList;
  26387. }
  26388. class PointLightHelper extends Mesh {
  26389. constructor(light, sphereSize, color) {
  26390. const geometry = new SphereGeometry(sphereSize, 4, 2);
  26391. const material = new MeshBasicMaterial({
  26392. wireframe: true,
  26393. fog: false,
  26394. toneMapped: false
  26395. });
  26396. super(geometry, material);
  26397. this.light = light;
  26398. this.light.updateMatrixWorld();
  26399. this.color = color;
  26400. this.type = 'PointLightHelper';
  26401. this.matrix = this.light.matrixWorld;
  26402. this.matrixAutoUpdate = false;
  26403. this.update();
  26404. /*
  26405. // TODO: delete this comment?
  26406. const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  26407. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  26408. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  26409. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  26410. const d = light.distance;
  26411. if ( d === 0.0 ) {
  26412. this.lightDistance.visible = false;
  26413. } else {
  26414. this.lightDistance.scale.set( d, d, d );
  26415. }
  26416. this.add( this.lightDistance );
  26417. */
  26418. }
  26419. dispose() {
  26420. this.geometry.dispose();
  26421. this.material.dispose();
  26422. }
  26423. update() {
  26424. if (this.color !== undefined) {
  26425. this.material.color.set(this.color);
  26426. } else {
  26427. this.material.color.copy(this.light.color);
  26428. }
  26429. /*
  26430. const d = this.light.distance;
  26431. if ( d === 0.0 ) {
  26432. this.lightDistance.visible = false;
  26433. } else {
  26434. this.lightDistance.visible = true;
  26435. this.lightDistance.scale.set( d, d, d );
  26436. }
  26437. */
  26438. }
  26439. }
  26440. const _vector$1 = /*@__PURE__*/new Vector3();
  26441. const _color1 = /*@__PURE__*/new Color();
  26442. const _color2 = /*@__PURE__*/new Color();
  26443. class HemisphereLightHelper extends Object3D {
  26444. constructor(light, size, color) {
  26445. super();
  26446. this.light = light;
  26447. this.light.updateMatrixWorld();
  26448. this.matrix = light.matrixWorld;
  26449. this.matrixAutoUpdate = false;
  26450. this.color = color;
  26451. const geometry = new OctahedronGeometry(size);
  26452. geometry.rotateY(Math.PI * 0.5);
  26453. this.material = new MeshBasicMaterial({
  26454. wireframe: true,
  26455. fog: false,
  26456. toneMapped: false
  26457. });
  26458. if (this.color === undefined) this.material.vertexColors = true;
  26459. const position = geometry.getAttribute('position');
  26460. const colors = new Float32Array(position.count * 3);
  26461. geometry.setAttribute('color', new BufferAttribute(colors, 3));
  26462. this.add(new Mesh(geometry, this.material));
  26463. this.update();
  26464. }
  26465. dispose() {
  26466. this.children[0].geometry.dispose();
  26467. this.children[0].material.dispose();
  26468. }
  26469. update() {
  26470. const mesh = this.children[0];
  26471. if (this.color !== undefined) {
  26472. this.material.color.set(this.color);
  26473. } else {
  26474. const colors = mesh.geometry.getAttribute('color');
  26475. _color1.copy(this.light.color);
  26476. _color2.copy(this.light.groundColor);
  26477. for (let i = 0, l = colors.count; i < l; i++) {
  26478. const color = i < l / 2 ? _color1 : _color2;
  26479. colors.setXYZ(i, color.r, color.g, color.b);
  26480. }
  26481. colors.needsUpdate = true;
  26482. }
  26483. mesh.lookAt(_vector$1.setFromMatrixPosition(this.light.matrixWorld).negate());
  26484. }
  26485. }
  26486. class GridHelper extends LineSegments {
  26487. constructor(size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888) {
  26488. color1 = new Color(color1);
  26489. color2 = new Color(color2);
  26490. const center = divisions / 2;
  26491. const step = size / divisions;
  26492. const halfSize = size / 2;
  26493. const vertices = [],
  26494. colors = [];
  26495. for (let i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
  26496. vertices.push(-halfSize, 0, k, halfSize, 0, k);
  26497. vertices.push(k, 0, -halfSize, k, 0, halfSize);
  26498. const color = i === center ? color1 : color2;
  26499. color.toArray(colors, j);
  26500. j += 3;
  26501. color.toArray(colors, j);
  26502. j += 3;
  26503. color.toArray(colors, j);
  26504. j += 3;
  26505. color.toArray(colors, j);
  26506. j += 3;
  26507. }
  26508. const geometry = new BufferGeometry();
  26509. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  26510. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  26511. const material = new LineBasicMaterial({
  26512. vertexColors: true,
  26513. toneMapped: false
  26514. });
  26515. super(geometry, material);
  26516. this.type = 'GridHelper';
  26517. }
  26518. }
  26519. class PolarGridHelper extends LineSegments {
  26520. constructor(radius = 10, radials = 16, circles = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888) {
  26521. color1 = new Color(color1);
  26522. color2 = new Color(color2);
  26523. const vertices = [];
  26524. const colors = []; // create the radials
  26525. for (let i = 0; i <= radials; i++) {
  26526. const v = i / radials * (Math.PI * 2);
  26527. const x = Math.sin(v) * radius;
  26528. const z = Math.cos(v) * radius;
  26529. vertices.push(0, 0, 0);
  26530. vertices.push(x, 0, z);
  26531. const color = i & 1 ? color1 : color2;
  26532. colors.push(color.r, color.g, color.b);
  26533. colors.push(color.r, color.g, color.b);
  26534. } // create the circles
  26535. for (let i = 0; i <= circles; i++) {
  26536. const color = i & 1 ? color1 : color2;
  26537. const r = radius - radius / circles * i;
  26538. for (let j = 0; j < divisions; j++) {
  26539. // first vertex
  26540. let v = j / divisions * (Math.PI * 2);
  26541. let x = Math.sin(v) * r;
  26542. let z = Math.cos(v) * r;
  26543. vertices.push(x, 0, z);
  26544. colors.push(color.r, color.g, color.b); // second vertex
  26545. v = (j + 1) / divisions * (Math.PI * 2);
  26546. x = Math.sin(v) * r;
  26547. z = Math.cos(v) * r;
  26548. vertices.push(x, 0, z);
  26549. colors.push(color.r, color.g, color.b);
  26550. }
  26551. }
  26552. const geometry = new BufferGeometry();
  26553. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  26554. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  26555. const material = new LineBasicMaterial({
  26556. vertexColors: true,
  26557. toneMapped: false
  26558. });
  26559. super(geometry, material);
  26560. this.type = 'PolarGridHelper';
  26561. }
  26562. }
  26563. const _v1 = /*@__PURE__*/new Vector3();
  26564. const _v2 = /*@__PURE__*/new Vector3();
  26565. const _v3 = /*@__PURE__*/new Vector3();
  26566. class DirectionalLightHelper extends Object3D {
  26567. constructor(light, size, color) {
  26568. super();
  26569. this.light = light;
  26570. this.light.updateMatrixWorld();
  26571. this.matrix = light.matrixWorld;
  26572. this.matrixAutoUpdate = false;
  26573. this.color = color;
  26574. if (size === undefined) size = 1;
  26575. let geometry = new BufferGeometry();
  26576. geometry.setAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
  26577. const material = new LineBasicMaterial({
  26578. fog: false,
  26579. toneMapped: false
  26580. });
  26581. this.lightPlane = new Line(geometry, material);
  26582. this.add(this.lightPlane);
  26583. geometry = new BufferGeometry();
  26584. geometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
  26585. this.targetLine = new Line(geometry, material);
  26586. this.add(this.targetLine);
  26587. this.update();
  26588. }
  26589. dispose() {
  26590. this.lightPlane.geometry.dispose();
  26591. this.lightPlane.material.dispose();
  26592. this.targetLine.geometry.dispose();
  26593. this.targetLine.material.dispose();
  26594. }
  26595. update() {
  26596. _v1.setFromMatrixPosition(this.light.matrixWorld);
  26597. _v2.setFromMatrixPosition(this.light.target.matrixWorld);
  26598. _v3.subVectors(_v2, _v1);
  26599. this.lightPlane.lookAt(_v2);
  26600. if (this.color !== undefined) {
  26601. this.lightPlane.material.color.set(this.color);
  26602. this.targetLine.material.color.set(this.color);
  26603. } else {
  26604. this.lightPlane.material.color.copy(this.light.color);
  26605. this.targetLine.material.color.copy(this.light.color);
  26606. }
  26607. this.targetLine.lookAt(_v2);
  26608. this.targetLine.scale.z = _v3.length();
  26609. }
  26610. }
  26611. const _vector = /*@__PURE__*/new Vector3();
  26612. const _camera = /*@__PURE__*/new Camera();
  26613. /**
  26614. * - shows frustum, line of sight and up of the camera
  26615. * - suitable for fast updates
  26616. * - based on frustum visualization in lightgl.js shadowmap example
  26617. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  26618. */
  26619. class CameraHelper extends LineSegments {
  26620. constructor(camera) {
  26621. const geometry = new BufferGeometry();
  26622. const material = new LineBasicMaterial({
  26623. color: 0xffffff,
  26624. vertexColors: true,
  26625. toneMapped: false
  26626. });
  26627. const vertices = [];
  26628. const colors = [];
  26629. const pointMap = {}; // colors
  26630. const colorFrustum = new Color(0xffaa00);
  26631. const colorCone = new Color(0xff0000);
  26632. const colorUp = new Color(0x00aaff);
  26633. const colorTarget = new Color(0xffffff);
  26634. const colorCross = new Color(0x333333); // near
  26635. addLine('n1', 'n2', colorFrustum);
  26636. addLine('n2', 'n4', colorFrustum);
  26637. addLine('n4', 'n3', colorFrustum);
  26638. addLine('n3', 'n1', colorFrustum); // far
  26639. addLine('f1', 'f2', colorFrustum);
  26640. addLine('f2', 'f4', colorFrustum);
  26641. addLine('f4', 'f3', colorFrustum);
  26642. addLine('f3', 'f1', colorFrustum); // sides
  26643. addLine('n1', 'f1', colorFrustum);
  26644. addLine('n2', 'f2', colorFrustum);
  26645. addLine('n3', 'f3', colorFrustum);
  26646. addLine('n4', 'f4', colorFrustum); // cone
  26647. addLine('p', 'n1', colorCone);
  26648. addLine('p', 'n2', colorCone);
  26649. addLine('p', 'n3', colorCone);
  26650. addLine('p', 'n4', colorCone); // up
  26651. addLine('u1', 'u2', colorUp);
  26652. addLine('u2', 'u3', colorUp);
  26653. addLine('u3', 'u1', colorUp); // target
  26654. addLine('c', 't', colorTarget);
  26655. addLine('p', 'c', colorCross); // cross
  26656. addLine('cn1', 'cn2', colorCross);
  26657. addLine('cn3', 'cn4', colorCross);
  26658. addLine('cf1', 'cf2', colorCross);
  26659. addLine('cf3', 'cf4', colorCross);
  26660. function addLine(a, b, color) {
  26661. addPoint(a, color);
  26662. addPoint(b, color);
  26663. }
  26664. function addPoint(id, color) {
  26665. vertices.push(0, 0, 0);
  26666. colors.push(color.r, color.g, color.b);
  26667. if (pointMap[id] === undefined) {
  26668. pointMap[id] = [];
  26669. }
  26670. pointMap[id].push(vertices.length / 3 - 1);
  26671. }
  26672. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  26673. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  26674. super(geometry, material);
  26675. this.type = 'CameraHelper';
  26676. this.camera = camera;
  26677. if (this.camera.updateProjectionMatrix) this.camera.updateProjectionMatrix();
  26678. this.matrix = camera.matrixWorld;
  26679. this.matrixAutoUpdate = false;
  26680. this.pointMap = pointMap;
  26681. this.update();
  26682. }
  26683. update() {
  26684. const geometry = this.geometry;
  26685. const pointMap = this.pointMap;
  26686. const w = 1,
  26687. h = 1; // we need just camera projection matrix inverse
  26688. // world matrix must be identity
  26689. _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / target
  26690. setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
  26691. setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // near
  26692. setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
  26693. setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
  26694. setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
  26695. setPoint('n4', pointMap, geometry, _camera, w, h, -1); // far
  26696. setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
  26697. setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
  26698. setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
  26699. setPoint('f4', pointMap, geometry, _camera, w, h, 1); // up
  26700. setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
  26701. setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
  26702. setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // cross
  26703. setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
  26704. setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
  26705. setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
  26706. setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
  26707. setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
  26708. setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
  26709. setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
  26710. setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
  26711. geometry.getAttribute('position').needsUpdate = true;
  26712. }
  26713. dispose() {
  26714. this.geometry.dispose();
  26715. this.material.dispose();
  26716. }
  26717. }
  26718. function setPoint(point, pointMap, geometry, camera, x, y, z) {
  26719. _vector.set(x, y, z).unproject(camera);
  26720. const points = pointMap[point];
  26721. if (points !== undefined) {
  26722. const position = geometry.getAttribute('position');
  26723. for (let i = 0, l = points.length; i < l; i++) {
  26724. position.setXYZ(points[i], _vector.x, _vector.y, _vector.z);
  26725. }
  26726. }
  26727. }
  26728. const _box = /*@__PURE__*/new Box3();
  26729. class BoxHelper extends LineSegments {
  26730. constructor(object, color = 0xffff00) {
  26731. 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]);
  26732. const positions = new Float32Array(8 * 3);
  26733. const geometry = new BufferGeometry();
  26734. geometry.setIndex(new BufferAttribute(indices, 1));
  26735. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  26736. super(geometry, new LineBasicMaterial({
  26737. color: color,
  26738. toneMapped: false
  26739. }));
  26740. this.object = object;
  26741. this.type = 'BoxHelper';
  26742. this.matrixAutoUpdate = false;
  26743. this.update();
  26744. }
  26745. update(object) {
  26746. if (object !== undefined) {
  26747. console.warn('THREE.BoxHelper: .update() has no longer arguments.');
  26748. }
  26749. if (this.object !== undefined) {
  26750. _box.setFromObject(this.object);
  26751. }
  26752. if (_box.isEmpty()) return;
  26753. const min = _box.min;
  26754. const max = _box.max;
  26755. /*
  26756. 5____4
  26757. 1/___0/|
  26758. | 6__|_7
  26759. 2/___3/
  26760. 0: max.x, max.y, max.z
  26761. 1: min.x, max.y, max.z
  26762. 2: min.x, min.y, max.z
  26763. 3: max.x, min.y, max.z
  26764. 4: max.x, max.y, min.z
  26765. 5: min.x, max.y, min.z
  26766. 6: min.x, min.y, min.z
  26767. 7: max.x, min.y, min.z
  26768. */
  26769. const position = this.geometry.attributes.position;
  26770. const array = position.array;
  26771. array[0] = max.x;
  26772. array[1] = max.y;
  26773. array[2] = max.z;
  26774. array[3] = min.x;
  26775. array[4] = max.y;
  26776. array[5] = max.z;
  26777. array[6] = min.x;
  26778. array[7] = min.y;
  26779. array[8] = max.z;
  26780. array[9] = max.x;
  26781. array[10] = min.y;
  26782. array[11] = max.z;
  26783. array[12] = max.x;
  26784. array[13] = max.y;
  26785. array[14] = min.z;
  26786. array[15] = min.x;
  26787. array[16] = max.y;
  26788. array[17] = min.z;
  26789. array[18] = min.x;
  26790. array[19] = min.y;
  26791. array[20] = min.z;
  26792. array[21] = max.x;
  26793. array[22] = min.y;
  26794. array[23] = min.z;
  26795. position.needsUpdate = true;
  26796. this.geometry.computeBoundingSphere();
  26797. }
  26798. setFromObject(object) {
  26799. this.object = object;
  26800. this.update();
  26801. return this;
  26802. }
  26803. copy(source) {
  26804. LineSegments.prototype.copy.call(this, source);
  26805. this.object = source.object;
  26806. return this;
  26807. }
  26808. }
  26809. class Box3Helper extends LineSegments {
  26810. constructor(box, color = 0xffff00) {
  26811. 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]);
  26812. 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];
  26813. const geometry = new BufferGeometry();
  26814. geometry.setIndex(new BufferAttribute(indices, 1));
  26815. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  26816. super(geometry, new LineBasicMaterial({
  26817. color: color,
  26818. toneMapped: false
  26819. }));
  26820. this.box = box;
  26821. this.type = 'Box3Helper';
  26822. this.geometry.computeBoundingSphere();
  26823. }
  26824. updateMatrixWorld(force) {
  26825. const box = this.box;
  26826. if (box.isEmpty()) return;
  26827. box.getCenter(this.position);
  26828. box.getSize(this.scale);
  26829. this.scale.multiplyScalar(0.5);
  26830. super.updateMatrixWorld(force);
  26831. }
  26832. }
  26833. class PlaneHelper extends Line {
  26834. constructor(plane, size = 1, hex = 0xffff00) {
  26835. const color = hex;
  26836. 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];
  26837. const geometry = new BufferGeometry();
  26838. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  26839. geometry.computeBoundingSphere();
  26840. super(geometry, new LineBasicMaterial({
  26841. color: color,
  26842. toneMapped: false
  26843. }));
  26844. this.type = 'PlaneHelper';
  26845. this.plane = plane;
  26846. this.size = size;
  26847. const positions2 = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1];
  26848. const geometry2 = new BufferGeometry();
  26849. geometry2.setAttribute('position', new Float32BufferAttribute(positions2, 3));
  26850. geometry2.computeBoundingSphere();
  26851. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  26852. color: color,
  26853. opacity: 0.2,
  26854. transparent: true,
  26855. depthWrite: false,
  26856. toneMapped: false
  26857. })));
  26858. }
  26859. updateMatrixWorld(force) {
  26860. let scale = -this.plane.constant;
  26861. if (Math.abs(scale) < 1e-8) scale = 1e-8; // sign does not matter
  26862. this.scale.set(0.5 * this.size, 0.5 * this.size, scale);
  26863. this.children[0].material.side = scale < 0 ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  26864. this.lookAt(this.plane.normal);
  26865. super.updateMatrixWorld(force);
  26866. }
  26867. }
  26868. const _axis = /*@__PURE__*/new Vector3();
  26869. let _lineGeometry, _coneGeometry;
  26870. class ArrowHelper extends Object3D {
  26871. // dir is assumed to be normalized
  26872. 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) {
  26873. super();
  26874. this.type = 'ArrowHelper';
  26875. if (_lineGeometry === undefined) {
  26876. _lineGeometry = new BufferGeometry();
  26877. _lineGeometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
  26878. _coneGeometry = new CylinderGeometry(0, 0.5, 1, 5, 1);
  26879. _coneGeometry.translate(0, -0.5, 0);
  26880. }
  26881. this.position.copy(origin);
  26882. this.line = new Line(_lineGeometry, new LineBasicMaterial({
  26883. color: color,
  26884. toneMapped: false
  26885. }));
  26886. this.line.matrixAutoUpdate = false;
  26887. this.add(this.line);
  26888. this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
  26889. color: color,
  26890. toneMapped: false
  26891. }));
  26892. this.cone.matrixAutoUpdate = false;
  26893. this.add(this.cone);
  26894. this.setDirection(dir);
  26895. this.setLength(length, headLength, headWidth);
  26896. }
  26897. setDirection(dir) {
  26898. // dir is assumed to be normalized
  26899. if (dir.y > 0.99999) {
  26900. this.quaternion.set(0, 0, 0, 1);
  26901. } else if (dir.y < -0.99999) {
  26902. this.quaternion.set(1, 0, 0, 0);
  26903. } else {
  26904. _axis.set(dir.z, 0, -dir.x).normalize();
  26905. const radians = Math.acos(dir.y);
  26906. this.quaternion.setFromAxisAngle(_axis, radians);
  26907. }
  26908. }
  26909. setLength(length, headLength = length * 0.2, headWidth = headLength * 0.2) {
  26910. this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
  26911. this.line.updateMatrix();
  26912. this.cone.scale.set(headWidth, headLength, headWidth);
  26913. this.cone.position.y = length;
  26914. this.cone.updateMatrix();
  26915. }
  26916. setColor(color) {
  26917. this.line.material.color.set(color);
  26918. this.cone.material.color.set(color);
  26919. }
  26920. copy(source) {
  26921. super.copy(source, false);
  26922. this.line.copy(source.line);
  26923. this.cone.copy(source.cone);
  26924. return this;
  26925. }
  26926. }
  26927. class AxesHelper extends LineSegments {
  26928. constructor(size = 1) {
  26929. const vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
  26930. const colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
  26931. const geometry = new BufferGeometry();
  26932. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  26933. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  26934. const material = new LineBasicMaterial({
  26935. vertexColors: true,
  26936. toneMapped: false
  26937. });
  26938. super(geometry, material);
  26939. this.type = 'AxesHelper';
  26940. }
  26941. dispose() {
  26942. this.geometry.dispose();
  26943. this.material.dispose();
  26944. }
  26945. }
  26946. const _floatView = new Float32Array(1);
  26947. const _int32View = new Int32Array(_floatView.buffer);
  26948. class DataUtils {
  26949. // Converts float32 to float16 (stored as uint16 value).
  26950. static toHalfFloat(val) {
  26951. // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
  26952. /* This method is faster than the OpenEXR implementation (very often
  26953. * used, eg. in Ogre), with the additional benefit of rounding, inspired
  26954. * by James Tursa?s half-precision code. */
  26955. _floatView[0] = val;
  26956. const x = _int32View[0];
  26957. let bits = x >> 16 & 0x8000;
  26958. /* Get the sign */
  26959. let m = x >> 12 & 0x07ff;
  26960. /* Keep one extra bit for rounding */
  26961. const e = x >> 23 & 0xff;
  26962. /* Using int is faster here */
  26963. /* If zero, or denormal, or exponent underflows too much for a denormal
  26964. * half, return signed zero. */
  26965. if (e < 103) return bits;
  26966. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  26967. if (e > 142) {
  26968. bits |= 0x7c00;
  26969. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  26970. * not Inf, so make sure we set one mantissa bit too. */
  26971. bits |= (e == 255 ? 0 : 1) && x & 0x007fffff;
  26972. return bits;
  26973. }
  26974. /* If exponent underflows but not too much, return a denormal */
  26975. if (e < 113) {
  26976. m |= 0x0800;
  26977. /* Extra rounding may overflow and set mantissa to 0 and exponent
  26978. * to 1, which is OK. */
  26979. bits |= (m >> 114 - e) + (m >> 113 - e & 1);
  26980. return bits;
  26981. }
  26982. bits |= e - 112 << 10 | m >> 1;
  26983. /* Extra rounding. An overflow will set mantissa to 0 and increment
  26984. * the exponent, which is OK. */
  26985. bits += m & 1;
  26986. return bits;
  26987. }
  26988. }
  26989. const LOD_MIN = 4;
  26990. const LOD_MAX = 8;
  26991. const SIZE_MAX = Math.pow(2, LOD_MAX); // The standard deviations (radians) associated with the extra mips. These are
  26992. // chosen to approximate a Trowbridge-Reitz distribution function times the
  26993. // geometric shadowing function. These sigma values squared must match the
  26994. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  26995. const EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582];
  26996. 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
  26997. // samples and exit early, but not recompile the shader.
  26998. const MAX_SAMPLES = 20;
  26999. const ENCODINGS = {
  27000. [LinearEncoding]: 0,
  27001. [sRGBEncoding]: 1,
  27002. [RGBEEncoding]: 2,
  27003. [RGBM7Encoding]: 3,
  27004. [RGBM16Encoding]: 4,
  27005. [RGBDEncoding]: 5,
  27006. [GammaEncoding]: 6
  27007. };
  27008. const backgroundMaterial = new MeshBasicMaterial({
  27009. side: BackSide,
  27010. depthWrite: false,
  27011. depthTest: false
  27012. });
  27013. const backgroundBox = new Mesh(new BoxGeometry(), backgroundMaterial);
  27014. const _flatCamera = /*@__PURE__*/new OrthographicCamera();
  27015. const {
  27016. _lodPlanes,
  27017. _sizeLods,
  27018. _sigmas
  27019. } = /*@__PURE__*/_createPlanes();
  27020. const _clearColor = /*@__PURE__*/new Color();
  27021. let _oldTarget = null; // Golden Ratio
  27022. const PHI = (1 + Math.sqrt(5)) / 2;
  27023. const INV_PHI = 1 / PHI; // Vertices of a dodecahedron (except the opposites, which represent the
  27024. // same axis), used as axis directions evenly spread on a sphere.
  27025. 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)];
  27026. /**
  27027. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  27028. * (PMREM) from a cubeMap environment texture. This allows different levels of
  27029. * blur to be quickly accessed based on material roughness. It is packed into a
  27030. * special CubeUV format that allows us to perform custom interpolation so that
  27031. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  27032. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  27033. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  27034. * higher roughness levels. In this way we maintain resolution to smoothly
  27035. * interpolate diffuse lighting while limiting sampling computation.
  27036. *
  27037. * Paper: Fast, Accurate Image-Based Lighting
  27038. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  27039. */
  27040. function convertLinearToRGBE(color) {
  27041. const maxComponent = Math.max(color.r, color.g, color.b);
  27042. const fExp = Math.min(Math.max(Math.ceil(Math.log2(maxComponent)), -128.0), 127.0);
  27043. color.multiplyScalar(Math.pow(2.0, -fExp));
  27044. const alpha = (fExp + 128.0) / 255.0;
  27045. return alpha;
  27046. }
  27047. class PMREMGenerator {
  27048. constructor(renderer) {
  27049. this._renderer = renderer;
  27050. this._pingPongRenderTarget = null;
  27051. this._blurMaterial = _getBlurShader(MAX_SAMPLES);
  27052. this._equirectShader = null;
  27053. this._cubemapShader = null;
  27054. this._compileMaterial(this._blurMaterial);
  27055. }
  27056. /**
  27057. * Generates a PMREM from a supplied Scene, which can be faster than using an
  27058. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  27059. * in radians to be applied to the scene before PMREM generation. Optional near
  27060. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  27061. * is placed at the origin).
  27062. */
  27063. fromScene(scene, sigma = 0, near = 0.1, far = 100) {
  27064. _oldTarget = this._renderer.getRenderTarget();
  27065. const cubeUVRenderTarget = this._allocateTargets();
  27066. this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget);
  27067. if (sigma > 0) {
  27068. this._blur(cubeUVRenderTarget, 0, 0, sigma);
  27069. }
  27070. this._applyPMREM(cubeUVRenderTarget);
  27071. this._cleanup(cubeUVRenderTarget);
  27072. return cubeUVRenderTarget;
  27073. }
  27074. /**
  27075. * Generates a PMREM from an equirectangular texture, which can be either LDR
  27076. * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
  27077. * as this matches best with the 256 x 256 cubemap output.
  27078. */
  27079. fromEquirectangular(equirectangular) {
  27080. return this._fromTexture(equirectangular);
  27081. }
  27082. /**
  27083. * Generates a PMREM from an cubemap texture, which can be either LDR
  27084. * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
  27085. * as this matches best with the 256 x 256 cubemap output.
  27086. */
  27087. fromCubemap(cubemap) {
  27088. return this._fromTexture(cubemap);
  27089. }
  27090. /**
  27091. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  27092. * your texture's network fetch for increased concurrency.
  27093. */
  27094. compileCubemapShader() {
  27095. if (this._cubemapShader === null) {
  27096. this._cubemapShader = _getCubemapShader();
  27097. this._compileMaterial(this._cubemapShader);
  27098. }
  27099. }
  27100. /**
  27101. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  27102. * your texture's network fetch for increased concurrency.
  27103. */
  27104. compileEquirectangularShader() {
  27105. if (this._equirectShader === null) {
  27106. this._equirectShader = _getEquirectShader();
  27107. this._compileMaterial(this._equirectShader);
  27108. }
  27109. }
  27110. /**
  27111. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  27112. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  27113. * one of them will cause any others to also become unusable.
  27114. */
  27115. dispose() {
  27116. this._blurMaterial.dispose();
  27117. if (this._cubemapShader !== null) this._cubemapShader.dispose();
  27118. if (this._equirectShader !== null) this._equirectShader.dispose();
  27119. for (let i = 0; i < _lodPlanes.length; i++) {
  27120. _lodPlanes[i].dispose();
  27121. }
  27122. } // private interface
  27123. _cleanup(outputTarget) {
  27124. this._pingPongRenderTarget.dispose();
  27125. this._renderer.setRenderTarget(_oldTarget);
  27126. outputTarget.scissorTest = false;
  27127. _setViewport(outputTarget, 0, 0, outputTarget.width, outputTarget.height);
  27128. }
  27129. _fromTexture(texture) {
  27130. _oldTarget = this._renderer.getRenderTarget();
  27131. const cubeUVRenderTarget = this._allocateTargets(texture);
  27132. this._textureToCubeUV(texture, cubeUVRenderTarget);
  27133. this._applyPMREM(cubeUVRenderTarget);
  27134. this._cleanup(cubeUVRenderTarget);
  27135. return cubeUVRenderTarget;
  27136. }
  27137. _allocateTargets(texture) {
  27138. // warning: null texture is valid
  27139. const params = {
  27140. magFilter: NearestFilter,
  27141. minFilter: NearestFilter,
  27142. generateMipmaps: false,
  27143. type: UnsignedByteType,
  27144. format: RGBEFormat,
  27145. encoding: _isLDR(texture) ? texture.encoding : RGBEEncoding,
  27146. depthBuffer: false
  27147. };
  27148. const cubeUVRenderTarget = _createRenderTarget(params);
  27149. cubeUVRenderTarget.depthBuffer = texture ? false : true;
  27150. this._pingPongRenderTarget = _createRenderTarget(params);
  27151. return cubeUVRenderTarget;
  27152. }
  27153. _compileMaterial(material) {
  27154. const tmpMesh = new Mesh(_lodPlanes[0], material);
  27155. this._renderer.compile(tmpMesh, _flatCamera);
  27156. }
  27157. _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) {
  27158. const fov = 90;
  27159. const aspect = 1;
  27160. const cubeCamera = new PerspectiveCamera(fov, aspect, near, far);
  27161. const upSign = [1, -1, 1, 1, 1, 1];
  27162. const forwardSign = [1, 1, 1, -1, -1, -1];
  27163. const renderer = this._renderer;
  27164. const originalAutoClear = renderer.autoClear;
  27165. const outputEncoding = renderer.outputEncoding;
  27166. const toneMapping = renderer.toneMapping;
  27167. renderer.getClearColor(_clearColor);
  27168. renderer.toneMapping = NoToneMapping;
  27169. renderer.outputEncoding = LinearEncoding;
  27170. renderer.autoClear = false;
  27171. let useSolidColor = false;
  27172. const background = scene.background;
  27173. if (background) {
  27174. if (background.isColor) {
  27175. backgroundMaterial.color.copy(background).convertSRGBToLinear();
  27176. scene.background = null;
  27177. const alpha = convertLinearToRGBE(backgroundMaterial.color);
  27178. backgroundMaterial.opacity = alpha;
  27179. useSolidColor = true;
  27180. }
  27181. } else {
  27182. backgroundMaterial.color.copy(_clearColor).convertSRGBToLinear();
  27183. const alpha = convertLinearToRGBE(backgroundMaterial.color);
  27184. backgroundMaterial.opacity = alpha;
  27185. useSolidColor = true;
  27186. }
  27187. for (let i = 0; i < 6; i++) {
  27188. const col = i % 3;
  27189. if (col == 0) {
  27190. cubeCamera.up.set(0, upSign[i], 0);
  27191. cubeCamera.lookAt(forwardSign[i], 0, 0);
  27192. } else if (col == 1) {
  27193. cubeCamera.up.set(0, 0, upSign[i]);
  27194. cubeCamera.lookAt(0, forwardSign[i], 0);
  27195. } else {
  27196. cubeCamera.up.set(0, upSign[i], 0);
  27197. cubeCamera.lookAt(0, 0, forwardSign[i]);
  27198. }
  27199. _setViewport(cubeUVRenderTarget, col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX);
  27200. renderer.setRenderTarget(cubeUVRenderTarget);
  27201. if (useSolidColor) {
  27202. renderer.render(backgroundBox, cubeCamera);
  27203. }
  27204. renderer.render(scene, cubeCamera);
  27205. }
  27206. renderer.toneMapping = toneMapping;
  27207. renderer.outputEncoding = outputEncoding;
  27208. renderer.autoClear = originalAutoClear;
  27209. }
  27210. _textureToCubeUV(texture, cubeUVRenderTarget) {
  27211. const renderer = this._renderer;
  27212. if (texture.isCubeTexture) {
  27213. if (this._cubemapShader == null) {
  27214. this._cubemapShader = _getCubemapShader();
  27215. }
  27216. } else {
  27217. if (this._equirectShader == null) {
  27218. this._equirectShader = _getEquirectShader();
  27219. }
  27220. }
  27221. const material = texture.isCubeTexture ? this._cubemapShader : this._equirectShader;
  27222. const mesh = new Mesh(_lodPlanes[0], material);
  27223. const uniforms = material.uniforms;
  27224. uniforms['envMap'].value = texture;
  27225. if (!texture.isCubeTexture) {
  27226. uniforms['texelSize'].value.set(1.0 / texture.image.width, 1.0 / texture.image.height);
  27227. }
  27228. uniforms['inputEncoding'].value = ENCODINGS[texture.encoding];
  27229. uniforms['outputEncoding'].value = ENCODINGS[cubeUVRenderTarget.texture.encoding];
  27230. _setViewport(cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX);
  27231. renderer.setRenderTarget(cubeUVRenderTarget);
  27232. renderer.render(mesh, _flatCamera);
  27233. }
  27234. _applyPMREM(cubeUVRenderTarget) {
  27235. const renderer = this._renderer;
  27236. const autoClear = renderer.autoClear;
  27237. renderer.autoClear = false;
  27238. for (let i = 1; i < TOTAL_LODS; i++) {
  27239. const sigma = Math.sqrt(_sigmas[i] * _sigmas[i] - _sigmas[i - 1] * _sigmas[i - 1]);
  27240. const poleAxis = _axisDirections[(i - 1) % _axisDirections.length];
  27241. this._blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis);
  27242. }
  27243. renderer.autoClear = autoClear;
  27244. }
  27245. /**
  27246. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  27247. * vertically and horizontally, but this breaks down on a cube. Here we apply
  27248. * the blur latitudinally (around the poles), and then longitudinally (towards
  27249. * the poles) to approximate the orthogonally-separable blur. It is least
  27250. * accurate at the poles, but still does a decent job.
  27251. */
  27252. _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) {
  27253. const pingPongRenderTarget = this._pingPongRenderTarget;
  27254. this._halfBlur(cubeUVRenderTarget, pingPongRenderTarget, lodIn, lodOut, sigma, 'latitudinal', poleAxis);
  27255. this._halfBlur(pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, 'longitudinal', poleAxis);
  27256. }
  27257. _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) {
  27258. const renderer = this._renderer;
  27259. const blurMaterial = this._blurMaterial;
  27260. if (direction !== 'latitudinal' && direction !== 'longitudinal') {
  27261. console.error('blur direction must be either latitudinal or longitudinal!');
  27262. } // Number of standard deviations at which to cut off the discrete approximation.
  27263. const STANDARD_DEVIATIONS = 3;
  27264. const blurMesh = new Mesh(_lodPlanes[lodOut], blurMaterial);
  27265. const blurUniforms = blurMaterial.uniforms;
  27266. const pixels = _sizeLods[lodIn] - 1;
  27267. const radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1);
  27268. const sigmaPixels = sigmaRadians / radiansPerPixel;
  27269. const samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES;
  27270. if (samples > MAX_SAMPLES) {
  27271. console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES}`);
  27272. }
  27273. const weights = [];
  27274. let sum = 0;
  27275. for (let i = 0; i < MAX_SAMPLES; ++i) {
  27276. const x = i / sigmaPixels;
  27277. const weight = Math.exp(-x * x / 2);
  27278. weights.push(weight);
  27279. if (i == 0) {
  27280. sum += weight;
  27281. } else if (i < samples) {
  27282. sum += 2 * weight;
  27283. }
  27284. }
  27285. for (let i = 0; i < weights.length; i++) {
  27286. weights[i] = weights[i] / sum;
  27287. }
  27288. blurUniforms['envMap'].value = targetIn.texture;
  27289. blurUniforms['samples'].value = samples;
  27290. blurUniforms['weights'].value = weights;
  27291. blurUniforms['latitudinal'].value = direction === 'latitudinal';
  27292. if (poleAxis) {
  27293. blurUniforms['poleAxis'].value = poleAxis;
  27294. }
  27295. blurUniforms['dTheta'].value = radiansPerPixel;
  27296. blurUniforms['mipInt'].value = LOD_MAX - lodIn;
  27297. blurUniforms['inputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
  27298. blurUniforms['outputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
  27299. const outputSize = _sizeLods[lodOut];
  27300. const x = 3 * Math.max(0, SIZE_MAX - 2 * outputSize);
  27301. const y = (lodOut === 0 ? 0 : 2 * SIZE_MAX) + 2 * outputSize * (lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0);
  27302. _setViewport(targetOut, x, y, 3 * outputSize, 2 * outputSize);
  27303. renderer.setRenderTarget(targetOut);
  27304. renderer.render(blurMesh, _flatCamera);
  27305. }
  27306. }
  27307. function _isLDR(texture) {
  27308. if (texture === undefined || texture.type !== UnsignedByteType) return false;
  27309. return texture.encoding === LinearEncoding || texture.encoding === sRGBEncoding || texture.encoding === GammaEncoding;
  27310. }
  27311. function _createPlanes() {
  27312. const _lodPlanes = [];
  27313. const _sizeLods = [];
  27314. const _sigmas = [];
  27315. let lod = LOD_MAX;
  27316. for (let i = 0; i < TOTAL_LODS; i++) {
  27317. const sizeLod = Math.pow(2, lod);
  27318. _sizeLods.push(sizeLod);
  27319. let sigma = 1.0 / sizeLod;
  27320. if (i > LOD_MAX - LOD_MIN) {
  27321. sigma = EXTRA_LOD_SIGMA[i - LOD_MAX + LOD_MIN - 1];
  27322. } else if (i == 0) {
  27323. sigma = 0;
  27324. }
  27325. _sigmas.push(sigma);
  27326. const texelSize = 1.0 / (sizeLod - 1);
  27327. const min = -texelSize / 2;
  27328. const max = 1 + texelSize / 2;
  27329. const uv1 = [min, min, max, min, max, max, min, min, max, max, min, max];
  27330. const cubeFaces = 6;
  27331. const vertices = 6;
  27332. const positionSize = 3;
  27333. const uvSize = 2;
  27334. const faceIndexSize = 1;
  27335. const position = new Float32Array(positionSize * vertices * cubeFaces);
  27336. const uv = new Float32Array(uvSize * vertices * cubeFaces);
  27337. const faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces);
  27338. for (let face = 0; face < cubeFaces; face++) {
  27339. const x = face % 3 * 2 / 3 - 1;
  27340. const y = face > 2 ? 0 : -1;
  27341. 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];
  27342. position.set(coordinates, positionSize * vertices * face);
  27343. uv.set(uv1, uvSize * vertices * face);
  27344. const fill = [face, face, face, face, face, face];
  27345. faceIndex.set(fill, faceIndexSize * vertices * face);
  27346. }
  27347. const planes = new BufferGeometry();
  27348. planes.setAttribute('position', new BufferAttribute(position, positionSize));
  27349. planes.setAttribute('uv', new BufferAttribute(uv, uvSize));
  27350. planes.setAttribute('faceIndex', new BufferAttribute(faceIndex, faceIndexSize));
  27351. _lodPlanes.push(planes);
  27352. if (lod > LOD_MIN) {
  27353. lod--;
  27354. }
  27355. }
  27356. return {
  27357. _lodPlanes,
  27358. _sizeLods,
  27359. _sigmas
  27360. };
  27361. }
  27362. function _createRenderTarget(params) {
  27363. const cubeUVRenderTarget = new WebGLRenderTarget(3 * SIZE_MAX, 3 * SIZE_MAX, params);
  27364. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  27365. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  27366. cubeUVRenderTarget.scissorTest = true;
  27367. return cubeUVRenderTarget;
  27368. }
  27369. function _setViewport(target, x, y, width, height) {
  27370. target.viewport.set(x, y, width, height);
  27371. target.scissor.set(x, y, width, height);
  27372. }
  27373. function _getBlurShader(maxSamples) {
  27374. const weights = new Float32Array(maxSamples);
  27375. const poleAxis = new Vector3(0, 1, 0);
  27376. const shaderMaterial = new RawShaderMaterial({
  27377. name: 'SphericalGaussianBlur',
  27378. defines: {
  27379. 'n': maxSamples
  27380. },
  27381. uniforms: {
  27382. 'envMap': {
  27383. value: null
  27384. },
  27385. 'samples': {
  27386. value: 1
  27387. },
  27388. 'weights': {
  27389. value: weights
  27390. },
  27391. 'latitudinal': {
  27392. value: false
  27393. },
  27394. 'dTheta': {
  27395. value: 0
  27396. },
  27397. 'mipInt': {
  27398. value: 0
  27399. },
  27400. 'poleAxis': {
  27401. value: poleAxis
  27402. },
  27403. 'inputEncoding': {
  27404. value: ENCODINGS[LinearEncoding]
  27405. },
  27406. 'outputEncoding': {
  27407. value: ENCODINGS[LinearEncoding]
  27408. }
  27409. },
  27410. vertexShader: _getCommonVertexShader(),
  27411. fragmentShader:
  27412. /* glsl */
  27413. `
  27414. precision mediump float;
  27415. precision mediump int;
  27416. varying vec3 vOutputDirection;
  27417. uniform sampler2D envMap;
  27418. uniform int samples;
  27419. uniform float weights[ n ];
  27420. uniform bool latitudinal;
  27421. uniform float dTheta;
  27422. uniform float mipInt;
  27423. uniform vec3 poleAxis;
  27424. ${_getEncodings()}
  27425. #define ENVMAP_TYPE_CUBE_UV
  27426. #include <cube_uv_reflection_fragment>
  27427. vec3 getSample( float theta, vec3 axis ) {
  27428. float cosTheta = cos( theta );
  27429. // Rodrigues' axis-angle rotation
  27430. vec3 sampleDirection = vOutputDirection * cosTheta
  27431. + cross( axis, vOutputDirection ) * sin( theta )
  27432. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  27433. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  27434. }
  27435. void main() {
  27436. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  27437. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  27438. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  27439. }
  27440. axis = normalize( axis );
  27441. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  27442. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  27443. for ( int i = 1; i < n; i++ ) {
  27444. if ( i >= samples ) {
  27445. break;
  27446. }
  27447. float theta = dTheta * float( i );
  27448. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  27449. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  27450. }
  27451. gl_FragColor = linearToOutputTexel( gl_FragColor );
  27452. }
  27453. `,
  27454. blending: NoBlending,
  27455. depthTest: false,
  27456. depthWrite: false
  27457. });
  27458. return shaderMaterial;
  27459. }
  27460. function _getEquirectShader() {
  27461. const texelSize = new Vector2(1, 1);
  27462. const shaderMaterial = new RawShaderMaterial({
  27463. name: 'EquirectangularToCubeUV',
  27464. uniforms: {
  27465. 'envMap': {
  27466. value: null
  27467. },
  27468. 'texelSize': {
  27469. value: texelSize
  27470. },
  27471. 'inputEncoding': {
  27472. value: ENCODINGS[LinearEncoding]
  27473. },
  27474. 'outputEncoding': {
  27475. value: ENCODINGS[LinearEncoding]
  27476. }
  27477. },
  27478. vertexShader: _getCommonVertexShader(),
  27479. fragmentShader:
  27480. /* glsl */
  27481. `
  27482. precision mediump float;
  27483. precision mediump int;
  27484. varying vec3 vOutputDirection;
  27485. uniform sampler2D envMap;
  27486. uniform vec2 texelSize;
  27487. ${_getEncodings()}
  27488. #include <common>
  27489. void main() {
  27490. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  27491. vec3 outputDirection = normalize( vOutputDirection );
  27492. vec2 uv = equirectUv( outputDirection );
  27493. vec2 f = fract( uv / texelSize - 0.5 );
  27494. uv -= f * texelSize;
  27495. vec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  27496. uv.x += texelSize.x;
  27497. vec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  27498. uv.y += texelSize.y;
  27499. vec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  27500. uv.x -= texelSize.x;
  27501. vec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  27502. vec3 tm = mix( tl, tr, f.x );
  27503. vec3 bm = mix( bl, br, f.x );
  27504. gl_FragColor.rgb = mix( tm, bm, f.y );
  27505. gl_FragColor = linearToOutputTexel( gl_FragColor );
  27506. }
  27507. `,
  27508. blending: NoBlending,
  27509. depthTest: false,
  27510. depthWrite: false
  27511. });
  27512. return shaderMaterial;
  27513. }
  27514. function _getCubemapShader() {
  27515. const shaderMaterial = new RawShaderMaterial({
  27516. name: 'CubemapToCubeUV',
  27517. uniforms: {
  27518. 'envMap': {
  27519. value: null
  27520. },
  27521. 'inputEncoding': {
  27522. value: ENCODINGS[LinearEncoding]
  27523. },
  27524. 'outputEncoding': {
  27525. value: ENCODINGS[LinearEncoding]
  27526. }
  27527. },
  27528. vertexShader: _getCommonVertexShader(),
  27529. fragmentShader:
  27530. /* glsl */
  27531. `
  27532. precision mediump float;
  27533. precision mediump int;
  27534. varying vec3 vOutputDirection;
  27535. uniform samplerCube envMap;
  27536. ${_getEncodings()}
  27537. void main() {
  27538. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  27539. gl_FragColor.rgb = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) ).rgb;
  27540. gl_FragColor = linearToOutputTexel( gl_FragColor );
  27541. }
  27542. `,
  27543. blending: NoBlending,
  27544. depthTest: false,
  27545. depthWrite: false
  27546. });
  27547. return shaderMaterial;
  27548. }
  27549. function _getCommonVertexShader() {
  27550. return (
  27551. /* glsl */
  27552. `
  27553. precision mediump float;
  27554. precision mediump int;
  27555. attribute vec3 position;
  27556. attribute vec2 uv;
  27557. attribute float faceIndex;
  27558. varying vec3 vOutputDirection;
  27559. // RH coordinate system; PMREM face-indexing convention
  27560. vec3 getDirection( vec2 uv, float face ) {
  27561. uv = 2.0 * uv - 1.0;
  27562. vec3 direction = vec3( uv, 1.0 );
  27563. if ( face == 0.0 ) {
  27564. direction = direction.zyx; // ( 1, v, u ) pos x
  27565. } else if ( face == 1.0 ) {
  27566. direction = direction.xzy;
  27567. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  27568. } else if ( face == 2.0 ) {
  27569. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  27570. } else if ( face == 3.0 ) {
  27571. direction = direction.zyx;
  27572. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  27573. } else if ( face == 4.0 ) {
  27574. direction = direction.xzy;
  27575. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  27576. } else if ( face == 5.0 ) {
  27577. direction.z *= -1.0; // ( u, v, -1 ) neg z
  27578. }
  27579. return direction;
  27580. }
  27581. void main() {
  27582. vOutputDirection = getDirection( uv, faceIndex );
  27583. gl_Position = vec4( position, 1.0 );
  27584. }
  27585. `
  27586. );
  27587. }
  27588. function _getEncodings() {
  27589. return (
  27590. /* glsl */
  27591. `
  27592. uniform int inputEncoding;
  27593. uniform int outputEncoding;
  27594. #include <encodings_pars_fragment>
  27595. vec4 inputTexelToLinear( vec4 value ) {
  27596. if ( inputEncoding == 0 ) {
  27597. return value;
  27598. } else if ( inputEncoding == 1 ) {
  27599. return sRGBToLinear( value );
  27600. } else if ( inputEncoding == 2 ) {
  27601. return RGBEToLinear( value );
  27602. } else if ( inputEncoding == 3 ) {
  27603. return RGBMToLinear( value, 7.0 );
  27604. } else if ( inputEncoding == 4 ) {
  27605. return RGBMToLinear( value, 16.0 );
  27606. } else if ( inputEncoding == 5 ) {
  27607. return RGBDToLinear( value, 256.0 );
  27608. } else {
  27609. return GammaToLinear( value, 2.2 );
  27610. }
  27611. }
  27612. vec4 linearToOutputTexel( vec4 value ) {
  27613. if ( outputEncoding == 0 ) {
  27614. return value;
  27615. } else if ( outputEncoding == 1 ) {
  27616. return LinearTosRGB( value );
  27617. } else if ( outputEncoding == 2 ) {
  27618. return LinearToRGBE( value );
  27619. } else if ( outputEncoding == 3 ) {
  27620. return LinearToRGBM( value, 7.0 );
  27621. } else if ( outputEncoding == 4 ) {
  27622. return LinearToRGBM( value, 16.0 );
  27623. } else if ( outputEncoding == 5 ) {
  27624. return LinearToRGBD( value, 256.0 );
  27625. } else {
  27626. return LinearToGamma( value, 2.2 );
  27627. }
  27628. }
  27629. vec4 envMapTexelToLinear( vec4 color ) {
  27630. return inputTexelToLinear( color );
  27631. }
  27632. `
  27633. );
  27634. }
  27635. const LineStrip = 0;
  27636. const LinePieces = 1;
  27637. const NoColors = 0;
  27638. const FaceColors = 1;
  27639. const VertexColors = 2;
  27640. function MeshFaceMaterial(materials) {
  27641. console.warn('THREE.MeshFaceMaterial has been removed. Use an Array instead.');
  27642. return materials;
  27643. }
  27644. function MultiMaterial(materials = []) {
  27645. console.warn('THREE.MultiMaterial has been removed. Use an Array instead.');
  27646. materials.isMultiMaterial = true;
  27647. materials.materials = materials;
  27648. materials.clone = function () {
  27649. return materials.slice();
  27650. };
  27651. return materials;
  27652. }
  27653. function PointCloud(geometry, material) {
  27654. console.warn('THREE.PointCloud has been renamed to THREE.Points.');
  27655. return new Points(geometry, material);
  27656. }
  27657. function Particle(material) {
  27658. console.warn('THREE.Particle has been renamed to THREE.Sprite.');
  27659. return new Sprite(material);
  27660. }
  27661. function ParticleSystem(geometry, material) {
  27662. console.warn('THREE.ParticleSystem has been renamed to THREE.Points.');
  27663. return new Points(geometry, material);
  27664. }
  27665. function PointCloudMaterial(parameters) {
  27666. console.warn('THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.');
  27667. return new PointsMaterial(parameters);
  27668. }
  27669. function ParticleBasicMaterial(parameters) {
  27670. console.warn('THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.');
  27671. return new PointsMaterial(parameters);
  27672. }
  27673. function ParticleSystemMaterial(parameters) {
  27674. console.warn('THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.');
  27675. return new PointsMaterial(parameters);
  27676. }
  27677. function Vertex(x, y, z) {
  27678. console.warn('THREE.Vertex has been removed. Use THREE.Vector3 instead.');
  27679. return new Vector3(x, y, z);
  27680. } //
  27681. function DynamicBufferAttribute(array, itemSize) {
  27682. console.warn('THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.');
  27683. return new BufferAttribute(array, itemSize).setUsage(DynamicDrawUsage);
  27684. }
  27685. function Int8Attribute(array, itemSize) {
  27686. console.warn('THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.');
  27687. return new Int8BufferAttribute(array, itemSize);
  27688. }
  27689. function Uint8Attribute(array, itemSize) {
  27690. console.warn('THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.');
  27691. return new Uint8BufferAttribute(array, itemSize);
  27692. }
  27693. function Uint8ClampedAttribute(array, itemSize) {
  27694. console.warn('THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.');
  27695. return new Uint8ClampedBufferAttribute(array, itemSize);
  27696. }
  27697. function Int16Attribute(array, itemSize) {
  27698. console.warn('THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.');
  27699. return new Int16BufferAttribute(array, itemSize);
  27700. }
  27701. function Uint16Attribute(array, itemSize) {
  27702. console.warn('THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.');
  27703. return new Uint16BufferAttribute(array, itemSize);
  27704. }
  27705. function Int32Attribute(array, itemSize) {
  27706. console.warn('THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.');
  27707. return new Int32BufferAttribute(array, itemSize);
  27708. }
  27709. function Uint32Attribute(array, itemSize) {
  27710. console.warn('THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.');
  27711. return new Uint32BufferAttribute(array, itemSize);
  27712. }
  27713. function Float32Attribute(array, itemSize) {
  27714. console.warn('THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.');
  27715. return new Float32BufferAttribute(array, itemSize);
  27716. }
  27717. function Float64Attribute(array, itemSize) {
  27718. console.warn('THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.');
  27719. return new Float64BufferAttribute(array, itemSize);
  27720. } //
  27721. Curve.create = function (construct, getPoint) {
  27722. console.log('THREE.Curve.create() has been deprecated');
  27723. construct.prototype = Object.create(Curve.prototype);
  27724. construct.prototype.constructor = construct;
  27725. construct.prototype.getPoint = getPoint;
  27726. return construct;
  27727. }; //
  27728. Path.prototype.fromPoints = function (points) {
  27729. console.warn('THREE.Path: .fromPoints() has been renamed to .setFromPoints().');
  27730. return this.setFromPoints(points);
  27731. }; //
  27732. function AxisHelper(size) {
  27733. console.warn('THREE.AxisHelper has been renamed to THREE.AxesHelper.');
  27734. return new AxesHelper(size);
  27735. }
  27736. function BoundingBoxHelper(object, color) {
  27737. console.warn('THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.');
  27738. return new BoxHelper(object, color);
  27739. }
  27740. function EdgesHelper(object, hex) {
  27741. console.warn('THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.');
  27742. return new LineSegments(new EdgesGeometry(object.geometry), new LineBasicMaterial({
  27743. color: hex !== undefined ? hex : 0xffffff
  27744. }));
  27745. }
  27746. GridHelper.prototype.setColors = function () {
  27747. console.error('THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.');
  27748. };
  27749. SkeletonHelper.prototype.update = function () {
  27750. console.error('THREE.SkeletonHelper: update() no longer needs to be called.');
  27751. };
  27752. function WireframeHelper(object, hex) {
  27753. console.warn('THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.');
  27754. return new LineSegments(new WireframeGeometry(object.geometry), new LineBasicMaterial({
  27755. color: hex !== undefined ? hex : 0xffffff
  27756. }));
  27757. } //
  27758. Loader.prototype.extractUrlBase = function (url) {
  27759. console.warn('THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.');
  27760. return LoaderUtils.extractUrlBase(url);
  27761. };
  27762. Loader.Handlers = {
  27763. add: function ()
  27764. /* regex, loader */
  27765. {
  27766. console.error('THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.');
  27767. },
  27768. get: function ()
  27769. /* file */
  27770. {
  27771. console.error('THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.');
  27772. }
  27773. };
  27774. function XHRLoader(manager) {
  27775. console.warn('THREE.XHRLoader has been renamed to THREE.FileLoader.');
  27776. return new FileLoader(manager);
  27777. }
  27778. function BinaryTextureLoader(manager) {
  27779. console.warn('THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.');
  27780. return new DataTextureLoader(manager);
  27781. } //
  27782. Box2.prototype.center = function (optionalTarget) {
  27783. console.warn('THREE.Box2: .center() has been renamed to .getCenter().');
  27784. return this.getCenter(optionalTarget);
  27785. };
  27786. Box2.prototype.empty = function () {
  27787. console.warn('THREE.Box2: .empty() has been renamed to .isEmpty().');
  27788. return this.isEmpty();
  27789. };
  27790. Box2.prototype.isIntersectionBox = function (box) {
  27791. console.warn('THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().');
  27792. return this.intersectsBox(box);
  27793. };
  27794. Box2.prototype.size = function (optionalTarget) {
  27795. console.warn('THREE.Box2: .size() has been renamed to .getSize().');
  27796. return this.getSize(optionalTarget);
  27797. }; //
  27798. Box3.prototype.center = function (optionalTarget) {
  27799. console.warn('THREE.Box3: .center() has been renamed to .getCenter().');
  27800. return this.getCenter(optionalTarget);
  27801. };
  27802. Box3.prototype.empty = function () {
  27803. console.warn('THREE.Box3: .empty() has been renamed to .isEmpty().');
  27804. return this.isEmpty();
  27805. };
  27806. Box3.prototype.isIntersectionBox = function (box) {
  27807. console.warn('THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().');
  27808. return this.intersectsBox(box);
  27809. };
  27810. Box3.prototype.isIntersectionSphere = function (sphere) {
  27811. console.warn('THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  27812. return this.intersectsSphere(sphere);
  27813. };
  27814. Box3.prototype.size = function (optionalTarget) {
  27815. console.warn('THREE.Box3: .size() has been renamed to .getSize().');
  27816. return this.getSize(optionalTarget);
  27817. }; //
  27818. Sphere.prototype.empty = function () {
  27819. console.warn('THREE.Sphere: .empty() has been renamed to .isEmpty().');
  27820. return this.isEmpty();
  27821. }; //
  27822. Frustum.prototype.setFromMatrix = function (m) {
  27823. console.warn('THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().');
  27824. return this.setFromProjectionMatrix(m);
  27825. }; //
  27826. Line3.prototype.center = function (optionalTarget) {
  27827. console.warn('THREE.Line3: .center() has been renamed to .getCenter().');
  27828. return this.getCenter(optionalTarget);
  27829. }; //
  27830. Matrix3.prototype.flattenToArrayOffset = function (array, offset) {
  27831. console.warn('THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');
  27832. return this.toArray(array, offset);
  27833. };
  27834. Matrix3.prototype.multiplyVector3 = function (vector) {
  27835. console.warn('THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.');
  27836. return vector.applyMatrix3(this);
  27837. };
  27838. Matrix3.prototype.multiplyVector3Array = function ()
  27839. /* a */
  27840. {
  27841. console.error('THREE.Matrix3: .multiplyVector3Array() has been removed.');
  27842. };
  27843. Matrix3.prototype.applyToBufferAttribute = function (attribute) {
  27844. console.warn('THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.');
  27845. return attribute.applyMatrix3(this);
  27846. };
  27847. Matrix3.prototype.applyToVector3Array = function ()
  27848. /* array, offset, length */
  27849. {
  27850. console.error('THREE.Matrix3: .applyToVector3Array() has been removed.');
  27851. };
  27852. Matrix3.prototype.getInverse = function (matrix) {
  27853. console.warn('THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  27854. return this.copy(matrix).invert();
  27855. }; //
  27856. Matrix4.prototype.extractPosition = function (m) {
  27857. console.warn('THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().');
  27858. return this.copyPosition(m);
  27859. };
  27860. Matrix4.prototype.flattenToArrayOffset = function (array, offset) {
  27861. console.warn('THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');
  27862. return this.toArray(array, offset);
  27863. };
  27864. Matrix4.prototype.getPosition = function () {
  27865. console.warn('THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.');
  27866. return new Vector3().setFromMatrixColumn(this, 3);
  27867. };
  27868. Matrix4.prototype.setRotationFromQuaternion = function (q) {
  27869. console.warn('THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().');
  27870. return this.makeRotationFromQuaternion(q);
  27871. };
  27872. Matrix4.prototype.multiplyToArray = function () {
  27873. console.warn('THREE.Matrix4: .multiplyToArray() has been removed.');
  27874. };
  27875. Matrix4.prototype.multiplyVector3 = function (vector) {
  27876. console.warn('THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  27877. return vector.applyMatrix4(this);
  27878. };
  27879. Matrix4.prototype.multiplyVector4 = function (vector) {
  27880. console.warn('THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  27881. return vector.applyMatrix4(this);
  27882. };
  27883. Matrix4.prototype.multiplyVector3Array = function ()
  27884. /* a */
  27885. {
  27886. console.error('THREE.Matrix4: .multiplyVector3Array() has been removed.');
  27887. };
  27888. Matrix4.prototype.rotateAxis = function (v) {
  27889. console.warn('THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.');
  27890. v.transformDirection(this);
  27891. };
  27892. Matrix4.prototype.crossVector = function (vector) {
  27893. console.warn('THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  27894. return vector.applyMatrix4(this);
  27895. };
  27896. Matrix4.prototype.translate = function () {
  27897. console.error('THREE.Matrix4: .translate() has been removed.');
  27898. };
  27899. Matrix4.prototype.rotateX = function () {
  27900. console.error('THREE.Matrix4: .rotateX() has been removed.');
  27901. };
  27902. Matrix4.prototype.rotateY = function () {
  27903. console.error('THREE.Matrix4: .rotateY() has been removed.');
  27904. };
  27905. Matrix4.prototype.rotateZ = function () {
  27906. console.error('THREE.Matrix4: .rotateZ() has been removed.');
  27907. };
  27908. Matrix4.prototype.rotateByAxis = function () {
  27909. console.error('THREE.Matrix4: .rotateByAxis() has been removed.');
  27910. };
  27911. Matrix4.prototype.applyToBufferAttribute = function (attribute) {
  27912. console.warn('THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.');
  27913. return attribute.applyMatrix4(this);
  27914. };
  27915. Matrix4.prototype.applyToVector3Array = function ()
  27916. /* array, offset, length */
  27917. {
  27918. console.error('THREE.Matrix4: .applyToVector3Array() has been removed.');
  27919. };
  27920. Matrix4.prototype.makeFrustum = function (left, right, bottom, top, near, far) {
  27921. console.warn('THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.');
  27922. return this.makePerspective(left, right, top, bottom, near, far);
  27923. };
  27924. Matrix4.prototype.getInverse = function (matrix) {
  27925. console.warn('THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  27926. return this.copy(matrix).invert();
  27927. }; //
  27928. Plane.prototype.isIntersectionLine = function (line) {
  27929. console.warn('THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().');
  27930. return this.intersectsLine(line);
  27931. }; //
  27932. Quaternion.prototype.multiplyVector3 = function (vector) {
  27933. console.warn('THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.');
  27934. return vector.applyQuaternion(this);
  27935. };
  27936. Quaternion.prototype.inverse = function () {
  27937. console.warn('THREE.Quaternion: .inverse() has been renamed to invert().');
  27938. return this.invert();
  27939. }; //
  27940. Ray.prototype.isIntersectionBox = function (box) {
  27941. console.warn('THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().');
  27942. return this.intersectsBox(box);
  27943. };
  27944. Ray.prototype.isIntersectionPlane = function (plane) {
  27945. console.warn('THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().');
  27946. return this.intersectsPlane(plane);
  27947. };
  27948. Ray.prototype.isIntersectionSphere = function (sphere) {
  27949. console.warn('THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  27950. return this.intersectsSphere(sphere);
  27951. }; //
  27952. Triangle.prototype.area = function () {
  27953. console.warn('THREE.Triangle: .area() has been renamed to .getArea().');
  27954. return this.getArea();
  27955. };
  27956. Triangle.prototype.barycoordFromPoint = function (point, target) {
  27957. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  27958. return this.getBarycoord(point, target);
  27959. };
  27960. Triangle.prototype.midpoint = function (target) {
  27961. console.warn('THREE.Triangle: .midpoint() has been renamed to .getMidpoint().');
  27962. return this.getMidpoint(target);
  27963. };
  27964. Triangle.prototypenormal = function (target) {
  27965. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  27966. return this.getNormal(target);
  27967. };
  27968. Triangle.prototype.plane = function (target) {
  27969. console.warn('THREE.Triangle: .plane() has been renamed to .getPlane().');
  27970. return this.getPlane(target);
  27971. };
  27972. Triangle.barycoordFromPoint = function (point, a, b, c, target) {
  27973. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  27974. return Triangle.getBarycoord(point, a, b, c, target);
  27975. };
  27976. Triangle.normal = function (a, b, c, target) {
  27977. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  27978. return Triangle.getNormal(a, b, c, target);
  27979. }; //
  27980. Shape.prototype.extractAllPoints = function (divisions) {
  27981. console.warn('THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.');
  27982. return this.extractPoints(divisions);
  27983. };
  27984. Shape.prototype.extrude = function (options) {
  27985. console.warn('THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.');
  27986. return new ExtrudeGeometry(this, options);
  27987. };
  27988. Shape.prototype.makeGeometry = function (options) {
  27989. console.warn('THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.');
  27990. return new ShapeGeometry(this, options);
  27991. }; //
  27992. Vector2.prototype.fromAttribute = function (attribute, index, offset) {
  27993. console.warn('THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().');
  27994. return this.fromBufferAttribute(attribute, index, offset);
  27995. };
  27996. Vector2.prototype.distanceToManhattan = function (v) {
  27997. console.warn('THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  27998. return this.manhattanDistanceTo(v);
  27999. };
  28000. Vector2.prototype.lengthManhattan = function () {
  28001. console.warn('THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().');
  28002. return this.manhattanLength();
  28003. }; //
  28004. Vector3.prototype.setEulerFromRotationMatrix = function () {
  28005. console.error('THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.');
  28006. };
  28007. Vector3.prototype.setEulerFromQuaternion = function () {
  28008. console.error('THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.');
  28009. };
  28010. Vector3.prototype.getPositionFromMatrix = function (m) {
  28011. console.warn('THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().');
  28012. return this.setFromMatrixPosition(m);
  28013. };
  28014. Vector3.prototype.getScaleFromMatrix = function (m) {
  28015. console.warn('THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().');
  28016. return this.setFromMatrixScale(m);
  28017. };
  28018. Vector3.prototype.getColumnFromMatrix = function (index, matrix) {
  28019. console.warn('THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().');
  28020. return this.setFromMatrixColumn(matrix, index);
  28021. };
  28022. Vector3.prototype.applyProjection = function (m) {
  28023. console.warn('THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.');
  28024. return this.applyMatrix4(m);
  28025. };
  28026. Vector3.prototype.fromAttribute = function (attribute, index, offset) {
  28027. console.warn('THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28028. return this.fromBufferAttribute(attribute, index, offset);
  28029. };
  28030. Vector3.prototype.distanceToManhattan = function (v) {
  28031. console.warn('THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  28032. return this.manhattanDistanceTo(v);
  28033. };
  28034. Vector3.prototype.lengthManhattan = function () {
  28035. console.warn('THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().');
  28036. return this.manhattanLength();
  28037. }; //
  28038. Vector4.prototype.fromAttribute = function (attribute, index, offset) {
  28039. console.warn('THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28040. return this.fromBufferAttribute(attribute, index, offset);
  28041. };
  28042. Vector4.prototype.lengthManhattan = function () {
  28043. console.warn('THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().');
  28044. return this.manhattanLength();
  28045. }; //
  28046. Object3D.prototype.getChildByName = function (name) {
  28047. console.warn('THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().');
  28048. return this.getObjectByName(name);
  28049. };
  28050. Object3D.prototype.renderDepth = function () {
  28051. console.warn('THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.');
  28052. };
  28053. Object3D.prototype.translate = function (distance, axis) {
  28054. console.warn('THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.');
  28055. return this.translateOnAxis(axis, distance);
  28056. };
  28057. Object3D.prototype.getWorldRotation = function () {
  28058. console.error('THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.');
  28059. };
  28060. Object3D.prototype.applyMatrix = function (matrix) {
  28061. console.warn('THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().');
  28062. return this.applyMatrix4(matrix);
  28063. };
  28064. Object.defineProperties(Object3D.prototype, {
  28065. eulerOrder: {
  28066. get: function () {
  28067. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  28068. return this.rotation.order;
  28069. },
  28070. set: function (value) {
  28071. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  28072. this.rotation.order = value;
  28073. }
  28074. },
  28075. useQuaternion: {
  28076. get: function () {
  28077. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  28078. },
  28079. set: function () {
  28080. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  28081. }
  28082. }
  28083. });
  28084. Mesh.prototype.setDrawMode = function () {
  28085. console.error('THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  28086. };
  28087. Object.defineProperties(Mesh.prototype, {
  28088. drawMode: {
  28089. get: function () {
  28090. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.');
  28091. return TrianglesDrawMode;
  28092. },
  28093. set: function () {
  28094. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  28095. }
  28096. }
  28097. });
  28098. SkinnedMesh.prototype.initBones = function () {
  28099. console.error('THREE.SkinnedMesh: initBones() has been removed.');
  28100. }; //
  28101. PerspectiveCamera.prototype.setLens = function (focalLength, filmGauge) {
  28102. console.warn('THREE.PerspectiveCamera.setLens is deprecated. ' + 'Use .setFocalLength and .filmGauge for a photographic setup.');
  28103. if (filmGauge !== undefined) this.filmGauge = filmGauge;
  28104. this.setFocalLength(focalLength);
  28105. }; //
  28106. Object.defineProperties(Light.prototype, {
  28107. onlyShadow: {
  28108. set: function () {
  28109. console.warn('THREE.Light: .onlyShadow has been removed.');
  28110. }
  28111. },
  28112. shadowCameraFov: {
  28113. set: function (value) {
  28114. console.warn('THREE.Light: .shadowCameraFov is now .shadow.camera.fov.');
  28115. this.shadow.camera.fov = value;
  28116. }
  28117. },
  28118. shadowCameraLeft: {
  28119. set: function (value) {
  28120. console.warn('THREE.Light: .shadowCameraLeft is now .shadow.camera.left.');
  28121. this.shadow.camera.left = value;
  28122. }
  28123. },
  28124. shadowCameraRight: {
  28125. set: function (value) {
  28126. console.warn('THREE.Light: .shadowCameraRight is now .shadow.camera.right.');
  28127. this.shadow.camera.right = value;
  28128. }
  28129. },
  28130. shadowCameraTop: {
  28131. set: function (value) {
  28132. console.warn('THREE.Light: .shadowCameraTop is now .shadow.camera.top.');
  28133. this.shadow.camera.top = value;
  28134. }
  28135. },
  28136. shadowCameraBottom: {
  28137. set: function (value) {
  28138. console.warn('THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.');
  28139. this.shadow.camera.bottom = value;
  28140. }
  28141. },
  28142. shadowCameraNear: {
  28143. set: function (value) {
  28144. console.warn('THREE.Light: .shadowCameraNear is now .shadow.camera.near.');
  28145. this.shadow.camera.near = value;
  28146. }
  28147. },
  28148. shadowCameraFar: {
  28149. set: function (value) {
  28150. console.warn('THREE.Light: .shadowCameraFar is now .shadow.camera.far.');
  28151. this.shadow.camera.far = value;
  28152. }
  28153. },
  28154. shadowCameraVisible: {
  28155. set: function () {
  28156. console.warn('THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.');
  28157. }
  28158. },
  28159. shadowBias: {
  28160. set: function (value) {
  28161. console.warn('THREE.Light: .shadowBias is now .shadow.bias.');
  28162. this.shadow.bias = value;
  28163. }
  28164. },
  28165. shadowDarkness: {
  28166. set: function () {
  28167. console.warn('THREE.Light: .shadowDarkness has been removed.');
  28168. }
  28169. },
  28170. shadowMapWidth: {
  28171. set: function (value) {
  28172. console.warn('THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.');
  28173. this.shadow.mapSize.width = value;
  28174. }
  28175. },
  28176. shadowMapHeight: {
  28177. set: function (value) {
  28178. console.warn('THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.');
  28179. this.shadow.mapSize.height = value;
  28180. }
  28181. }
  28182. }); //
  28183. Object.defineProperties(BufferAttribute.prototype, {
  28184. length: {
  28185. get: function () {
  28186. console.warn('THREE.BufferAttribute: .length has been deprecated. Use .count instead.');
  28187. return this.array.length;
  28188. }
  28189. },
  28190. dynamic: {
  28191. get: function () {
  28192. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  28193. return this.usage === DynamicDrawUsage;
  28194. },
  28195. set: function ()
  28196. /* value */
  28197. {
  28198. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  28199. this.setUsage(DynamicDrawUsage);
  28200. }
  28201. }
  28202. });
  28203. BufferAttribute.prototype.setDynamic = function (value) {
  28204. console.warn('THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.');
  28205. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  28206. return this;
  28207. };
  28208. BufferAttribute.prototype.copyIndicesArray = function ()
  28209. /* indices */
  28210. {
  28211. console.error('THREE.BufferAttribute: .copyIndicesArray() has been removed.');
  28212. }, BufferAttribute.prototype.setArray = function ()
  28213. /* array */
  28214. {
  28215. console.error('THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  28216. }; //
  28217. BufferGeometry.prototype.addIndex = function (index) {
  28218. console.warn('THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().');
  28219. this.setIndex(index);
  28220. };
  28221. BufferGeometry.prototype.addAttribute = function (name, attribute) {
  28222. console.warn('THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().');
  28223. if (!(attribute && attribute.isBufferAttribute) && !(attribute && attribute.isInterleavedBufferAttribute)) {
  28224. console.warn('THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).');
  28225. return this.setAttribute(name, new BufferAttribute(arguments[1], arguments[2]));
  28226. }
  28227. if (name === 'index') {
  28228. console.warn('THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.');
  28229. this.setIndex(attribute);
  28230. return this;
  28231. }
  28232. return this.setAttribute(name, attribute);
  28233. };
  28234. BufferGeometry.prototype.addDrawCall = function (start, count, indexOffset) {
  28235. if (indexOffset !== undefined) {
  28236. console.warn('THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.');
  28237. }
  28238. console.warn('THREE.BufferGeometry: .addDrawCall() is now .addGroup().');
  28239. this.addGroup(start, count);
  28240. };
  28241. BufferGeometry.prototype.clearDrawCalls = function () {
  28242. console.warn('THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().');
  28243. this.clearGroups();
  28244. };
  28245. BufferGeometry.prototype.computeOffsets = function () {
  28246. console.warn('THREE.BufferGeometry: .computeOffsets() has been removed.');
  28247. };
  28248. BufferGeometry.prototype.removeAttribute = function (name) {
  28249. console.warn('THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().');
  28250. return this.deleteAttribute(name);
  28251. };
  28252. BufferGeometry.prototype.applyMatrix = function (matrix) {
  28253. console.warn('THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().');
  28254. return this.applyMatrix4(matrix);
  28255. };
  28256. Object.defineProperties(BufferGeometry.prototype, {
  28257. drawcalls: {
  28258. get: function () {
  28259. console.error('THREE.BufferGeometry: .drawcalls has been renamed to .groups.');
  28260. return this.groups;
  28261. }
  28262. },
  28263. offsets: {
  28264. get: function () {
  28265. console.warn('THREE.BufferGeometry: .offsets has been renamed to .groups.');
  28266. return this.groups;
  28267. }
  28268. }
  28269. });
  28270. InterleavedBuffer.prototype.setDynamic = function (value) {
  28271. console.warn('THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.');
  28272. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  28273. return this;
  28274. };
  28275. InterleavedBuffer.prototype.setArray = function ()
  28276. /* array */
  28277. {
  28278. console.error('THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  28279. }; //
  28280. ExtrudeGeometry.prototype.getArrays = function () {
  28281. console.error('THREE.ExtrudeGeometry: .getArrays() has been removed.');
  28282. };
  28283. ExtrudeGeometry.prototype.addShapeList = function () {
  28284. console.error('THREE.ExtrudeGeometry: .addShapeList() has been removed.');
  28285. };
  28286. ExtrudeGeometry.prototype.addShape = function () {
  28287. console.error('THREE.ExtrudeGeometry: .addShape() has been removed.');
  28288. }; //
  28289. Scene.prototype.dispose = function () {
  28290. console.error('THREE.Scene: .dispose() has been removed.');
  28291. }; //
  28292. Uniform.prototype.onUpdate = function () {
  28293. console.warn('THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.');
  28294. return this;
  28295. }; //
  28296. Object.defineProperties(Material.prototype, {
  28297. wrapAround: {
  28298. get: function () {
  28299. console.warn('THREE.Material: .wrapAround has been removed.');
  28300. },
  28301. set: function () {
  28302. console.warn('THREE.Material: .wrapAround has been removed.');
  28303. }
  28304. },
  28305. overdraw: {
  28306. get: function () {
  28307. console.warn('THREE.Material: .overdraw has been removed.');
  28308. },
  28309. set: function () {
  28310. console.warn('THREE.Material: .overdraw has been removed.');
  28311. }
  28312. },
  28313. wrapRGB: {
  28314. get: function () {
  28315. console.warn('THREE.Material: .wrapRGB has been removed.');
  28316. return new Color();
  28317. }
  28318. },
  28319. shading: {
  28320. get: function () {
  28321. console.error('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  28322. },
  28323. set: function (value) {
  28324. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  28325. this.flatShading = value === FlatShading;
  28326. }
  28327. },
  28328. stencilMask: {
  28329. get: function () {
  28330. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  28331. return this.stencilFuncMask;
  28332. },
  28333. set: function (value) {
  28334. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  28335. this.stencilFuncMask = value;
  28336. }
  28337. }
  28338. });
  28339. Object.defineProperties(ShaderMaterial.prototype, {
  28340. derivatives: {
  28341. get: function () {
  28342. console.warn('THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  28343. return this.extensions.derivatives;
  28344. },
  28345. set: function (value) {
  28346. console.warn('THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  28347. this.extensions.derivatives = value;
  28348. }
  28349. }
  28350. }); //
  28351. WebGLRenderer.prototype.clearTarget = function (renderTarget, color, depth, stencil) {
  28352. console.warn('THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.');
  28353. this.setRenderTarget(renderTarget);
  28354. this.clear(color, depth, stencil);
  28355. };
  28356. WebGLRenderer.prototype.animate = function (callback) {
  28357. console.warn('THREE.WebGLRenderer: .animate() is now .setAnimationLoop().');
  28358. this.setAnimationLoop(callback);
  28359. };
  28360. WebGLRenderer.prototype.getCurrentRenderTarget = function () {
  28361. console.warn('THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().');
  28362. return this.getRenderTarget();
  28363. };
  28364. WebGLRenderer.prototype.getMaxAnisotropy = function () {
  28365. console.warn('THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().');
  28366. return this.capabilities.getMaxAnisotropy();
  28367. };
  28368. WebGLRenderer.prototype.getPrecision = function () {
  28369. console.warn('THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.');
  28370. return this.capabilities.precision;
  28371. };
  28372. WebGLRenderer.prototype.resetGLState = function () {
  28373. console.warn('THREE.WebGLRenderer: .resetGLState() is now .state.reset().');
  28374. return this.state.reset();
  28375. };
  28376. WebGLRenderer.prototype.supportsFloatTextures = function () {
  28377. console.warn('THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).');
  28378. return this.extensions.get('OES_texture_float');
  28379. };
  28380. WebGLRenderer.prototype.supportsHalfFloatTextures = function () {
  28381. console.warn('THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).');
  28382. return this.extensions.get('OES_texture_half_float');
  28383. };
  28384. WebGLRenderer.prototype.supportsStandardDerivatives = function () {
  28385. console.warn('THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).');
  28386. return this.extensions.get('OES_standard_derivatives');
  28387. };
  28388. WebGLRenderer.prototype.supportsCompressedTextureS3TC = function () {
  28389. console.warn('THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).');
  28390. return this.extensions.get('WEBGL_compressed_texture_s3tc');
  28391. };
  28392. WebGLRenderer.prototype.supportsCompressedTexturePVRTC = function () {
  28393. console.warn('THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).');
  28394. return this.extensions.get('WEBGL_compressed_texture_pvrtc');
  28395. };
  28396. WebGLRenderer.prototype.supportsBlendMinMax = function () {
  28397. console.warn('THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).');
  28398. return this.extensions.get('EXT_blend_minmax');
  28399. };
  28400. WebGLRenderer.prototype.supportsVertexTextures = function () {
  28401. console.warn('THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.');
  28402. return this.capabilities.vertexTextures;
  28403. };
  28404. WebGLRenderer.prototype.supportsInstancedArrays = function () {
  28405. console.warn('THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).');
  28406. return this.extensions.get('ANGLE_instanced_arrays');
  28407. };
  28408. WebGLRenderer.prototype.enableScissorTest = function (boolean) {
  28409. console.warn('THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().');
  28410. this.setScissorTest(boolean);
  28411. };
  28412. WebGLRenderer.prototype.initMaterial = function () {
  28413. console.warn('THREE.WebGLRenderer: .initMaterial() has been removed.');
  28414. };
  28415. WebGLRenderer.prototype.addPrePlugin = function () {
  28416. console.warn('THREE.WebGLRenderer: .addPrePlugin() has been removed.');
  28417. };
  28418. WebGLRenderer.prototype.addPostPlugin = function () {
  28419. console.warn('THREE.WebGLRenderer: .addPostPlugin() has been removed.');
  28420. };
  28421. WebGLRenderer.prototype.updateShadowMap = function () {
  28422. console.warn('THREE.WebGLRenderer: .updateShadowMap() has been removed.');
  28423. };
  28424. WebGLRenderer.prototype.setFaceCulling = function () {
  28425. console.warn('THREE.WebGLRenderer: .setFaceCulling() has been removed.');
  28426. };
  28427. WebGLRenderer.prototype.allocTextureUnit = function () {
  28428. console.warn('THREE.WebGLRenderer: .allocTextureUnit() has been removed.');
  28429. };
  28430. WebGLRenderer.prototype.setTexture = function () {
  28431. console.warn('THREE.WebGLRenderer: .setTexture() has been removed.');
  28432. };
  28433. WebGLRenderer.prototype.setTexture2D = function () {
  28434. console.warn('THREE.WebGLRenderer: .setTexture2D() has been removed.');
  28435. };
  28436. WebGLRenderer.prototype.setTextureCube = function () {
  28437. console.warn('THREE.WebGLRenderer: .setTextureCube() has been removed.');
  28438. };
  28439. WebGLRenderer.prototype.getActiveMipMapLevel = function () {
  28440. console.warn('THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().');
  28441. return this.getActiveMipmapLevel();
  28442. };
  28443. Object.defineProperties(WebGLRenderer.prototype, {
  28444. shadowMapEnabled: {
  28445. get: function () {
  28446. return this.shadowMap.enabled;
  28447. },
  28448. set: function (value) {
  28449. console.warn('THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.');
  28450. this.shadowMap.enabled = value;
  28451. }
  28452. },
  28453. shadowMapType: {
  28454. get: function () {
  28455. return this.shadowMap.type;
  28456. },
  28457. set: function (value) {
  28458. console.warn('THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.');
  28459. this.shadowMap.type = value;
  28460. }
  28461. },
  28462. shadowMapCullFace: {
  28463. get: function () {
  28464. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  28465. return undefined;
  28466. },
  28467. set: function ()
  28468. /* value */
  28469. {
  28470. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  28471. }
  28472. },
  28473. context: {
  28474. get: function () {
  28475. console.warn('THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.');
  28476. return this.getContext();
  28477. }
  28478. },
  28479. vr: {
  28480. get: function () {
  28481. console.warn('THREE.WebGLRenderer: .vr has been renamed to .xr');
  28482. return this.xr;
  28483. }
  28484. },
  28485. gammaInput: {
  28486. get: function () {
  28487. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  28488. return false;
  28489. },
  28490. set: function () {
  28491. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  28492. }
  28493. },
  28494. gammaOutput: {
  28495. get: function () {
  28496. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  28497. return false;
  28498. },
  28499. set: function (value) {
  28500. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  28501. this.outputEncoding = value === true ? sRGBEncoding : LinearEncoding;
  28502. }
  28503. },
  28504. toneMappingWhitePoint: {
  28505. get: function () {
  28506. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  28507. return 1.0;
  28508. },
  28509. set: function () {
  28510. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  28511. }
  28512. }
  28513. });
  28514. Object.defineProperties(WebGLShadowMap.prototype, {
  28515. cullFace: {
  28516. get: function () {
  28517. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  28518. return undefined;
  28519. },
  28520. set: function ()
  28521. /* cullFace */
  28522. {
  28523. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  28524. }
  28525. },
  28526. renderReverseSided: {
  28527. get: function () {
  28528. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  28529. return undefined;
  28530. },
  28531. set: function () {
  28532. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  28533. }
  28534. },
  28535. renderSingleSided: {
  28536. get: function () {
  28537. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  28538. return undefined;
  28539. },
  28540. set: function () {
  28541. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  28542. }
  28543. }
  28544. });
  28545. function WebGLRenderTargetCube(width, height, options) {
  28546. console.warn('THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).');
  28547. return new WebGLCubeRenderTarget(width, options);
  28548. } //
  28549. Object.defineProperties(WebGLRenderTarget.prototype, {
  28550. wrapS: {
  28551. get: function () {
  28552. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  28553. return this.texture.wrapS;
  28554. },
  28555. set: function (value) {
  28556. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  28557. this.texture.wrapS = value;
  28558. }
  28559. },
  28560. wrapT: {
  28561. get: function () {
  28562. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  28563. return this.texture.wrapT;
  28564. },
  28565. set: function (value) {
  28566. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  28567. this.texture.wrapT = value;
  28568. }
  28569. },
  28570. magFilter: {
  28571. get: function () {
  28572. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  28573. return this.texture.magFilter;
  28574. },
  28575. set: function (value) {
  28576. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  28577. this.texture.magFilter = value;
  28578. }
  28579. },
  28580. minFilter: {
  28581. get: function () {
  28582. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  28583. return this.texture.minFilter;
  28584. },
  28585. set: function (value) {
  28586. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  28587. this.texture.minFilter = value;
  28588. }
  28589. },
  28590. anisotropy: {
  28591. get: function () {
  28592. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  28593. return this.texture.anisotropy;
  28594. },
  28595. set: function (value) {
  28596. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  28597. this.texture.anisotropy = value;
  28598. }
  28599. },
  28600. offset: {
  28601. get: function () {
  28602. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  28603. return this.texture.offset;
  28604. },
  28605. set: function (value) {
  28606. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  28607. this.texture.offset = value;
  28608. }
  28609. },
  28610. repeat: {
  28611. get: function () {
  28612. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  28613. return this.texture.repeat;
  28614. },
  28615. set: function (value) {
  28616. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  28617. this.texture.repeat = value;
  28618. }
  28619. },
  28620. format: {
  28621. get: function () {
  28622. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  28623. return this.texture.format;
  28624. },
  28625. set: function (value) {
  28626. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  28627. this.texture.format = value;
  28628. }
  28629. },
  28630. type: {
  28631. get: function () {
  28632. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  28633. return this.texture.type;
  28634. },
  28635. set: function (value) {
  28636. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  28637. this.texture.type = value;
  28638. }
  28639. },
  28640. generateMipmaps: {
  28641. get: function () {
  28642. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  28643. return this.texture.generateMipmaps;
  28644. },
  28645. set: function (value) {
  28646. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  28647. this.texture.generateMipmaps = value;
  28648. }
  28649. }
  28650. }); //
  28651. Audio.prototype.load = function (file) {
  28652. console.warn('THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.');
  28653. const scope = this;
  28654. const audioLoader = new AudioLoader();
  28655. audioLoader.load(file, function (buffer) {
  28656. scope.setBuffer(buffer);
  28657. });
  28658. return this;
  28659. };
  28660. AudioAnalyser.prototype.getData = function () {
  28661. console.warn('THREE.AudioAnalyser: .getData() is now .getFrequencyData().');
  28662. return this.getFrequencyData();
  28663. }; //
  28664. CubeCamera.prototype.updateCubeMap = function (renderer, scene) {
  28665. console.warn('THREE.CubeCamera: .updateCubeMap() is now .update().');
  28666. return this.update(renderer, scene);
  28667. };
  28668. CubeCamera.prototype.clear = function (renderer, color, depth, stencil) {
  28669. console.warn('THREE.CubeCamera: .clear() is now .renderTarget.clear().');
  28670. return this.renderTarget.clear(renderer, color, depth, stencil);
  28671. };
  28672. ImageUtils.crossOrigin = undefined;
  28673. ImageUtils.loadTexture = function (url, mapping, onLoad, onError) {
  28674. console.warn('THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.');
  28675. const loader = new TextureLoader();
  28676. loader.setCrossOrigin(this.crossOrigin);
  28677. const texture = loader.load(url, onLoad, undefined, onError);
  28678. if (mapping) texture.mapping = mapping;
  28679. return texture;
  28680. };
  28681. ImageUtils.loadTextureCube = function (urls, mapping, onLoad, onError) {
  28682. console.warn('THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.');
  28683. const loader = new CubeTextureLoader();
  28684. loader.setCrossOrigin(this.crossOrigin);
  28685. const texture = loader.load(urls, onLoad, undefined, onError);
  28686. if (mapping) texture.mapping = mapping;
  28687. return texture;
  28688. };
  28689. ImageUtils.loadCompressedTexture = function () {
  28690. console.error('THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.');
  28691. };
  28692. ImageUtils.loadCompressedTextureCube = function () {
  28693. console.error('THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.');
  28694. }; //
  28695. function CanvasRenderer() {
  28696. console.error('THREE.CanvasRenderer has been removed');
  28697. } //
  28698. function JSONLoader() {
  28699. console.error('THREE.JSONLoader has been removed.');
  28700. } //
  28701. const SceneUtils = {
  28702. createMultiMaterialObject: function ()
  28703. /* geometry, materials */
  28704. {
  28705. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  28706. },
  28707. detach: function ()
  28708. /* child, parent, scene */
  28709. {
  28710. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  28711. },
  28712. attach: function ()
  28713. /* child, scene, parent */
  28714. {
  28715. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  28716. }
  28717. }; //
  28718. function LensFlare() {
  28719. console.error('THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js');
  28720. }
  28721. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  28722. /* eslint-disable no-undef */
  28723. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
  28724. detail: {
  28725. revision: REVISION
  28726. }
  28727. }));
  28728. /* eslint-enable no-undef */
  28729. }
  28730. if (typeof window !== 'undefined') {
  28731. if (window.__THREE__) {
  28732. console.warn('WARNING: Multiple instances of Three.js being imported.');
  28733. } else {
  28734. window.__THREE__ = REVISION;
  28735. }
  28736. }
  28737. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  28738. exports.AddEquation = AddEquation;
  28739. exports.AddOperation = AddOperation;
  28740. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  28741. exports.AdditiveBlending = AdditiveBlending;
  28742. exports.AlphaFormat = AlphaFormat;
  28743. exports.AlwaysDepth = AlwaysDepth;
  28744. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  28745. exports.AmbientLight = AmbientLight;
  28746. exports.AmbientLightProbe = AmbientLightProbe;
  28747. exports.AnimationClip = AnimationClip;
  28748. exports.AnimationLoader = AnimationLoader;
  28749. exports.AnimationMixer = AnimationMixer;
  28750. exports.AnimationObjectGroup = AnimationObjectGroup;
  28751. exports.AnimationUtils = AnimationUtils;
  28752. exports.ArcCurve = ArcCurve;
  28753. exports.ArrayCamera = ArrayCamera;
  28754. exports.ArrowHelper = ArrowHelper;
  28755. exports.Audio = Audio;
  28756. exports.AudioAnalyser = AudioAnalyser;
  28757. exports.AudioContext = AudioContext;
  28758. exports.AudioListener = AudioListener;
  28759. exports.AudioLoader = AudioLoader;
  28760. exports.AxesHelper = AxesHelper;
  28761. exports.AxisHelper = AxisHelper;
  28762. exports.BackSide = BackSide;
  28763. exports.BasicDepthPacking = BasicDepthPacking;
  28764. exports.BasicShadowMap = BasicShadowMap;
  28765. exports.BinaryTextureLoader = BinaryTextureLoader;
  28766. exports.Bone = Bone;
  28767. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  28768. exports.BoundingBoxHelper = BoundingBoxHelper;
  28769. exports.Box2 = Box2;
  28770. exports.Box3 = Box3;
  28771. exports.Box3Helper = Box3Helper;
  28772. exports.BoxBufferGeometry = BoxGeometry;
  28773. exports.BoxGeometry = BoxGeometry;
  28774. exports.BoxHelper = BoxHelper;
  28775. exports.BufferAttribute = BufferAttribute;
  28776. exports.BufferGeometry = BufferGeometry;
  28777. exports.BufferGeometryLoader = BufferGeometryLoader;
  28778. exports.ByteType = ByteType;
  28779. exports.Cache = Cache;
  28780. exports.Camera = Camera;
  28781. exports.CameraHelper = CameraHelper;
  28782. exports.CanvasRenderer = CanvasRenderer;
  28783. exports.CanvasTexture = CanvasTexture;
  28784. exports.CatmullRomCurve3 = CatmullRomCurve3;
  28785. exports.CineonToneMapping = CineonToneMapping;
  28786. exports.CircleBufferGeometry = CircleGeometry;
  28787. exports.CircleGeometry = CircleGeometry;
  28788. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  28789. exports.Clock = Clock;
  28790. exports.Color = Color;
  28791. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  28792. exports.CompressedTexture = CompressedTexture;
  28793. exports.CompressedTextureLoader = CompressedTextureLoader;
  28794. exports.ConeBufferGeometry = ConeGeometry;
  28795. exports.ConeGeometry = ConeGeometry;
  28796. exports.CubeCamera = CubeCamera;
  28797. exports.CubeReflectionMapping = CubeReflectionMapping;
  28798. exports.CubeRefractionMapping = CubeRefractionMapping;
  28799. exports.CubeTexture = CubeTexture;
  28800. exports.CubeTextureLoader = CubeTextureLoader;
  28801. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  28802. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  28803. exports.CubicBezierCurve = CubicBezierCurve;
  28804. exports.CubicBezierCurve3 = CubicBezierCurve3;
  28805. exports.CubicInterpolant = CubicInterpolant;
  28806. exports.CullFaceBack = CullFaceBack;
  28807. exports.CullFaceFront = CullFaceFront;
  28808. exports.CullFaceFrontBack = CullFaceFrontBack;
  28809. exports.CullFaceNone = CullFaceNone;
  28810. exports.Curve = Curve;
  28811. exports.CurvePath = CurvePath;
  28812. exports.CustomBlending = CustomBlending;
  28813. exports.CustomToneMapping = CustomToneMapping;
  28814. exports.CylinderBufferGeometry = CylinderGeometry;
  28815. exports.CylinderGeometry = CylinderGeometry;
  28816. exports.Cylindrical = Cylindrical;
  28817. exports.DataTexture = DataTexture;
  28818. exports.DataTexture2DArray = DataTexture2DArray;
  28819. exports.DataTexture3D = DataTexture3D;
  28820. exports.DataTextureLoader = DataTextureLoader;
  28821. exports.DataUtils = DataUtils;
  28822. exports.DecrementStencilOp = DecrementStencilOp;
  28823. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  28824. exports.DefaultLoadingManager = DefaultLoadingManager;
  28825. exports.DepthFormat = DepthFormat;
  28826. exports.DepthStencilFormat = DepthStencilFormat;
  28827. exports.DepthTexture = DepthTexture;
  28828. exports.DirectionalLight = DirectionalLight;
  28829. exports.DirectionalLightHelper = DirectionalLightHelper;
  28830. exports.DiscreteInterpolant = DiscreteInterpolant;
  28831. exports.DodecahedronBufferGeometry = DodecahedronGeometry;
  28832. exports.DodecahedronGeometry = DodecahedronGeometry;
  28833. exports.DoubleSide = DoubleSide;
  28834. exports.DstAlphaFactor = DstAlphaFactor;
  28835. exports.DstColorFactor = DstColorFactor;
  28836. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  28837. exports.DynamicCopyUsage = DynamicCopyUsage;
  28838. exports.DynamicDrawUsage = DynamicDrawUsage;
  28839. exports.DynamicReadUsage = DynamicReadUsage;
  28840. exports.EdgesGeometry = EdgesGeometry;
  28841. exports.EdgesHelper = EdgesHelper;
  28842. exports.EllipseCurve = EllipseCurve;
  28843. exports.EqualDepth = EqualDepth;
  28844. exports.EqualStencilFunc = EqualStencilFunc;
  28845. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  28846. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  28847. exports.Euler = Euler;
  28848. exports.EventDispatcher = EventDispatcher;
  28849. exports.ExtrudeBufferGeometry = ExtrudeGeometry;
  28850. exports.ExtrudeGeometry = ExtrudeGeometry;
  28851. exports.FaceColors = FaceColors;
  28852. exports.FileLoader = FileLoader;
  28853. exports.FlatShading = FlatShading;
  28854. exports.Float16BufferAttribute = Float16BufferAttribute;
  28855. exports.Float32Attribute = Float32Attribute;
  28856. exports.Float32BufferAttribute = Float32BufferAttribute;
  28857. exports.Float64Attribute = Float64Attribute;
  28858. exports.Float64BufferAttribute = Float64BufferAttribute;
  28859. exports.FloatType = FloatType;
  28860. exports.Fog = Fog;
  28861. exports.FogExp2 = FogExp2;
  28862. exports.Font = Font;
  28863. exports.FontLoader = FontLoader;
  28864. exports.FrontSide = FrontSide;
  28865. exports.Frustum = Frustum;
  28866. exports.GLBufferAttribute = GLBufferAttribute;
  28867. exports.GLSL1 = GLSL1;
  28868. exports.GLSL3 = GLSL3;
  28869. exports.GammaEncoding = GammaEncoding;
  28870. exports.GreaterDepth = GreaterDepth;
  28871. exports.GreaterEqualDepth = GreaterEqualDepth;
  28872. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  28873. exports.GreaterStencilFunc = GreaterStencilFunc;
  28874. exports.GridHelper = GridHelper;
  28875. exports.Group = Group;
  28876. exports.HalfFloatType = HalfFloatType;
  28877. exports.HemisphereLight = HemisphereLight;
  28878. exports.HemisphereLightHelper = HemisphereLightHelper;
  28879. exports.HemisphereLightProbe = HemisphereLightProbe;
  28880. exports.IcosahedronBufferGeometry = IcosahedronGeometry;
  28881. exports.IcosahedronGeometry = IcosahedronGeometry;
  28882. exports.ImageBitmapLoader = ImageBitmapLoader;
  28883. exports.ImageLoader = ImageLoader;
  28884. exports.ImageUtils = ImageUtils;
  28885. exports.ImmediateRenderObject = ImmediateRenderObject;
  28886. exports.IncrementStencilOp = IncrementStencilOp;
  28887. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  28888. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  28889. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  28890. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  28891. exports.InstancedMesh = InstancedMesh;
  28892. exports.Int16Attribute = Int16Attribute;
  28893. exports.Int16BufferAttribute = Int16BufferAttribute;
  28894. exports.Int32Attribute = Int32Attribute;
  28895. exports.Int32BufferAttribute = Int32BufferAttribute;
  28896. exports.Int8Attribute = Int8Attribute;
  28897. exports.Int8BufferAttribute = Int8BufferAttribute;
  28898. exports.IntType = IntType;
  28899. exports.InterleavedBuffer = InterleavedBuffer;
  28900. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  28901. exports.Interpolant = Interpolant;
  28902. exports.InterpolateDiscrete = InterpolateDiscrete;
  28903. exports.InterpolateLinear = InterpolateLinear;
  28904. exports.InterpolateSmooth = InterpolateSmooth;
  28905. exports.InvertStencilOp = InvertStencilOp;
  28906. exports.JSONLoader = JSONLoader;
  28907. exports.KeepStencilOp = KeepStencilOp;
  28908. exports.KeyframeTrack = KeyframeTrack;
  28909. exports.LOD = LOD;
  28910. exports.LatheBufferGeometry = LatheGeometry;
  28911. exports.LatheGeometry = LatheGeometry;
  28912. exports.Layers = Layers;
  28913. exports.LensFlare = LensFlare;
  28914. exports.LessDepth = LessDepth;
  28915. exports.LessEqualDepth = LessEqualDepth;
  28916. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  28917. exports.LessStencilFunc = LessStencilFunc;
  28918. exports.Light = Light;
  28919. exports.LightProbe = LightProbe;
  28920. exports.Line = Line;
  28921. exports.Line3 = Line3;
  28922. exports.LineBasicMaterial = LineBasicMaterial;
  28923. exports.LineCurve = LineCurve;
  28924. exports.LineCurve3 = LineCurve3;
  28925. exports.LineDashedMaterial = LineDashedMaterial;
  28926. exports.LineLoop = LineLoop;
  28927. exports.LinePieces = LinePieces;
  28928. exports.LineSegments = LineSegments;
  28929. exports.LineStrip = LineStrip;
  28930. exports.LinearEncoding = LinearEncoding;
  28931. exports.LinearFilter = LinearFilter;
  28932. exports.LinearInterpolant = LinearInterpolant;
  28933. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  28934. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  28935. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  28936. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  28937. exports.LinearToneMapping = LinearToneMapping;
  28938. exports.Loader = Loader;
  28939. exports.LoaderUtils = LoaderUtils;
  28940. exports.LoadingManager = LoadingManager;
  28941. exports.LogLuvEncoding = LogLuvEncoding;
  28942. exports.LoopOnce = LoopOnce;
  28943. exports.LoopPingPong = LoopPingPong;
  28944. exports.LoopRepeat = LoopRepeat;
  28945. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  28946. exports.LuminanceFormat = LuminanceFormat;
  28947. exports.MOUSE = MOUSE;
  28948. exports.Material = Material;
  28949. exports.MaterialLoader = MaterialLoader;
  28950. exports.Math = MathUtils;
  28951. exports.MathUtils = MathUtils;
  28952. exports.Matrix3 = Matrix3;
  28953. exports.Matrix4 = Matrix4;
  28954. exports.MaxEquation = MaxEquation;
  28955. exports.Mesh = Mesh;
  28956. exports.MeshBasicMaterial = MeshBasicMaterial;
  28957. exports.MeshDepthMaterial = MeshDepthMaterial;
  28958. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  28959. exports.MeshFaceMaterial = MeshFaceMaterial;
  28960. exports.MeshLambertMaterial = MeshLambertMaterial;
  28961. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  28962. exports.MeshNormalMaterial = MeshNormalMaterial;
  28963. exports.MeshPhongMaterial = MeshPhongMaterial;
  28964. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  28965. exports.MeshStandardMaterial = MeshStandardMaterial;
  28966. exports.MeshToonMaterial = MeshToonMaterial;
  28967. exports.MinEquation = MinEquation;
  28968. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  28969. exports.MixOperation = MixOperation;
  28970. exports.MultiMaterial = MultiMaterial;
  28971. exports.MultiplyBlending = MultiplyBlending;
  28972. exports.MultiplyOperation = MultiplyOperation;
  28973. exports.NearestFilter = NearestFilter;
  28974. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  28975. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  28976. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  28977. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  28978. exports.NeverDepth = NeverDepth;
  28979. exports.NeverStencilFunc = NeverStencilFunc;
  28980. exports.NoBlending = NoBlending;
  28981. exports.NoColors = NoColors;
  28982. exports.NoToneMapping = NoToneMapping;
  28983. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  28984. exports.NormalBlending = NormalBlending;
  28985. exports.NotEqualDepth = NotEqualDepth;
  28986. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  28987. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  28988. exports.Object3D = Object3D;
  28989. exports.ObjectLoader = ObjectLoader;
  28990. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  28991. exports.OctahedronBufferGeometry = OctahedronGeometry;
  28992. exports.OctahedronGeometry = OctahedronGeometry;
  28993. exports.OneFactor = OneFactor;
  28994. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  28995. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  28996. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  28997. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  28998. exports.OrthographicCamera = OrthographicCamera;
  28999. exports.PCFShadowMap = PCFShadowMap;
  29000. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  29001. exports.PMREMGenerator = PMREMGenerator;
  29002. exports.ParametricBufferGeometry = ParametricGeometry;
  29003. exports.ParametricGeometry = ParametricGeometry;
  29004. exports.Particle = Particle;
  29005. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  29006. exports.ParticleSystem = ParticleSystem;
  29007. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  29008. exports.Path = Path;
  29009. exports.PerspectiveCamera = PerspectiveCamera;
  29010. exports.Plane = Plane;
  29011. exports.PlaneBufferGeometry = PlaneGeometry;
  29012. exports.PlaneGeometry = PlaneGeometry;
  29013. exports.PlaneHelper = PlaneHelper;
  29014. exports.PointCloud = PointCloud;
  29015. exports.PointCloudMaterial = PointCloudMaterial;
  29016. exports.PointLight = PointLight;
  29017. exports.PointLightHelper = PointLightHelper;
  29018. exports.Points = Points;
  29019. exports.PointsMaterial = PointsMaterial;
  29020. exports.PolarGridHelper = PolarGridHelper;
  29021. exports.PolyhedronBufferGeometry = PolyhedronGeometry;
  29022. exports.PolyhedronGeometry = PolyhedronGeometry;
  29023. exports.PositionalAudio = PositionalAudio;
  29024. exports.PropertyBinding = PropertyBinding;
  29025. exports.PropertyMixer = PropertyMixer;
  29026. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  29027. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  29028. exports.Quaternion = Quaternion;
  29029. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  29030. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  29031. exports.REVISION = REVISION;
  29032. exports.RGBADepthPacking = RGBADepthPacking;
  29033. exports.RGBAFormat = RGBAFormat;
  29034. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  29035. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  29036. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  29037. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  29038. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  29039. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  29040. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  29041. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  29042. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  29043. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  29044. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  29045. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  29046. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  29047. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  29048. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  29049. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  29050. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  29051. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  29052. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  29053. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  29054. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  29055. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  29056. exports.RGBDEncoding = RGBDEncoding;
  29057. exports.RGBEEncoding = RGBEEncoding;
  29058. exports.RGBEFormat = RGBEFormat;
  29059. exports.RGBFormat = RGBFormat;
  29060. exports.RGBIntegerFormat = RGBIntegerFormat;
  29061. exports.RGBM16Encoding = RGBM16Encoding;
  29062. exports.RGBM7Encoding = RGBM7Encoding;
  29063. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  29064. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  29065. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  29066. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  29067. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  29068. exports.RGFormat = RGFormat;
  29069. exports.RGIntegerFormat = RGIntegerFormat;
  29070. exports.RawShaderMaterial = RawShaderMaterial;
  29071. exports.Ray = Ray;
  29072. exports.Raycaster = Raycaster;
  29073. exports.RectAreaLight = RectAreaLight;
  29074. exports.RedFormat = RedFormat;
  29075. exports.RedIntegerFormat = RedIntegerFormat;
  29076. exports.ReinhardToneMapping = ReinhardToneMapping;
  29077. exports.RepeatWrapping = RepeatWrapping;
  29078. exports.ReplaceStencilOp = ReplaceStencilOp;
  29079. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  29080. exports.RingBufferGeometry = RingGeometry;
  29081. exports.RingGeometry = RingGeometry;
  29082. exports.SRGB8_ALPHA8_ASTC_10x10_Format = SRGB8_ALPHA8_ASTC_10x10_Format;
  29083. exports.SRGB8_ALPHA8_ASTC_10x5_Format = SRGB8_ALPHA8_ASTC_10x5_Format;
  29084. exports.SRGB8_ALPHA8_ASTC_10x6_Format = SRGB8_ALPHA8_ASTC_10x6_Format;
  29085. exports.SRGB8_ALPHA8_ASTC_10x8_Format = SRGB8_ALPHA8_ASTC_10x8_Format;
  29086. exports.SRGB8_ALPHA8_ASTC_12x10_Format = SRGB8_ALPHA8_ASTC_12x10_Format;
  29087. exports.SRGB8_ALPHA8_ASTC_12x12_Format = SRGB8_ALPHA8_ASTC_12x12_Format;
  29088. exports.SRGB8_ALPHA8_ASTC_4x4_Format = SRGB8_ALPHA8_ASTC_4x4_Format;
  29089. exports.SRGB8_ALPHA8_ASTC_5x4_Format = SRGB8_ALPHA8_ASTC_5x4_Format;
  29090. exports.SRGB8_ALPHA8_ASTC_5x5_Format = SRGB8_ALPHA8_ASTC_5x5_Format;
  29091. exports.SRGB8_ALPHA8_ASTC_6x5_Format = SRGB8_ALPHA8_ASTC_6x5_Format;
  29092. exports.SRGB8_ALPHA8_ASTC_6x6_Format = SRGB8_ALPHA8_ASTC_6x6_Format;
  29093. exports.SRGB8_ALPHA8_ASTC_8x5_Format = SRGB8_ALPHA8_ASTC_8x5_Format;
  29094. exports.SRGB8_ALPHA8_ASTC_8x6_Format = SRGB8_ALPHA8_ASTC_8x6_Format;
  29095. exports.SRGB8_ALPHA8_ASTC_8x8_Format = SRGB8_ALPHA8_ASTC_8x8_Format;
  29096. exports.Scene = Scene;
  29097. exports.SceneUtils = SceneUtils;
  29098. exports.ShaderChunk = ShaderChunk;
  29099. exports.ShaderLib = ShaderLib;
  29100. exports.ShaderMaterial = ShaderMaterial;
  29101. exports.ShadowMaterial = ShadowMaterial;
  29102. exports.Shape = Shape;
  29103. exports.ShapeBufferGeometry = ShapeGeometry;
  29104. exports.ShapeGeometry = ShapeGeometry;
  29105. exports.ShapePath = ShapePath;
  29106. exports.ShapeUtils = ShapeUtils;
  29107. exports.ShortType = ShortType;
  29108. exports.Skeleton = Skeleton;
  29109. exports.SkeletonHelper = SkeletonHelper;
  29110. exports.SkinnedMesh = SkinnedMesh;
  29111. exports.SmoothShading = SmoothShading;
  29112. exports.Sphere = Sphere;
  29113. exports.SphereBufferGeometry = SphereGeometry;
  29114. exports.SphereGeometry = SphereGeometry;
  29115. exports.Spherical = Spherical;
  29116. exports.SphericalHarmonics3 = SphericalHarmonics3;
  29117. exports.SplineCurve = SplineCurve;
  29118. exports.SpotLight = SpotLight;
  29119. exports.SpotLightHelper = SpotLightHelper;
  29120. exports.Sprite = Sprite;
  29121. exports.SpriteMaterial = SpriteMaterial;
  29122. exports.SrcAlphaFactor = SrcAlphaFactor;
  29123. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  29124. exports.SrcColorFactor = SrcColorFactor;
  29125. exports.StaticCopyUsage = StaticCopyUsage;
  29126. exports.StaticDrawUsage = StaticDrawUsage;
  29127. exports.StaticReadUsage = StaticReadUsage;
  29128. exports.StereoCamera = StereoCamera;
  29129. exports.StreamCopyUsage = StreamCopyUsage;
  29130. exports.StreamDrawUsage = StreamDrawUsage;
  29131. exports.StreamReadUsage = StreamReadUsage;
  29132. exports.StringKeyframeTrack = StringKeyframeTrack;
  29133. exports.SubtractEquation = SubtractEquation;
  29134. exports.SubtractiveBlending = SubtractiveBlending;
  29135. exports.TOUCH = TOUCH;
  29136. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  29137. exports.TetrahedronBufferGeometry = TetrahedronGeometry;
  29138. exports.TetrahedronGeometry = TetrahedronGeometry;
  29139. exports.TextBufferGeometry = TextGeometry;
  29140. exports.TextGeometry = TextGeometry;
  29141. exports.Texture = Texture;
  29142. exports.TextureLoader = TextureLoader;
  29143. exports.TorusBufferGeometry = TorusGeometry;
  29144. exports.TorusGeometry = TorusGeometry;
  29145. exports.TorusKnotBufferGeometry = TorusKnotGeometry;
  29146. exports.TorusKnotGeometry = TorusKnotGeometry;
  29147. exports.Triangle = Triangle;
  29148. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  29149. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  29150. exports.TrianglesDrawMode = TrianglesDrawMode;
  29151. exports.TubeBufferGeometry = TubeGeometry;
  29152. exports.TubeGeometry = TubeGeometry;
  29153. exports.UVMapping = UVMapping;
  29154. exports.Uint16Attribute = Uint16Attribute;
  29155. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  29156. exports.Uint32Attribute = Uint32Attribute;
  29157. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  29158. exports.Uint8Attribute = Uint8Attribute;
  29159. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  29160. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  29161. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  29162. exports.Uniform = Uniform;
  29163. exports.UniformsLib = UniformsLib;
  29164. exports.UniformsUtils = UniformsUtils;
  29165. exports.UnsignedByteType = UnsignedByteType;
  29166. exports.UnsignedInt248Type = UnsignedInt248Type;
  29167. exports.UnsignedIntType = UnsignedIntType;
  29168. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  29169. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  29170. exports.UnsignedShort565Type = UnsignedShort565Type;
  29171. exports.UnsignedShortType = UnsignedShortType;
  29172. exports.VSMShadowMap = VSMShadowMap;
  29173. exports.Vector2 = Vector2;
  29174. exports.Vector3 = Vector3;
  29175. exports.Vector4 = Vector4;
  29176. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  29177. exports.Vertex = Vertex;
  29178. exports.VertexColors = VertexColors;
  29179. exports.VideoTexture = VideoTexture;
  29180. exports.WebGL1Renderer = WebGL1Renderer;
  29181. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  29182. exports.WebGLMultipleRenderTargets = WebGLMultipleRenderTargets;
  29183. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  29184. exports.WebGLRenderTarget = WebGLRenderTarget;
  29185. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  29186. exports.WebGLRenderer = WebGLRenderer;
  29187. exports.WebGLUtils = WebGLUtils;
  29188. exports.WireframeGeometry = WireframeGeometry;
  29189. exports.WireframeHelper = WireframeHelper;
  29190. exports.WrapAroundEnding = WrapAroundEnding;
  29191. exports.XHRLoader = XHRLoader;
  29192. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  29193. exports.ZeroFactor = ZeroFactor;
  29194. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  29195. exports.ZeroStencilOp = ZeroStencilOp;
  29196. exports.sRGBEncoding = sRGBEncoding;
  29197. Object.defineProperty(exports, '__esModule', { value: true });
  29198. })));
粤ICP备19079148号