3d-force-graph.js 1.4 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398
  1. // Version 1.70.5 3d-force-graph - https://github.com/vasturiano/3d-force-graph
  2. (function (global, factory) {
  3. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  4. typeof define === 'function' && define.amd ? define(factory) :
  5. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.ForceGraph3D = factory());
  6. }(this, (function () { 'use strict';
  7. function styleInject$1(css, ref) {
  8. if ( ref === void 0 ) ref = {};
  9. var insertAt = ref.insertAt;
  10. if (!css || typeof document === 'undefined') { return; }
  11. var head = document.head || document.getElementsByTagName('head')[0];
  12. var style = document.createElement('style');
  13. style.type = 'text/css';
  14. if (insertAt === 'top') {
  15. if (head.firstChild) {
  16. head.insertBefore(style, head.firstChild);
  17. } else {
  18. head.appendChild(style);
  19. }
  20. } else {
  21. head.appendChild(style);
  22. }
  23. if (style.styleSheet) {
  24. style.styleSheet.cssText = css;
  25. } else {
  26. style.appendChild(document.createTextNode(css));
  27. }
  28. }
  29. var css_248z$1 = ".graph-info-msg {\n top: 50%;\n width: 100%;\n text-align: center;\n color: lavender;\n opacity: 0.7;\n font-size: 22px;\n position: absolute;\n font-family: Sans-serif;\n}\n\n.scene-container .clickable {\n cursor: pointer;\n}\n\n.scene-container .grabbable {\n cursor: move;\n cursor: grab;\n cursor: -moz-grab;\n cursor: -webkit-grab;\n}\n\n.scene-container .grabbable:active {\n cursor: grabbing;\n cursor: -moz-grabbing;\n cursor: -webkit-grabbing;\n}";
  30. styleInject$1(css_248z$1);
  31. function ownKeys$2(object, enumerableOnly) {
  32. var keys = Object.keys(object);
  33. if (Object.getOwnPropertySymbols) {
  34. var symbols = Object.getOwnPropertySymbols(object);
  35. if (enumerableOnly) {
  36. symbols = symbols.filter(function (sym) {
  37. return Object.getOwnPropertyDescriptor(object, sym).enumerable;
  38. });
  39. }
  40. keys.push.apply(keys, symbols);
  41. }
  42. return keys;
  43. }
  44. function _objectSpread2$2(target) {
  45. for (var i = 1; i < arguments.length; i++) {
  46. var source = arguments[i] != null ? arguments[i] : {};
  47. if (i % 2) {
  48. ownKeys$2(Object(source), true).forEach(function (key) {
  49. _defineProperty$3(target, key, source[key]);
  50. });
  51. } else if (Object.getOwnPropertyDescriptors) {
  52. Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
  53. } else {
  54. ownKeys$2(Object(source)).forEach(function (key) {
  55. Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
  56. });
  57. }
  58. }
  59. return target;
  60. }
  61. function _defineProperty$3(obj, key, value) {
  62. if (key in obj) {
  63. Object.defineProperty(obj, key, {
  64. value: value,
  65. enumerable: true,
  66. configurable: true,
  67. writable: true
  68. });
  69. } else {
  70. obj[key] = value;
  71. }
  72. return obj;
  73. }
  74. function _toConsumableArray$4(arr) {
  75. return _arrayWithoutHoles$4(arr) || _iterableToArray$4(arr) || _unsupportedIterableToArray$5(arr) || _nonIterableSpread$4();
  76. }
  77. function _arrayWithoutHoles$4(arr) {
  78. if (Array.isArray(arr)) return _arrayLikeToArray$5(arr);
  79. }
  80. function _iterableToArray$4(iter) {
  81. if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
  82. }
  83. function _unsupportedIterableToArray$5(o, minLen) {
  84. if (!o) return;
  85. if (typeof o === "string") return _arrayLikeToArray$5(o, minLen);
  86. var n = Object.prototype.toString.call(o).slice(8, -1);
  87. if (n === "Object" && o.constructor) n = o.constructor.name;
  88. if (n === "Map" || n === "Set") return Array.from(o);
  89. if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$5(o, minLen);
  90. }
  91. function _arrayLikeToArray$5(arr, len) {
  92. if (len == null || len > arr.length) len = arr.length;
  93. for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  94. return arr2;
  95. }
  96. function _nonIterableSpread$4() {
  97. throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  98. }
  99. /**
  100. * @license
  101. * Copyright 2010-2021 Three.js Authors
  102. * SPDX-License-Identifier: MIT
  103. */
  104. const REVISION = '130';
  105. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  106. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  107. const CullFaceNone = 0;
  108. const CullFaceBack = 1;
  109. const CullFaceFront = 2;
  110. const PCFShadowMap = 1;
  111. const PCFSoftShadowMap = 2;
  112. const VSMShadowMap = 3;
  113. const FrontSide = 0;
  114. const BackSide = 1;
  115. const DoubleSide = 2;
  116. const FlatShading = 1;
  117. const NoBlending = 0;
  118. const NormalBlending = 1;
  119. const AdditiveBlending = 2;
  120. const SubtractiveBlending = 3;
  121. const MultiplyBlending = 4;
  122. const CustomBlending = 5;
  123. const AddEquation = 100;
  124. const SubtractEquation = 101;
  125. const ReverseSubtractEquation = 102;
  126. const MinEquation = 103;
  127. const MaxEquation = 104;
  128. const ZeroFactor = 200;
  129. const OneFactor = 201;
  130. const SrcColorFactor = 202;
  131. const OneMinusSrcColorFactor = 203;
  132. const SrcAlphaFactor = 204;
  133. const OneMinusSrcAlphaFactor = 205;
  134. const DstAlphaFactor = 206;
  135. const OneMinusDstAlphaFactor = 207;
  136. const DstColorFactor = 208;
  137. const OneMinusDstColorFactor = 209;
  138. const SrcAlphaSaturateFactor = 210;
  139. const NeverDepth = 0;
  140. const AlwaysDepth = 1;
  141. const LessDepth = 2;
  142. const LessEqualDepth = 3;
  143. const EqualDepth = 4;
  144. const GreaterEqualDepth = 5;
  145. const GreaterDepth = 6;
  146. const NotEqualDepth = 7;
  147. const MultiplyOperation = 0;
  148. const MixOperation = 1;
  149. const AddOperation = 2;
  150. const NoToneMapping = 0;
  151. const LinearToneMapping = 1;
  152. const ReinhardToneMapping = 2;
  153. const CineonToneMapping = 3;
  154. const ACESFilmicToneMapping = 4;
  155. const CustomToneMapping = 5;
  156. const UVMapping = 300;
  157. const CubeReflectionMapping = 301;
  158. const CubeRefractionMapping = 302;
  159. const EquirectangularReflectionMapping = 303;
  160. const EquirectangularRefractionMapping = 304;
  161. const CubeUVReflectionMapping = 306;
  162. const CubeUVRefractionMapping = 307;
  163. const RepeatWrapping = 1000;
  164. const ClampToEdgeWrapping = 1001;
  165. const MirroredRepeatWrapping = 1002;
  166. const NearestFilter = 1003;
  167. const NearestMipmapNearestFilter = 1004;
  168. const NearestMipmapLinearFilter = 1005;
  169. const LinearFilter = 1006;
  170. const LinearMipmapNearestFilter = 1007;
  171. const LinearMipmapLinearFilter = 1008;
  172. const UnsignedByteType = 1009;
  173. const ByteType = 1010;
  174. const ShortType = 1011;
  175. const UnsignedShortType = 1012;
  176. const IntType = 1013;
  177. const UnsignedIntType = 1014;
  178. const FloatType = 1015;
  179. const HalfFloatType = 1016;
  180. const UnsignedShort4444Type = 1017;
  181. const UnsignedShort5551Type = 1018;
  182. const UnsignedShort565Type = 1019;
  183. const UnsignedInt248Type = 1020;
  184. const AlphaFormat = 1021;
  185. const RGBFormat = 1022;
  186. const RGBAFormat = 1023;
  187. const LuminanceFormat = 1024;
  188. const LuminanceAlphaFormat = 1025;
  189. const DepthFormat = 1026;
  190. const DepthStencilFormat = 1027;
  191. const RedFormat = 1028;
  192. const RedIntegerFormat = 1029;
  193. const RGFormat = 1030;
  194. const RGIntegerFormat = 1031;
  195. const RGBIntegerFormat = 1032;
  196. const RGBAIntegerFormat = 1033;
  197. const RGB_S3TC_DXT1_Format = 33776;
  198. const RGBA_S3TC_DXT1_Format = 33777;
  199. const RGBA_S3TC_DXT3_Format = 33778;
  200. const RGBA_S3TC_DXT5_Format = 33779;
  201. const RGB_PVRTC_4BPPV1_Format = 35840;
  202. const RGB_PVRTC_2BPPV1_Format = 35841;
  203. const RGBA_PVRTC_4BPPV1_Format = 35842;
  204. const RGBA_PVRTC_2BPPV1_Format = 35843;
  205. const RGB_ETC1_Format = 36196;
  206. const RGB_ETC2_Format = 37492;
  207. const RGBA_ETC2_EAC_Format = 37496;
  208. const RGBA_ASTC_4x4_Format = 37808;
  209. const RGBA_ASTC_5x4_Format = 37809;
  210. const RGBA_ASTC_5x5_Format = 37810;
  211. const RGBA_ASTC_6x5_Format = 37811;
  212. const RGBA_ASTC_6x6_Format = 37812;
  213. const RGBA_ASTC_8x5_Format = 37813;
  214. const RGBA_ASTC_8x6_Format = 37814;
  215. const RGBA_ASTC_8x8_Format = 37815;
  216. const RGBA_ASTC_10x5_Format = 37816;
  217. const RGBA_ASTC_10x6_Format = 37817;
  218. const RGBA_ASTC_10x8_Format = 37818;
  219. const RGBA_ASTC_10x10_Format = 37819;
  220. const RGBA_ASTC_12x10_Format = 37820;
  221. const RGBA_ASTC_12x12_Format = 37821;
  222. const RGBA_BPTC_Format = 36492;
  223. const SRGB8_ALPHA8_ASTC_4x4_Format = 37840;
  224. const SRGB8_ALPHA8_ASTC_5x4_Format = 37841;
  225. const SRGB8_ALPHA8_ASTC_5x5_Format = 37842;
  226. const SRGB8_ALPHA8_ASTC_6x5_Format = 37843;
  227. const SRGB8_ALPHA8_ASTC_6x6_Format = 37844;
  228. const SRGB8_ALPHA8_ASTC_8x5_Format = 37845;
  229. const SRGB8_ALPHA8_ASTC_8x6_Format = 37846;
  230. const SRGB8_ALPHA8_ASTC_8x8_Format = 37847;
  231. const SRGB8_ALPHA8_ASTC_10x5_Format = 37848;
  232. const SRGB8_ALPHA8_ASTC_10x6_Format = 37849;
  233. const SRGB8_ALPHA8_ASTC_10x8_Format = 37850;
  234. const SRGB8_ALPHA8_ASTC_10x10_Format = 37851;
  235. const SRGB8_ALPHA8_ASTC_12x10_Format = 37852;
  236. const SRGB8_ALPHA8_ASTC_12x12_Format = 37853;
  237. const LoopOnce = 2200;
  238. const LoopRepeat = 2201;
  239. const LoopPingPong = 2202;
  240. const InterpolateDiscrete = 2300;
  241. const InterpolateLinear = 2301;
  242. const InterpolateSmooth = 2302;
  243. const ZeroCurvatureEnding = 2400;
  244. const ZeroSlopeEnding = 2401;
  245. const WrapAroundEnding = 2402;
  246. const NormalAnimationBlendMode = 2500;
  247. const AdditiveAnimationBlendMode = 2501;
  248. const TrianglesDrawMode = 0;
  249. const LinearEncoding = 3000;
  250. const sRGBEncoding = 3001;
  251. const GammaEncoding = 3007;
  252. const RGBEEncoding = 3002;
  253. const LogLuvEncoding = 3003;
  254. const RGBM7Encoding = 3004;
  255. const RGBM16Encoding = 3005;
  256. const RGBDEncoding = 3006;
  257. const BasicDepthPacking = 3200;
  258. const RGBADepthPacking = 3201;
  259. const TangentSpaceNormalMap = 0;
  260. const ObjectSpaceNormalMap = 1;
  261. const KeepStencilOp = 7680;
  262. const AlwaysStencilFunc = 519;
  263. const StaticDrawUsage = 35044;
  264. const DynamicDrawUsage = 35048;
  265. const GLSL3 = '300 es';
  266. /**
  267. * https://github.com/mrdoob/eventdispatcher.js/
  268. */
  269. class EventDispatcher {
  270. addEventListener( type, listener ) {
  271. if ( this._listeners === undefined ) this._listeners = {};
  272. const listeners = this._listeners;
  273. if ( listeners[ type ] === undefined ) {
  274. listeners[ type ] = [];
  275. }
  276. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  277. listeners[ type ].push( listener );
  278. }
  279. }
  280. hasEventListener( type, listener ) {
  281. if ( this._listeners === undefined ) return false;
  282. const listeners = this._listeners;
  283. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  284. }
  285. removeEventListener( type, listener ) {
  286. if ( this._listeners === undefined ) return;
  287. const listeners = this._listeners;
  288. const listenerArray = listeners[ type ];
  289. if ( listenerArray !== undefined ) {
  290. const index = listenerArray.indexOf( listener );
  291. if ( index !== - 1 ) {
  292. listenerArray.splice( index, 1 );
  293. }
  294. }
  295. }
  296. dispatchEvent( event ) {
  297. if ( this._listeners === undefined ) return;
  298. const listeners = this._listeners;
  299. const listenerArray = listeners[ event.type ];
  300. if ( listenerArray !== undefined ) {
  301. event.target = this;
  302. // Make a copy, in case listeners are removed while iterating.
  303. const array = listenerArray.slice( 0 );
  304. for ( let i = 0, l = array.length; i < l; i ++ ) {
  305. array[ i ].call( this, event );
  306. }
  307. event.target = null;
  308. }
  309. }
  310. }
  311. const _lut = [];
  312. for ( let i = 0; i < 256; i ++ ) {
  313. _lut[ i ] = ( i < 16 ? '0' : '' ) + ( i ).toString( 16 );
  314. }
  315. const DEG2RAD = Math.PI / 180;
  316. const RAD2DEG = 180 / Math.PI;
  317. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  318. function generateUUID() {
  319. const d0 = Math.random() * 0xffffffff | 0;
  320. const d1 = Math.random() * 0xffffffff | 0;
  321. const d2 = Math.random() * 0xffffffff | 0;
  322. const d3 = Math.random() * 0xffffffff | 0;
  323. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  324. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  325. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  326. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  327. // .toUpperCase() here flattens concatenated strings to save heap memory space.
  328. return uuid.toUpperCase();
  329. }
  330. function clamp( value, min, max ) {
  331. return Math.max( min, Math.min( max, value ) );
  332. }
  333. // compute euclidian modulo of m % n
  334. // https://en.wikipedia.org/wiki/Modulo_operation
  335. function euclideanModulo( n, m ) {
  336. return ( ( n % m ) + m ) % m;
  337. }
  338. // https://en.wikipedia.org/wiki/Linear_interpolation
  339. function lerp( x, y, t ) {
  340. return ( 1 - t ) * x + t * y;
  341. }
  342. function isPowerOfTwo( value ) {
  343. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  344. }
  345. function floorPowerOfTwo( value ) {
  346. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  347. }
  348. class Vector2 {
  349. constructor( x = 0, y = 0 ) {
  350. this.x = x;
  351. this.y = y;
  352. }
  353. get width() {
  354. return this.x;
  355. }
  356. set width( value ) {
  357. this.x = value;
  358. }
  359. get height() {
  360. return this.y;
  361. }
  362. set height( value ) {
  363. this.y = value;
  364. }
  365. set( x, y ) {
  366. this.x = x;
  367. this.y = y;
  368. return this;
  369. }
  370. setScalar( scalar ) {
  371. this.x = scalar;
  372. this.y = scalar;
  373. return this;
  374. }
  375. setX( x ) {
  376. this.x = x;
  377. return this;
  378. }
  379. setY( y ) {
  380. this.y = y;
  381. return this;
  382. }
  383. setComponent( index, value ) {
  384. switch ( index ) {
  385. case 0: this.x = value; break;
  386. case 1: this.y = value; break;
  387. default: throw new Error( 'index is out of range: ' + index );
  388. }
  389. return this;
  390. }
  391. getComponent( index ) {
  392. switch ( index ) {
  393. case 0: return this.x;
  394. case 1: return this.y;
  395. default: throw new Error( 'index is out of range: ' + index );
  396. }
  397. }
  398. clone() {
  399. return new this.constructor( this.x, this.y );
  400. }
  401. copy( v ) {
  402. this.x = v.x;
  403. this.y = v.y;
  404. return this;
  405. }
  406. add( v, w ) {
  407. if ( w !== undefined ) {
  408. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  409. return this.addVectors( v, w );
  410. }
  411. this.x += v.x;
  412. this.y += v.y;
  413. return this;
  414. }
  415. addScalar( s ) {
  416. this.x += s;
  417. this.y += s;
  418. return this;
  419. }
  420. addVectors( a, b ) {
  421. this.x = a.x + b.x;
  422. this.y = a.y + b.y;
  423. return this;
  424. }
  425. addScaledVector( v, s ) {
  426. this.x += v.x * s;
  427. this.y += v.y * s;
  428. return this;
  429. }
  430. sub( v, w ) {
  431. if ( w !== undefined ) {
  432. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  433. return this.subVectors( v, w );
  434. }
  435. this.x -= v.x;
  436. this.y -= v.y;
  437. return this;
  438. }
  439. subScalar( s ) {
  440. this.x -= s;
  441. this.y -= s;
  442. return this;
  443. }
  444. subVectors( a, b ) {
  445. this.x = a.x - b.x;
  446. this.y = a.y - b.y;
  447. return this;
  448. }
  449. multiply( v ) {
  450. this.x *= v.x;
  451. this.y *= v.y;
  452. return this;
  453. }
  454. multiplyScalar( scalar ) {
  455. this.x *= scalar;
  456. this.y *= scalar;
  457. return this;
  458. }
  459. divide( v ) {
  460. this.x /= v.x;
  461. this.y /= v.y;
  462. return this;
  463. }
  464. divideScalar( scalar ) {
  465. return this.multiplyScalar( 1 / scalar );
  466. }
  467. applyMatrix3( m ) {
  468. const x = this.x, y = this.y;
  469. const e = m.elements;
  470. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  471. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  472. return this;
  473. }
  474. min( v ) {
  475. this.x = Math.min( this.x, v.x );
  476. this.y = Math.min( this.y, v.y );
  477. return this;
  478. }
  479. max( v ) {
  480. this.x = Math.max( this.x, v.x );
  481. this.y = Math.max( this.y, v.y );
  482. return this;
  483. }
  484. clamp( min, max ) {
  485. // assumes min < max, componentwise
  486. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  487. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  488. return this;
  489. }
  490. clampScalar( minVal, maxVal ) {
  491. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  492. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  493. return this;
  494. }
  495. clampLength( min, max ) {
  496. const length = this.length();
  497. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  498. }
  499. floor() {
  500. this.x = Math.floor( this.x );
  501. this.y = Math.floor( this.y );
  502. return this;
  503. }
  504. ceil() {
  505. this.x = Math.ceil( this.x );
  506. this.y = Math.ceil( this.y );
  507. return this;
  508. }
  509. round() {
  510. this.x = Math.round( this.x );
  511. this.y = Math.round( this.y );
  512. return this;
  513. }
  514. roundToZero() {
  515. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  516. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  517. return this;
  518. }
  519. negate() {
  520. this.x = - this.x;
  521. this.y = - this.y;
  522. return this;
  523. }
  524. dot( v ) {
  525. return this.x * v.x + this.y * v.y;
  526. }
  527. cross( v ) {
  528. return this.x * v.y - this.y * v.x;
  529. }
  530. lengthSq() {
  531. return this.x * this.x + this.y * this.y;
  532. }
  533. length() {
  534. return Math.sqrt( this.x * this.x + this.y * this.y );
  535. }
  536. manhattanLength() {
  537. return Math.abs( this.x ) + Math.abs( this.y );
  538. }
  539. normalize() {
  540. return this.divideScalar( this.length() || 1 );
  541. }
  542. angle() {
  543. // computes the angle in radians with respect to the positive x-axis
  544. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  545. return angle;
  546. }
  547. distanceTo( v ) {
  548. return Math.sqrt( this.distanceToSquared( v ) );
  549. }
  550. distanceToSquared( v ) {
  551. const dx = this.x - v.x, dy = this.y - v.y;
  552. return dx * dx + dy * dy;
  553. }
  554. manhattanDistanceTo( v ) {
  555. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  556. }
  557. setLength( length ) {
  558. return this.normalize().multiplyScalar( length );
  559. }
  560. lerp( v, alpha ) {
  561. this.x += ( v.x - this.x ) * alpha;
  562. this.y += ( v.y - this.y ) * alpha;
  563. return this;
  564. }
  565. lerpVectors( v1, v2, alpha ) {
  566. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  567. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  568. return this;
  569. }
  570. equals( v ) {
  571. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  572. }
  573. fromArray( array, offset = 0 ) {
  574. this.x = array[ offset ];
  575. this.y = array[ offset + 1 ];
  576. return this;
  577. }
  578. toArray( array = [], offset = 0 ) {
  579. array[ offset ] = this.x;
  580. array[ offset + 1 ] = this.y;
  581. return array;
  582. }
  583. fromBufferAttribute( attribute, index, offset ) {
  584. if ( offset !== undefined ) {
  585. console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' );
  586. }
  587. this.x = attribute.getX( index );
  588. this.y = attribute.getY( index );
  589. return this;
  590. }
  591. rotateAround( center, angle ) {
  592. const c = Math.cos( angle ), s = Math.sin( angle );
  593. const x = this.x - center.x;
  594. const y = this.y - center.y;
  595. this.x = x * c - y * s + center.x;
  596. this.y = x * s + y * c + center.y;
  597. return this;
  598. }
  599. random() {
  600. this.x = Math.random();
  601. this.y = Math.random();
  602. return this;
  603. }
  604. }
  605. Vector2.prototype.isVector2 = true;
  606. class Matrix3 {
  607. constructor() {
  608. this.elements = [
  609. 1, 0, 0,
  610. 0, 1, 0,
  611. 0, 0, 1
  612. ];
  613. if ( arguments.length > 0 ) {
  614. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  615. }
  616. }
  617. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  618. const te = this.elements;
  619. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  620. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  621. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  622. return this;
  623. }
  624. identity() {
  625. this.set(
  626. 1, 0, 0,
  627. 0, 1, 0,
  628. 0, 0, 1
  629. );
  630. return this;
  631. }
  632. copy( m ) {
  633. const te = this.elements;
  634. const me = m.elements;
  635. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  636. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  637. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  638. return this;
  639. }
  640. extractBasis( xAxis, yAxis, zAxis ) {
  641. xAxis.setFromMatrix3Column( this, 0 );
  642. yAxis.setFromMatrix3Column( this, 1 );
  643. zAxis.setFromMatrix3Column( this, 2 );
  644. return this;
  645. }
  646. setFromMatrix4( m ) {
  647. const me = m.elements;
  648. this.set(
  649. me[ 0 ], me[ 4 ], me[ 8 ],
  650. me[ 1 ], me[ 5 ], me[ 9 ],
  651. me[ 2 ], me[ 6 ], me[ 10 ]
  652. );
  653. return this;
  654. }
  655. multiply( m ) {
  656. return this.multiplyMatrices( this, m );
  657. }
  658. premultiply( m ) {
  659. return this.multiplyMatrices( m, this );
  660. }
  661. multiplyMatrices( a, b ) {
  662. const ae = a.elements;
  663. const be = b.elements;
  664. const te = this.elements;
  665. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  666. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  667. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  668. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  669. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  670. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  671. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  672. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  673. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  674. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  675. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  676. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  677. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  678. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  679. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  680. return this;
  681. }
  682. multiplyScalar( s ) {
  683. const te = this.elements;
  684. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  685. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  686. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  687. return this;
  688. }
  689. determinant() {
  690. const te = this.elements;
  691. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  692. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  693. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  694. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  695. }
  696. invert() {
  697. const te = this.elements,
  698. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  699. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  700. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  701. t11 = n33 * n22 - n32 * n23,
  702. t12 = n32 * n13 - n33 * n12,
  703. t13 = n23 * n12 - n22 * n13,
  704. det = n11 * t11 + n21 * t12 + n31 * t13;
  705. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  706. const detInv = 1 / det;
  707. te[ 0 ] = t11 * detInv;
  708. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  709. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  710. te[ 3 ] = t12 * detInv;
  711. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  712. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  713. te[ 6 ] = t13 * detInv;
  714. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  715. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  716. return this;
  717. }
  718. transpose() {
  719. let tmp;
  720. const m = this.elements;
  721. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  722. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  723. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  724. return this;
  725. }
  726. getNormalMatrix( matrix4 ) {
  727. return this.setFromMatrix4( matrix4 ).invert().transpose();
  728. }
  729. transposeIntoArray( r ) {
  730. const m = this.elements;
  731. r[ 0 ] = m[ 0 ];
  732. r[ 1 ] = m[ 3 ];
  733. r[ 2 ] = m[ 6 ];
  734. r[ 3 ] = m[ 1 ];
  735. r[ 4 ] = m[ 4 ];
  736. r[ 5 ] = m[ 7 ];
  737. r[ 6 ] = m[ 2 ];
  738. r[ 7 ] = m[ 5 ];
  739. r[ 8 ] = m[ 8 ];
  740. return this;
  741. }
  742. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  743. const c = Math.cos( rotation );
  744. const s = Math.sin( rotation );
  745. this.set(
  746. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  747. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  748. 0, 0, 1
  749. );
  750. return this;
  751. }
  752. scale( sx, sy ) {
  753. const te = this.elements;
  754. te[ 0 ] *= sx; te[ 3 ] *= sx; te[ 6 ] *= sx;
  755. te[ 1 ] *= sy; te[ 4 ] *= sy; te[ 7 ] *= sy;
  756. return this;
  757. }
  758. rotate( theta ) {
  759. const c = Math.cos( theta );
  760. const s = Math.sin( theta );
  761. const te = this.elements;
  762. const a11 = te[ 0 ], a12 = te[ 3 ], a13 = te[ 6 ];
  763. const a21 = te[ 1 ], a22 = te[ 4 ], a23 = te[ 7 ];
  764. te[ 0 ] = c * a11 + s * a21;
  765. te[ 3 ] = c * a12 + s * a22;
  766. te[ 6 ] = c * a13 + s * a23;
  767. te[ 1 ] = - s * a11 + c * a21;
  768. te[ 4 ] = - s * a12 + c * a22;
  769. te[ 7 ] = - s * a13 + c * a23;
  770. return this;
  771. }
  772. translate( tx, ty ) {
  773. const te = this.elements;
  774. te[ 0 ] += tx * te[ 2 ]; te[ 3 ] += tx * te[ 5 ]; te[ 6 ] += tx * te[ 8 ];
  775. te[ 1 ] += ty * te[ 2 ]; te[ 4 ] += ty * te[ 5 ]; te[ 7 ] += ty * te[ 8 ];
  776. return this;
  777. }
  778. equals( matrix ) {
  779. const te = this.elements;
  780. const me = matrix.elements;
  781. for ( let i = 0; i < 9; i ++ ) {
  782. if ( te[ i ] !== me[ i ] ) return false;
  783. }
  784. return true;
  785. }
  786. fromArray( array, offset = 0 ) {
  787. for ( let i = 0; i < 9; i ++ ) {
  788. this.elements[ i ] = array[ i + offset ];
  789. }
  790. return this;
  791. }
  792. toArray( array = [], offset = 0 ) {
  793. const te = this.elements;
  794. array[ offset ] = te[ 0 ];
  795. array[ offset + 1 ] = te[ 1 ];
  796. array[ offset + 2 ] = te[ 2 ];
  797. array[ offset + 3 ] = te[ 3 ];
  798. array[ offset + 4 ] = te[ 4 ];
  799. array[ offset + 5 ] = te[ 5 ];
  800. array[ offset + 6 ] = te[ 6 ];
  801. array[ offset + 7 ] = te[ 7 ];
  802. array[ offset + 8 ] = te[ 8 ];
  803. return array;
  804. }
  805. clone() {
  806. return new this.constructor().fromArray( this.elements );
  807. }
  808. }
  809. Matrix3.prototype.isMatrix3 = true;
  810. let _canvas;
  811. class ImageUtils {
  812. static getDataURL( image ) {
  813. if ( /^data:/i.test( image.src ) ) {
  814. return image.src;
  815. }
  816. if ( typeof HTMLCanvasElement == 'undefined' ) {
  817. return image.src;
  818. }
  819. let canvas;
  820. if ( image instanceof HTMLCanvasElement ) {
  821. canvas = image;
  822. } else {
  823. if ( _canvas === undefined ) _canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  824. _canvas.width = image.width;
  825. _canvas.height = image.height;
  826. const context = _canvas.getContext( '2d' );
  827. if ( image instanceof ImageData ) {
  828. context.putImageData( image, 0, 0 );
  829. } else {
  830. context.drawImage( image, 0, 0, image.width, image.height );
  831. }
  832. canvas = _canvas;
  833. }
  834. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  835. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  836. return canvas.toDataURL( 'image/jpeg', 0.6 );
  837. } else {
  838. return canvas.toDataURL( 'image/png' );
  839. }
  840. }
  841. }
  842. let textureId = 0;
  843. class Texture extends EventDispatcher {
  844. 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 ) {
  845. super();
  846. Object.defineProperty( this, 'id', { value: textureId ++ } );
  847. this.uuid = generateUUID();
  848. this.name = '';
  849. this.image = image;
  850. this.mipmaps = [];
  851. this.mapping = mapping;
  852. this.wrapS = wrapS;
  853. this.wrapT = wrapT;
  854. this.magFilter = magFilter;
  855. this.minFilter = minFilter;
  856. this.anisotropy = anisotropy;
  857. this.format = format;
  858. this.internalFormat = null;
  859. this.type = type;
  860. this.offset = new Vector2( 0, 0 );
  861. this.repeat = new Vector2( 1, 1 );
  862. this.center = new Vector2( 0, 0 );
  863. this.rotation = 0;
  864. this.matrixAutoUpdate = true;
  865. this.matrix = new Matrix3();
  866. this.generateMipmaps = true;
  867. this.premultiplyAlpha = false;
  868. this.flipY = true;
  869. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  870. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  871. //
  872. // Also changing the encoding after already used by a Material will not automatically make the Material
  873. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  874. this.encoding = encoding;
  875. this.version = 0;
  876. this.onUpdate = null;
  877. }
  878. updateMatrix() {
  879. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  880. }
  881. clone() {
  882. return new this.constructor().copy( this );
  883. }
  884. copy( source ) {
  885. this.name = source.name;
  886. this.image = source.image;
  887. this.mipmaps = source.mipmaps.slice( 0 );
  888. this.mapping = source.mapping;
  889. this.wrapS = source.wrapS;
  890. this.wrapT = source.wrapT;
  891. this.magFilter = source.magFilter;
  892. this.minFilter = source.minFilter;
  893. this.anisotropy = source.anisotropy;
  894. this.format = source.format;
  895. this.internalFormat = source.internalFormat;
  896. this.type = source.type;
  897. this.offset.copy( source.offset );
  898. this.repeat.copy( source.repeat );
  899. this.center.copy( source.center );
  900. this.rotation = source.rotation;
  901. this.matrixAutoUpdate = source.matrixAutoUpdate;
  902. this.matrix.copy( source.matrix );
  903. this.generateMipmaps = source.generateMipmaps;
  904. this.premultiplyAlpha = source.premultiplyAlpha;
  905. this.flipY = source.flipY;
  906. this.unpackAlignment = source.unpackAlignment;
  907. this.encoding = source.encoding;
  908. return this;
  909. }
  910. toJSON( meta ) {
  911. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  912. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  913. return meta.textures[ this.uuid ];
  914. }
  915. const output = {
  916. metadata: {
  917. version: 4.5,
  918. type: 'Texture',
  919. generator: 'Texture.toJSON'
  920. },
  921. uuid: this.uuid,
  922. name: this.name,
  923. mapping: this.mapping,
  924. repeat: [ this.repeat.x, this.repeat.y ],
  925. offset: [ this.offset.x, this.offset.y ],
  926. center: [ this.center.x, this.center.y ],
  927. rotation: this.rotation,
  928. wrap: [ this.wrapS, this.wrapT ],
  929. format: this.format,
  930. type: this.type,
  931. encoding: this.encoding,
  932. minFilter: this.minFilter,
  933. magFilter: this.magFilter,
  934. anisotropy: this.anisotropy,
  935. flipY: this.flipY,
  936. premultiplyAlpha: this.premultiplyAlpha,
  937. unpackAlignment: this.unpackAlignment
  938. };
  939. if ( this.image !== undefined ) {
  940. // TODO: Move to THREE.Image
  941. const image = this.image;
  942. if ( image.uuid === undefined ) {
  943. image.uuid = generateUUID(); // UGH
  944. }
  945. if ( ! isRootObject && meta.images[ image.uuid ] === undefined ) {
  946. let url;
  947. if ( Array.isArray( image ) ) {
  948. // process array of images e.g. CubeTexture
  949. url = [];
  950. for ( let i = 0, l = image.length; i < l; i ++ ) {
  951. // check cube texture with data textures
  952. if ( image[ i ].isDataTexture ) {
  953. url.push( serializeImage( image[ i ].image ) );
  954. } else {
  955. url.push( serializeImage( image[ i ] ) );
  956. }
  957. }
  958. } else {
  959. // process single image
  960. url = serializeImage( image );
  961. }
  962. meta.images[ image.uuid ] = {
  963. uuid: image.uuid,
  964. url: url
  965. };
  966. }
  967. output.image = image.uuid;
  968. }
  969. if ( ! isRootObject ) {
  970. meta.textures[ this.uuid ] = output;
  971. }
  972. return output;
  973. }
  974. dispose() {
  975. this.dispatchEvent( { type: 'dispose' } );
  976. }
  977. transformUv( uv ) {
  978. if ( this.mapping !== UVMapping ) return uv;
  979. uv.applyMatrix3( this.matrix );
  980. if ( uv.x < 0 || uv.x > 1 ) {
  981. switch ( this.wrapS ) {
  982. case RepeatWrapping:
  983. uv.x = uv.x - Math.floor( uv.x );
  984. break;
  985. case ClampToEdgeWrapping:
  986. uv.x = uv.x < 0 ? 0 : 1;
  987. break;
  988. case MirroredRepeatWrapping:
  989. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  990. uv.x = Math.ceil( uv.x ) - uv.x;
  991. } else {
  992. uv.x = uv.x - Math.floor( uv.x );
  993. }
  994. break;
  995. }
  996. }
  997. if ( uv.y < 0 || uv.y > 1 ) {
  998. switch ( this.wrapT ) {
  999. case RepeatWrapping:
  1000. uv.y = uv.y - Math.floor( uv.y );
  1001. break;
  1002. case ClampToEdgeWrapping:
  1003. uv.y = uv.y < 0 ? 0 : 1;
  1004. break;
  1005. case MirroredRepeatWrapping:
  1006. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1007. uv.y = Math.ceil( uv.y ) - uv.y;
  1008. } else {
  1009. uv.y = uv.y - Math.floor( uv.y );
  1010. }
  1011. break;
  1012. }
  1013. }
  1014. if ( this.flipY ) {
  1015. uv.y = 1 - uv.y;
  1016. }
  1017. return uv;
  1018. }
  1019. set needsUpdate( value ) {
  1020. if ( value === true ) this.version ++;
  1021. }
  1022. }
  1023. Texture.DEFAULT_IMAGE = undefined;
  1024. Texture.DEFAULT_MAPPING = UVMapping;
  1025. Texture.prototype.isTexture = true;
  1026. function serializeImage( image ) {
  1027. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1028. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1029. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1030. // default images
  1031. return ImageUtils.getDataURL( image );
  1032. } else {
  1033. if ( image.data ) {
  1034. // images of DataTexture
  1035. return {
  1036. data: Array.prototype.slice.call( image.data ),
  1037. width: image.width,
  1038. height: image.height,
  1039. type: image.data.constructor.name
  1040. };
  1041. } else {
  1042. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1043. return {};
  1044. }
  1045. }
  1046. }
  1047. class Vector4 {
  1048. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1049. this.x = x;
  1050. this.y = y;
  1051. this.z = z;
  1052. this.w = w;
  1053. }
  1054. get width() {
  1055. return this.z;
  1056. }
  1057. set width( value ) {
  1058. this.z = value;
  1059. }
  1060. get height() {
  1061. return this.w;
  1062. }
  1063. set height( value ) {
  1064. this.w = value;
  1065. }
  1066. set( x, y, z, w ) {
  1067. this.x = x;
  1068. this.y = y;
  1069. this.z = z;
  1070. this.w = w;
  1071. return this;
  1072. }
  1073. setScalar( scalar ) {
  1074. this.x = scalar;
  1075. this.y = scalar;
  1076. this.z = scalar;
  1077. this.w = scalar;
  1078. return this;
  1079. }
  1080. setX( x ) {
  1081. this.x = x;
  1082. return this;
  1083. }
  1084. setY( y ) {
  1085. this.y = y;
  1086. return this;
  1087. }
  1088. setZ( z ) {
  1089. this.z = z;
  1090. return this;
  1091. }
  1092. setW( w ) {
  1093. this.w = w;
  1094. return this;
  1095. }
  1096. setComponent( index, value ) {
  1097. switch ( index ) {
  1098. case 0: this.x = value; break;
  1099. case 1: this.y = value; break;
  1100. case 2: this.z = value; break;
  1101. case 3: this.w = value; break;
  1102. default: throw new Error( 'index is out of range: ' + index );
  1103. }
  1104. return this;
  1105. }
  1106. getComponent( index ) {
  1107. switch ( index ) {
  1108. case 0: return this.x;
  1109. case 1: return this.y;
  1110. case 2: return this.z;
  1111. case 3: return this.w;
  1112. default: throw new Error( 'index is out of range: ' + index );
  1113. }
  1114. }
  1115. clone() {
  1116. return new this.constructor( this.x, this.y, this.z, this.w );
  1117. }
  1118. copy( v ) {
  1119. this.x = v.x;
  1120. this.y = v.y;
  1121. this.z = v.z;
  1122. this.w = ( v.w !== undefined ) ? v.w : 1;
  1123. return this;
  1124. }
  1125. add( v, w ) {
  1126. if ( w !== undefined ) {
  1127. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1128. return this.addVectors( v, w );
  1129. }
  1130. this.x += v.x;
  1131. this.y += v.y;
  1132. this.z += v.z;
  1133. this.w += v.w;
  1134. return this;
  1135. }
  1136. addScalar( s ) {
  1137. this.x += s;
  1138. this.y += s;
  1139. this.z += s;
  1140. this.w += s;
  1141. return this;
  1142. }
  1143. addVectors( a, b ) {
  1144. this.x = a.x + b.x;
  1145. this.y = a.y + b.y;
  1146. this.z = a.z + b.z;
  1147. this.w = a.w + b.w;
  1148. return this;
  1149. }
  1150. addScaledVector( v, s ) {
  1151. this.x += v.x * s;
  1152. this.y += v.y * s;
  1153. this.z += v.z * s;
  1154. this.w += v.w * s;
  1155. return this;
  1156. }
  1157. sub( v, w ) {
  1158. if ( w !== undefined ) {
  1159. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1160. return this.subVectors( v, w );
  1161. }
  1162. this.x -= v.x;
  1163. this.y -= v.y;
  1164. this.z -= v.z;
  1165. this.w -= v.w;
  1166. return this;
  1167. }
  1168. subScalar( s ) {
  1169. this.x -= s;
  1170. this.y -= s;
  1171. this.z -= s;
  1172. this.w -= s;
  1173. return this;
  1174. }
  1175. subVectors( a, b ) {
  1176. this.x = a.x - b.x;
  1177. this.y = a.y - b.y;
  1178. this.z = a.z - b.z;
  1179. this.w = a.w - b.w;
  1180. return this;
  1181. }
  1182. multiply( v ) {
  1183. this.x *= v.x;
  1184. this.y *= v.y;
  1185. this.z *= v.z;
  1186. this.w *= v.w;
  1187. return this;
  1188. }
  1189. multiplyScalar( scalar ) {
  1190. this.x *= scalar;
  1191. this.y *= scalar;
  1192. this.z *= scalar;
  1193. this.w *= scalar;
  1194. return this;
  1195. }
  1196. applyMatrix4( m ) {
  1197. const x = this.x, y = this.y, z = this.z, w = this.w;
  1198. const e = m.elements;
  1199. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1200. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1201. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1202. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1203. return this;
  1204. }
  1205. divideScalar( scalar ) {
  1206. return this.multiplyScalar( 1 / scalar );
  1207. }
  1208. setAxisAngleFromQuaternion( q ) {
  1209. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1210. // q is assumed to be normalized
  1211. this.w = 2 * Math.acos( q.w );
  1212. const s = Math.sqrt( 1 - q.w * q.w );
  1213. if ( s < 0.0001 ) {
  1214. this.x = 1;
  1215. this.y = 0;
  1216. this.z = 0;
  1217. } else {
  1218. this.x = q.x / s;
  1219. this.y = q.y / s;
  1220. this.z = q.z / s;
  1221. }
  1222. return this;
  1223. }
  1224. setAxisAngleFromRotationMatrix( m ) {
  1225. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1226. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1227. let angle, x, y, z; // variables for result
  1228. const epsilon = 0.01, // margin to allow for rounding errors
  1229. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1230. te = m.elements,
  1231. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1232. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1233. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1234. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1235. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1236. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1237. // singularity found
  1238. // first check for identity matrix which must have +1 for all terms
  1239. // in leading diagonal and zero in other terms
  1240. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1241. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1242. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1243. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1244. // this singularity is identity matrix so angle = 0
  1245. this.set( 1, 0, 0, 0 );
  1246. return this; // zero angle, arbitrary axis
  1247. }
  1248. // otherwise this singularity is angle = 180
  1249. angle = Math.PI;
  1250. const xx = ( m11 + 1 ) / 2;
  1251. const yy = ( m22 + 1 ) / 2;
  1252. const zz = ( m33 + 1 ) / 2;
  1253. const xy = ( m12 + m21 ) / 4;
  1254. const xz = ( m13 + m31 ) / 4;
  1255. const yz = ( m23 + m32 ) / 4;
  1256. if ( ( xx > yy ) && ( xx > zz ) ) {
  1257. // m11 is the largest diagonal term
  1258. if ( xx < epsilon ) {
  1259. x = 0;
  1260. y = 0.707106781;
  1261. z = 0.707106781;
  1262. } else {
  1263. x = Math.sqrt( xx );
  1264. y = xy / x;
  1265. z = xz / x;
  1266. }
  1267. } else if ( yy > zz ) {
  1268. // m22 is the largest diagonal term
  1269. if ( yy < epsilon ) {
  1270. x = 0.707106781;
  1271. y = 0;
  1272. z = 0.707106781;
  1273. } else {
  1274. y = Math.sqrt( yy );
  1275. x = xy / y;
  1276. z = yz / y;
  1277. }
  1278. } else {
  1279. // m33 is the largest diagonal term so base result on this
  1280. if ( zz < epsilon ) {
  1281. x = 0.707106781;
  1282. y = 0.707106781;
  1283. z = 0;
  1284. } else {
  1285. z = Math.sqrt( zz );
  1286. x = xz / z;
  1287. y = yz / z;
  1288. }
  1289. }
  1290. this.set( x, y, z, angle );
  1291. return this; // return 180 deg rotation
  1292. }
  1293. // as we have reached here there are no singularities so we can handle normally
  1294. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1295. ( m13 - m31 ) * ( m13 - m31 ) +
  1296. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1297. if ( Math.abs( s ) < 0.001 ) s = 1;
  1298. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1299. // caught by singularity test above, but I've left it in just in case
  1300. this.x = ( m32 - m23 ) / s;
  1301. this.y = ( m13 - m31 ) / s;
  1302. this.z = ( m21 - m12 ) / s;
  1303. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1304. return this;
  1305. }
  1306. min( v ) {
  1307. this.x = Math.min( this.x, v.x );
  1308. this.y = Math.min( this.y, v.y );
  1309. this.z = Math.min( this.z, v.z );
  1310. this.w = Math.min( this.w, v.w );
  1311. return this;
  1312. }
  1313. max( v ) {
  1314. this.x = Math.max( this.x, v.x );
  1315. this.y = Math.max( this.y, v.y );
  1316. this.z = Math.max( this.z, v.z );
  1317. this.w = Math.max( this.w, v.w );
  1318. return this;
  1319. }
  1320. clamp( min, max ) {
  1321. // assumes min < max, componentwise
  1322. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1323. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1324. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1325. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1326. return this;
  1327. }
  1328. clampScalar( minVal, maxVal ) {
  1329. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1330. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1331. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1332. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  1333. return this;
  1334. }
  1335. clampLength( min, max ) {
  1336. const length = this.length();
  1337. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1338. }
  1339. floor() {
  1340. this.x = Math.floor( this.x );
  1341. this.y = Math.floor( this.y );
  1342. this.z = Math.floor( this.z );
  1343. this.w = Math.floor( this.w );
  1344. return this;
  1345. }
  1346. ceil() {
  1347. this.x = Math.ceil( this.x );
  1348. this.y = Math.ceil( this.y );
  1349. this.z = Math.ceil( this.z );
  1350. this.w = Math.ceil( this.w );
  1351. return this;
  1352. }
  1353. round() {
  1354. this.x = Math.round( this.x );
  1355. this.y = Math.round( this.y );
  1356. this.z = Math.round( this.z );
  1357. this.w = Math.round( this.w );
  1358. return this;
  1359. }
  1360. roundToZero() {
  1361. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1362. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1363. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1364. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1365. return this;
  1366. }
  1367. negate() {
  1368. this.x = - this.x;
  1369. this.y = - this.y;
  1370. this.z = - this.z;
  1371. this.w = - this.w;
  1372. return this;
  1373. }
  1374. dot( v ) {
  1375. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1376. }
  1377. lengthSq() {
  1378. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1379. }
  1380. length() {
  1381. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1382. }
  1383. manhattanLength() {
  1384. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1385. }
  1386. normalize() {
  1387. return this.divideScalar( this.length() || 1 );
  1388. }
  1389. setLength( length ) {
  1390. return this.normalize().multiplyScalar( length );
  1391. }
  1392. lerp( v, alpha ) {
  1393. this.x += ( v.x - this.x ) * alpha;
  1394. this.y += ( v.y - this.y ) * alpha;
  1395. this.z += ( v.z - this.z ) * alpha;
  1396. this.w += ( v.w - this.w ) * alpha;
  1397. return this;
  1398. }
  1399. lerpVectors( v1, v2, alpha ) {
  1400. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1401. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1402. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1403. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  1404. return this;
  1405. }
  1406. equals( v ) {
  1407. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1408. }
  1409. fromArray( array, offset = 0 ) {
  1410. this.x = array[ offset ];
  1411. this.y = array[ offset + 1 ];
  1412. this.z = array[ offset + 2 ];
  1413. this.w = array[ offset + 3 ];
  1414. return this;
  1415. }
  1416. toArray( array = [], offset = 0 ) {
  1417. array[ offset ] = this.x;
  1418. array[ offset + 1 ] = this.y;
  1419. array[ offset + 2 ] = this.z;
  1420. array[ offset + 3 ] = this.w;
  1421. return array;
  1422. }
  1423. fromBufferAttribute( attribute, index, offset ) {
  1424. if ( offset !== undefined ) {
  1425. console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' );
  1426. }
  1427. this.x = attribute.getX( index );
  1428. this.y = attribute.getY( index );
  1429. this.z = attribute.getZ( index );
  1430. this.w = attribute.getW( index );
  1431. return this;
  1432. }
  1433. random() {
  1434. this.x = Math.random();
  1435. this.y = Math.random();
  1436. this.z = Math.random();
  1437. this.w = Math.random();
  1438. return this;
  1439. }
  1440. }
  1441. Vector4.prototype.isVector4 = true;
  1442. /*
  1443. In options, we can specify:
  1444. * Texture parameters for an auto-generated target texture
  1445. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1446. */
  1447. class WebGLRenderTarget extends EventDispatcher {
  1448. constructor( width, height, options = {} ) {
  1449. super();
  1450. this.width = width;
  1451. this.height = height;
  1452. this.depth = 1;
  1453. this.scissor = new Vector4( 0, 0, width, height );
  1454. this.scissorTest = false;
  1455. this.viewport = new Vector4( 0, 0, width, height );
  1456. this.texture = new Texture( undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  1457. this.texture.image = { width: width, height: height, depth: 1 };
  1458. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  1459. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  1460. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  1461. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  1462. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  1463. }
  1464. setTexture( texture ) {
  1465. texture.image = {
  1466. width: this.width,
  1467. height: this.height,
  1468. depth: this.depth
  1469. };
  1470. this.texture = texture;
  1471. }
  1472. setSize( width, height, depth = 1 ) {
  1473. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1474. this.width = width;
  1475. this.height = height;
  1476. this.depth = depth;
  1477. this.texture.image.width = width;
  1478. this.texture.image.height = height;
  1479. this.texture.image.depth = depth;
  1480. this.dispose();
  1481. }
  1482. this.viewport.set( 0, 0, width, height );
  1483. this.scissor.set( 0, 0, width, height );
  1484. }
  1485. clone() {
  1486. return new this.constructor().copy( this );
  1487. }
  1488. copy( source ) {
  1489. this.width = source.width;
  1490. this.height = source.height;
  1491. this.depth = source.depth;
  1492. this.viewport.copy( source.viewport );
  1493. this.texture = source.texture.clone();
  1494. this.texture.image = { ...this.texture.image }; // See #20328.
  1495. this.depthBuffer = source.depthBuffer;
  1496. this.stencilBuffer = source.stencilBuffer;
  1497. this.depthTexture = source.depthTexture;
  1498. return this;
  1499. }
  1500. dispose() {
  1501. this.dispatchEvent( { type: 'dispose' } );
  1502. }
  1503. }
  1504. WebGLRenderTarget.prototype.isWebGLRenderTarget = true;
  1505. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  1506. constructor( width, height, count ) {
  1507. super( width, height );
  1508. const texture = this.texture;
  1509. this.texture = [];
  1510. for ( let i = 0; i < count; i ++ ) {
  1511. this.texture[ i ] = texture.clone();
  1512. }
  1513. }
  1514. setSize( width, height, depth = 1 ) {
  1515. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1516. this.width = width;
  1517. this.height = height;
  1518. this.depth = depth;
  1519. for ( let i = 0, il = this.texture.length; i < il; i ++ ) {
  1520. this.texture[ i ].image.width = width;
  1521. this.texture[ i ].image.height = height;
  1522. this.texture[ i ].image.depth = depth;
  1523. }
  1524. this.dispose();
  1525. }
  1526. this.viewport.set( 0, 0, width, height );
  1527. this.scissor.set( 0, 0, width, height );
  1528. return this;
  1529. }
  1530. copy( source ) {
  1531. this.dispose();
  1532. this.width = source.width;
  1533. this.height = source.height;
  1534. this.depth = source.depth;
  1535. this.viewport.set( 0, 0, this.width, this.height );
  1536. this.scissor.set( 0, 0, this.width, this.height );
  1537. this.depthBuffer = source.depthBuffer;
  1538. this.stencilBuffer = source.stencilBuffer;
  1539. this.depthTexture = source.depthTexture;
  1540. this.texture.length = 0;
  1541. for ( let i = 0, il = source.texture.length; i < il; i ++ ) {
  1542. this.texture[ i ] = source.texture[ i ].clone();
  1543. }
  1544. return this;
  1545. }
  1546. }
  1547. WebGLMultipleRenderTargets.prototype.isWebGLMultipleRenderTargets = true;
  1548. class WebGLMultisampleRenderTarget extends WebGLRenderTarget {
  1549. constructor( width, height, options ) {
  1550. super( width, height, options );
  1551. this.samples = 4;
  1552. }
  1553. copy( source ) {
  1554. super.copy.call( this, source );
  1555. this.samples = source.samples;
  1556. return this;
  1557. }
  1558. }
  1559. WebGLMultisampleRenderTarget.prototype.isWebGLMultisampleRenderTarget = true;
  1560. class Quaternion {
  1561. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1562. this._x = x;
  1563. this._y = y;
  1564. this._z = z;
  1565. this._w = w;
  1566. }
  1567. static slerp( qa, qb, qm, t ) {
  1568. console.warn( 'THREE.Quaternion: Static .slerp() has been deprecated. Use qm.slerpQuaternions( qa, qb, t ) instead.' );
  1569. return qm.slerpQuaternions( qa, qb, t );
  1570. }
  1571. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1572. // fuzz-free, array-based Quaternion SLERP operation
  1573. let x0 = src0[ srcOffset0 + 0 ],
  1574. y0 = src0[ srcOffset0 + 1 ],
  1575. z0 = src0[ srcOffset0 + 2 ],
  1576. w0 = src0[ srcOffset0 + 3 ];
  1577. const x1 = src1[ srcOffset1 + 0 ],
  1578. y1 = src1[ srcOffset1 + 1 ],
  1579. z1 = src1[ srcOffset1 + 2 ],
  1580. w1 = src1[ srcOffset1 + 3 ];
  1581. if ( t === 0 ) {
  1582. dst[ dstOffset + 0 ] = x0;
  1583. dst[ dstOffset + 1 ] = y0;
  1584. dst[ dstOffset + 2 ] = z0;
  1585. dst[ dstOffset + 3 ] = w0;
  1586. return;
  1587. }
  1588. if ( t === 1 ) {
  1589. dst[ dstOffset + 0 ] = x1;
  1590. dst[ dstOffset + 1 ] = y1;
  1591. dst[ dstOffset + 2 ] = z1;
  1592. dst[ dstOffset + 3 ] = w1;
  1593. return;
  1594. }
  1595. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1596. let s = 1 - t;
  1597. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1598. dir = ( cos >= 0 ? 1 : - 1 ),
  1599. sqrSin = 1 - cos * cos;
  1600. // Skip the Slerp for tiny steps to avoid numeric problems:
  1601. if ( sqrSin > Number.EPSILON ) {
  1602. const sin = Math.sqrt( sqrSin ),
  1603. len = Math.atan2( sin, cos * dir );
  1604. s = Math.sin( s * len ) / sin;
  1605. t = Math.sin( t * len ) / sin;
  1606. }
  1607. const tDir = t * dir;
  1608. x0 = x0 * s + x1 * tDir;
  1609. y0 = y0 * s + y1 * tDir;
  1610. z0 = z0 * s + z1 * tDir;
  1611. w0 = w0 * s + w1 * tDir;
  1612. // Normalize in case we just did a lerp:
  1613. if ( s === 1 - t ) {
  1614. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  1615. x0 *= f;
  1616. y0 *= f;
  1617. z0 *= f;
  1618. w0 *= f;
  1619. }
  1620. }
  1621. dst[ dstOffset ] = x0;
  1622. dst[ dstOffset + 1 ] = y0;
  1623. dst[ dstOffset + 2 ] = z0;
  1624. dst[ dstOffset + 3 ] = w0;
  1625. }
  1626. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  1627. const x0 = src0[ srcOffset0 ];
  1628. const y0 = src0[ srcOffset0 + 1 ];
  1629. const z0 = src0[ srcOffset0 + 2 ];
  1630. const w0 = src0[ srcOffset0 + 3 ];
  1631. const x1 = src1[ srcOffset1 ];
  1632. const y1 = src1[ srcOffset1 + 1 ];
  1633. const z1 = src1[ srcOffset1 + 2 ];
  1634. const w1 = src1[ srcOffset1 + 3 ];
  1635. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  1636. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  1637. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  1638. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  1639. return dst;
  1640. }
  1641. get x() {
  1642. return this._x;
  1643. }
  1644. set x( value ) {
  1645. this._x = value;
  1646. this._onChangeCallback();
  1647. }
  1648. get y() {
  1649. return this._y;
  1650. }
  1651. set y( value ) {
  1652. this._y = value;
  1653. this._onChangeCallback();
  1654. }
  1655. get z() {
  1656. return this._z;
  1657. }
  1658. set z( value ) {
  1659. this._z = value;
  1660. this._onChangeCallback();
  1661. }
  1662. get w() {
  1663. return this._w;
  1664. }
  1665. set w( value ) {
  1666. this._w = value;
  1667. this._onChangeCallback();
  1668. }
  1669. set( x, y, z, w ) {
  1670. this._x = x;
  1671. this._y = y;
  1672. this._z = z;
  1673. this._w = w;
  1674. this._onChangeCallback();
  1675. return this;
  1676. }
  1677. clone() {
  1678. return new this.constructor( this._x, this._y, this._z, this._w );
  1679. }
  1680. copy( quaternion ) {
  1681. this._x = quaternion.x;
  1682. this._y = quaternion.y;
  1683. this._z = quaternion.z;
  1684. this._w = quaternion.w;
  1685. this._onChangeCallback();
  1686. return this;
  1687. }
  1688. setFromEuler( euler, update ) {
  1689. if ( ! ( euler && euler.isEuler ) ) {
  1690. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  1691. }
  1692. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  1693. // http://www.mathworks.com/matlabcentral/fileexchange/
  1694. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1695. // content/SpinCalc.m
  1696. const cos = Math.cos;
  1697. const sin = Math.sin;
  1698. const c1 = cos( x / 2 );
  1699. const c2 = cos( y / 2 );
  1700. const c3 = cos( z / 2 );
  1701. const s1 = sin( x / 2 );
  1702. const s2 = sin( y / 2 );
  1703. const s3 = sin( z / 2 );
  1704. switch ( order ) {
  1705. case 'XYZ':
  1706. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1707. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1708. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1709. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1710. break;
  1711. case 'YXZ':
  1712. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1713. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1714. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1715. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1716. break;
  1717. case 'ZXY':
  1718. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1719. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1720. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1721. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1722. break;
  1723. case 'ZYX':
  1724. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1725. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1726. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1727. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1728. break;
  1729. case 'YZX':
  1730. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1731. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1732. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1733. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1734. break;
  1735. case 'XZY':
  1736. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1737. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1738. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1739. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1740. break;
  1741. default:
  1742. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  1743. }
  1744. if ( update !== false ) this._onChangeCallback();
  1745. return this;
  1746. }
  1747. setFromAxisAngle( axis, angle ) {
  1748. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  1749. // assumes axis is normalized
  1750. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  1751. this._x = axis.x * s;
  1752. this._y = axis.y * s;
  1753. this._z = axis.z * s;
  1754. this._w = Math.cos( halfAngle );
  1755. this._onChangeCallback();
  1756. return this;
  1757. }
  1758. setFromRotationMatrix( m ) {
  1759. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  1760. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1761. const te = m.elements,
  1762. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1763. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1764. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  1765. trace = m11 + m22 + m33;
  1766. if ( trace > 0 ) {
  1767. const s = 0.5 / Math.sqrt( trace + 1.0 );
  1768. this._w = 0.25 / s;
  1769. this._x = ( m32 - m23 ) * s;
  1770. this._y = ( m13 - m31 ) * s;
  1771. this._z = ( m21 - m12 ) * s;
  1772. } else if ( m11 > m22 && m11 > m33 ) {
  1773. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  1774. this._w = ( m32 - m23 ) / s;
  1775. this._x = 0.25 * s;
  1776. this._y = ( m12 + m21 ) / s;
  1777. this._z = ( m13 + m31 ) / s;
  1778. } else if ( m22 > m33 ) {
  1779. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  1780. this._w = ( m13 - m31 ) / s;
  1781. this._x = ( m12 + m21 ) / s;
  1782. this._y = 0.25 * s;
  1783. this._z = ( m23 + m32 ) / s;
  1784. } else {
  1785. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  1786. this._w = ( m21 - m12 ) / s;
  1787. this._x = ( m13 + m31 ) / s;
  1788. this._y = ( m23 + m32 ) / s;
  1789. this._z = 0.25 * s;
  1790. }
  1791. this._onChangeCallback();
  1792. return this;
  1793. }
  1794. setFromUnitVectors( vFrom, vTo ) {
  1795. // assumes direction vectors vFrom and vTo are normalized
  1796. let r = vFrom.dot( vTo ) + 1;
  1797. if ( r < Number.EPSILON ) {
  1798. // vFrom and vTo point in opposite directions
  1799. r = 0;
  1800. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  1801. this._x = - vFrom.y;
  1802. this._y = vFrom.x;
  1803. this._z = 0;
  1804. this._w = r;
  1805. } else {
  1806. this._x = 0;
  1807. this._y = - vFrom.z;
  1808. this._z = vFrom.y;
  1809. this._w = r;
  1810. }
  1811. } else {
  1812. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  1813. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  1814. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  1815. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  1816. this._w = r;
  1817. }
  1818. return this.normalize();
  1819. }
  1820. angleTo( q ) {
  1821. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) );
  1822. }
  1823. rotateTowards( q, step ) {
  1824. const angle = this.angleTo( q );
  1825. if ( angle === 0 ) return this;
  1826. const t = Math.min( 1, step / angle );
  1827. this.slerp( q, t );
  1828. return this;
  1829. }
  1830. identity() {
  1831. return this.set( 0, 0, 0, 1 );
  1832. }
  1833. invert() {
  1834. // quaternion is assumed to have unit length
  1835. return this.conjugate();
  1836. }
  1837. conjugate() {
  1838. this._x *= - 1;
  1839. this._y *= - 1;
  1840. this._z *= - 1;
  1841. this._onChangeCallback();
  1842. return this;
  1843. }
  1844. dot( v ) {
  1845. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  1846. }
  1847. lengthSq() {
  1848. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  1849. }
  1850. length() {
  1851. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  1852. }
  1853. normalize() {
  1854. let l = this.length();
  1855. if ( l === 0 ) {
  1856. this._x = 0;
  1857. this._y = 0;
  1858. this._z = 0;
  1859. this._w = 1;
  1860. } else {
  1861. l = 1 / l;
  1862. this._x = this._x * l;
  1863. this._y = this._y * l;
  1864. this._z = this._z * l;
  1865. this._w = this._w * l;
  1866. }
  1867. this._onChangeCallback();
  1868. return this;
  1869. }
  1870. multiply( q, p ) {
  1871. if ( p !== undefined ) {
  1872. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  1873. return this.multiplyQuaternions( q, p );
  1874. }
  1875. return this.multiplyQuaternions( this, q );
  1876. }
  1877. premultiply( q ) {
  1878. return this.multiplyQuaternions( q, this );
  1879. }
  1880. multiplyQuaternions( a, b ) {
  1881. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  1882. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  1883. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  1884. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  1885. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  1886. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  1887. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  1888. this._onChangeCallback();
  1889. return this;
  1890. }
  1891. slerp( qb, t ) {
  1892. if ( t === 0 ) return this;
  1893. if ( t === 1 ) return this.copy( qb );
  1894. const x = this._x, y = this._y, z = this._z, w = this._w;
  1895. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  1896. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  1897. if ( cosHalfTheta < 0 ) {
  1898. this._w = - qb._w;
  1899. this._x = - qb._x;
  1900. this._y = - qb._y;
  1901. this._z = - qb._z;
  1902. cosHalfTheta = - cosHalfTheta;
  1903. } else {
  1904. this.copy( qb );
  1905. }
  1906. if ( cosHalfTheta >= 1.0 ) {
  1907. this._w = w;
  1908. this._x = x;
  1909. this._y = y;
  1910. this._z = z;
  1911. return this;
  1912. }
  1913. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  1914. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  1915. const s = 1 - t;
  1916. this._w = s * w + t * this._w;
  1917. this._x = s * x + t * this._x;
  1918. this._y = s * y + t * this._y;
  1919. this._z = s * z + t * this._z;
  1920. this.normalize();
  1921. this._onChangeCallback();
  1922. return this;
  1923. }
  1924. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  1925. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  1926. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  1927. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  1928. this._w = ( w * ratioA + this._w * ratioB );
  1929. this._x = ( x * ratioA + this._x * ratioB );
  1930. this._y = ( y * ratioA + this._y * ratioB );
  1931. this._z = ( z * ratioA + this._z * ratioB );
  1932. this._onChangeCallback();
  1933. return this;
  1934. }
  1935. slerpQuaternions( qa, qb, t ) {
  1936. this.copy( qa ).slerp( qb, t );
  1937. }
  1938. equals( quaternion ) {
  1939. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  1940. }
  1941. fromArray( array, offset = 0 ) {
  1942. this._x = array[ offset ];
  1943. this._y = array[ offset + 1 ];
  1944. this._z = array[ offset + 2 ];
  1945. this._w = array[ offset + 3 ];
  1946. this._onChangeCallback();
  1947. return this;
  1948. }
  1949. toArray( array = [], offset = 0 ) {
  1950. array[ offset ] = this._x;
  1951. array[ offset + 1 ] = this._y;
  1952. array[ offset + 2 ] = this._z;
  1953. array[ offset + 3 ] = this._w;
  1954. return array;
  1955. }
  1956. fromBufferAttribute( attribute, index ) {
  1957. this._x = attribute.getX( index );
  1958. this._y = attribute.getY( index );
  1959. this._z = attribute.getZ( index );
  1960. this._w = attribute.getW( index );
  1961. return this;
  1962. }
  1963. _onChange( callback ) {
  1964. this._onChangeCallback = callback;
  1965. return this;
  1966. }
  1967. _onChangeCallback() {}
  1968. }
  1969. Quaternion.prototype.isQuaternion = true;
  1970. class Vector3 {
  1971. constructor( x = 0, y = 0, z = 0 ) {
  1972. this.x = x;
  1973. this.y = y;
  1974. this.z = z;
  1975. }
  1976. set( x, y, z ) {
  1977. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  1978. this.x = x;
  1979. this.y = y;
  1980. this.z = z;
  1981. return this;
  1982. }
  1983. setScalar( scalar ) {
  1984. this.x = scalar;
  1985. this.y = scalar;
  1986. this.z = scalar;
  1987. return this;
  1988. }
  1989. setX( x ) {
  1990. this.x = x;
  1991. return this;
  1992. }
  1993. setY( y ) {
  1994. this.y = y;
  1995. return this;
  1996. }
  1997. setZ( z ) {
  1998. this.z = z;
  1999. return this;
  2000. }
  2001. setComponent( index, value ) {
  2002. switch ( index ) {
  2003. case 0: this.x = value; break;
  2004. case 1: this.y = value; break;
  2005. case 2: this.z = value; break;
  2006. default: throw new Error( 'index is out of range: ' + index );
  2007. }
  2008. return this;
  2009. }
  2010. getComponent( index ) {
  2011. switch ( index ) {
  2012. case 0: return this.x;
  2013. case 1: return this.y;
  2014. case 2: return this.z;
  2015. default: throw new Error( 'index is out of range: ' + index );
  2016. }
  2017. }
  2018. clone() {
  2019. return new this.constructor( this.x, this.y, this.z );
  2020. }
  2021. copy( v ) {
  2022. this.x = v.x;
  2023. this.y = v.y;
  2024. this.z = v.z;
  2025. return this;
  2026. }
  2027. add( v, w ) {
  2028. if ( w !== undefined ) {
  2029. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  2030. return this.addVectors( v, w );
  2031. }
  2032. this.x += v.x;
  2033. this.y += v.y;
  2034. this.z += v.z;
  2035. return this;
  2036. }
  2037. addScalar( s ) {
  2038. this.x += s;
  2039. this.y += s;
  2040. this.z += s;
  2041. return this;
  2042. }
  2043. addVectors( a, b ) {
  2044. this.x = a.x + b.x;
  2045. this.y = a.y + b.y;
  2046. this.z = a.z + b.z;
  2047. return this;
  2048. }
  2049. addScaledVector( v, s ) {
  2050. this.x += v.x * s;
  2051. this.y += v.y * s;
  2052. this.z += v.z * s;
  2053. return this;
  2054. }
  2055. sub( v, w ) {
  2056. if ( w !== undefined ) {
  2057. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  2058. return this.subVectors( v, w );
  2059. }
  2060. this.x -= v.x;
  2061. this.y -= v.y;
  2062. this.z -= v.z;
  2063. return this;
  2064. }
  2065. subScalar( s ) {
  2066. this.x -= s;
  2067. this.y -= s;
  2068. this.z -= s;
  2069. return this;
  2070. }
  2071. subVectors( a, b ) {
  2072. this.x = a.x - b.x;
  2073. this.y = a.y - b.y;
  2074. this.z = a.z - b.z;
  2075. return this;
  2076. }
  2077. multiply( v, w ) {
  2078. if ( w !== undefined ) {
  2079. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  2080. return this.multiplyVectors( v, w );
  2081. }
  2082. this.x *= v.x;
  2083. this.y *= v.y;
  2084. this.z *= v.z;
  2085. return this;
  2086. }
  2087. multiplyScalar( scalar ) {
  2088. this.x *= scalar;
  2089. this.y *= scalar;
  2090. this.z *= scalar;
  2091. return this;
  2092. }
  2093. multiplyVectors( a, b ) {
  2094. this.x = a.x * b.x;
  2095. this.y = a.y * b.y;
  2096. this.z = a.z * b.z;
  2097. return this;
  2098. }
  2099. applyEuler( euler ) {
  2100. if ( ! ( euler && euler.isEuler ) ) {
  2101. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  2102. }
  2103. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  2104. }
  2105. applyAxisAngle( axis, angle ) {
  2106. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  2107. }
  2108. applyMatrix3( m ) {
  2109. const x = this.x, y = this.y, z = this.z;
  2110. const e = m.elements;
  2111. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2112. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2113. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2114. return this;
  2115. }
  2116. applyNormalMatrix( m ) {
  2117. return this.applyMatrix3( m ).normalize();
  2118. }
  2119. applyMatrix4( m ) {
  2120. const x = this.x, y = this.y, z = this.z;
  2121. const e = m.elements;
  2122. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2123. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2124. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2125. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2126. return this;
  2127. }
  2128. applyQuaternion( q ) {
  2129. const x = this.x, y = this.y, z = this.z;
  2130. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2131. // calculate quat * vector
  2132. const ix = qw * x + qy * z - qz * y;
  2133. const iy = qw * y + qz * x - qx * z;
  2134. const iz = qw * z + qx * y - qy * x;
  2135. const iw = - qx * x - qy * y - qz * z;
  2136. // calculate result * inverse quat
  2137. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  2138. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  2139. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  2140. return this;
  2141. }
  2142. project( camera ) {
  2143. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2144. }
  2145. unproject( camera ) {
  2146. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2147. }
  2148. transformDirection( m ) {
  2149. // input: THREE.Matrix4 affine matrix
  2150. // vector interpreted as a direction
  2151. const x = this.x, y = this.y, z = this.z;
  2152. const e = m.elements;
  2153. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2154. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2155. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2156. return this.normalize();
  2157. }
  2158. divide( v ) {
  2159. this.x /= v.x;
  2160. this.y /= v.y;
  2161. this.z /= v.z;
  2162. return this;
  2163. }
  2164. divideScalar( scalar ) {
  2165. return this.multiplyScalar( 1 / scalar );
  2166. }
  2167. min( v ) {
  2168. this.x = Math.min( this.x, v.x );
  2169. this.y = Math.min( this.y, v.y );
  2170. this.z = Math.min( this.z, v.z );
  2171. return this;
  2172. }
  2173. max( v ) {
  2174. this.x = Math.max( this.x, v.x );
  2175. this.y = Math.max( this.y, v.y );
  2176. this.z = Math.max( this.z, v.z );
  2177. return this;
  2178. }
  2179. clamp( min, max ) {
  2180. // assumes min < max, componentwise
  2181. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2182. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2183. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2184. return this;
  2185. }
  2186. clampScalar( minVal, maxVal ) {
  2187. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2188. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2189. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2190. return this;
  2191. }
  2192. clampLength( min, max ) {
  2193. const length = this.length();
  2194. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2195. }
  2196. floor() {
  2197. this.x = Math.floor( this.x );
  2198. this.y = Math.floor( this.y );
  2199. this.z = Math.floor( this.z );
  2200. return this;
  2201. }
  2202. ceil() {
  2203. this.x = Math.ceil( this.x );
  2204. this.y = Math.ceil( this.y );
  2205. this.z = Math.ceil( this.z );
  2206. return this;
  2207. }
  2208. round() {
  2209. this.x = Math.round( this.x );
  2210. this.y = Math.round( this.y );
  2211. this.z = Math.round( this.z );
  2212. return this;
  2213. }
  2214. roundToZero() {
  2215. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  2216. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  2217. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  2218. return this;
  2219. }
  2220. negate() {
  2221. this.x = - this.x;
  2222. this.y = - this.y;
  2223. this.z = - this.z;
  2224. return this;
  2225. }
  2226. dot( v ) {
  2227. return this.x * v.x + this.y * v.y + this.z * v.z;
  2228. }
  2229. // TODO lengthSquared?
  2230. lengthSq() {
  2231. return this.x * this.x + this.y * this.y + this.z * this.z;
  2232. }
  2233. length() {
  2234. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2235. }
  2236. manhattanLength() {
  2237. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2238. }
  2239. normalize() {
  2240. return this.divideScalar( this.length() || 1 );
  2241. }
  2242. setLength( length ) {
  2243. return this.normalize().multiplyScalar( length );
  2244. }
  2245. lerp( v, alpha ) {
  2246. this.x += ( v.x - this.x ) * alpha;
  2247. this.y += ( v.y - this.y ) * alpha;
  2248. this.z += ( v.z - this.z ) * alpha;
  2249. return this;
  2250. }
  2251. lerpVectors( v1, v2, alpha ) {
  2252. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2253. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2254. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2255. return this;
  2256. }
  2257. cross( v, w ) {
  2258. if ( w !== undefined ) {
  2259. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  2260. return this.crossVectors( v, w );
  2261. }
  2262. return this.crossVectors( this, v );
  2263. }
  2264. crossVectors( a, b ) {
  2265. const ax = a.x, ay = a.y, az = a.z;
  2266. const bx = b.x, by = b.y, bz = b.z;
  2267. this.x = ay * bz - az * by;
  2268. this.y = az * bx - ax * bz;
  2269. this.z = ax * by - ay * bx;
  2270. return this;
  2271. }
  2272. projectOnVector( v ) {
  2273. const denominator = v.lengthSq();
  2274. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2275. const scalar = v.dot( this ) / denominator;
  2276. return this.copy( v ).multiplyScalar( scalar );
  2277. }
  2278. projectOnPlane( planeNormal ) {
  2279. _vector$c.copy( this ).projectOnVector( planeNormal );
  2280. return this.sub( _vector$c );
  2281. }
  2282. reflect( normal ) {
  2283. // reflect incident vector off plane orthogonal to normal
  2284. // normal is assumed to have unit length
  2285. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2286. }
  2287. angleTo( v ) {
  2288. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2289. if ( denominator === 0 ) return Math.PI / 2;
  2290. const theta = this.dot( v ) / denominator;
  2291. // clamp, to handle numerical problems
  2292. return Math.acos( clamp( theta, - 1, 1 ) );
  2293. }
  2294. distanceTo( v ) {
  2295. return Math.sqrt( this.distanceToSquared( v ) );
  2296. }
  2297. distanceToSquared( v ) {
  2298. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2299. return dx * dx + dy * dy + dz * dz;
  2300. }
  2301. manhattanDistanceTo( v ) {
  2302. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2303. }
  2304. setFromSpherical( s ) {
  2305. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2306. }
  2307. setFromSphericalCoords( radius, phi, theta ) {
  2308. const sinPhiRadius = Math.sin( phi ) * radius;
  2309. this.x = sinPhiRadius * Math.sin( theta );
  2310. this.y = Math.cos( phi ) * radius;
  2311. this.z = sinPhiRadius * Math.cos( theta );
  2312. return this;
  2313. }
  2314. setFromCylindrical( c ) {
  2315. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2316. }
  2317. setFromCylindricalCoords( radius, theta, y ) {
  2318. this.x = radius * Math.sin( theta );
  2319. this.y = y;
  2320. this.z = radius * Math.cos( theta );
  2321. return this;
  2322. }
  2323. setFromMatrixPosition( m ) {
  2324. const e = m.elements;
  2325. this.x = e[ 12 ];
  2326. this.y = e[ 13 ];
  2327. this.z = e[ 14 ];
  2328. return this;
  2329. }
  2330. setFromMatrixScale( m ) {
  2331. const sx = this.setFromMatrixColumn( m, 0 ).length();
  2332. const sy = this.setFromMatrixColumn( m, 1 ).length();
  2333. const sz = this.setFromMatrixColumn( m, 2 ).length();
  2334. this.x = sx;
  2335. this.y = sy;
  2336. this.z = sz;
  2337. return this;
  2338. }
  2339. setFromMatrixColumn( m, index ) {
  2340. return this.fromArray( m.elements, index * 4 );
  2341. }
  2342. setFromMatrix3Column( m, index ) {
  2343. return this.fromArray( m.elements, index * 3 );
  2344. }
  2345. equals( v ) {
  2346. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2347. }
  2348. fromArray( array, offset = 0 ) {
  2349. this.x = array[ offset ];
  2350. this.y = array[ offset + 1 ];
  2351. this.z = array[ offset + 2 ];
  2352. return this;
  2353. }
  2354. toArray( array = [], offset = 0 ) {
  2355. array[ offset ] = this.x;
  2356. array[ offset + 1 ] = this.y;
  2357. array[ offset + 2 ] = this.z;
  2358. return array;
  2359. }
  2360. fromBufferAttribute( attribute, index, offset ) {
  2361. if ( offset !== undefined ) {
  2362. console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' );
  2363. }
  2364. this.x = attribute.getX( index );
  2365. this.y = attribute.getY( index );
  2366. this.z = attribute.getZ( index );
  2367. return this;
  2368. }
  2369. random() {
  2370. this.x = Math.random();
  2371. this.y = Math.random();
  2372. this.z = Math.random();
  2373. return this;
  2374. }
  2375. }
  2376. Vector3.prototype.isVector3 = true;
  2377. const _vector$c = /*@__PURE__*/ new Vector3();
  2378. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  2379. class Box3 {
  2380. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  2381. this.min = min;
  2382. this.max = max;
  2383. }
  2384. set( min, max ) {
  2385. this.min.copy( min );
  2386. this.max.copy( max );
  2387. return this;
  2388. }
  2389. setFromArray( array ) {
  2390. let minX = + Infinity;
  2391. let minY = + Infinity;
  2392. let minZ = + Infinity;
  2393. let maxX = - Infinity;
  2394. let maxY = - Infinity;
  2395. let maxZ = - Infinity;
  2396. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  2397. const x = array[ i ];
  2398. const y = array[ i + 1 ];
  2399. const z = array[ i + 2 ];
  2400. if ( x < minX ) minX = x;
  2401. if ( y < minY ) minY = y;
  2402. if ( z < minZ ) minZ = z;
  2403. if ( x > maxX ) maxX = x;
  2404. if ( y > maxY ) maxY = y;
  2405. if ( z > maxZ ) maxZ = z;
  2406. }
  2407. this.min.set( minX, minY, minZ );
  2408. this.max.set( maxX, maxY, maxZ );
  2409. return this;
  2410. }
  2411. setFromBufferAttribute( attribute ) {
  2412. let minX = + Infinity;
  2413. let minY = + Infinity;
  2414. let minZ = + Infinity;
  2415. let maxX = - Infinity;
  2416. let maxY = - Infinity;
  2417. let maxZ = - Infinity;
  2418. for ( let i = 0, l = attribute.count; i < l; i ++ ) {
  2419. const x = attribute.getX( i );
  2420. const y = attribute.getY( i );
  2421. const z = attribute.getZ( i );
  2422. if ( x < minX ) minX = x;
  2423. if ( y < minY ) minY = y;
  2424. if ( z < minZ ) minZ = z;
  2425. if ( x > maxX ) maxX = x;
  2426. if ( y > maxY ) maxY = y;
  2427. if ( z > maxZ ) maxZ = z;
  2428. }
  2429. this.min.set( minX, minY, minZ );
  2430. this.max.set( maxX, maxY, maxZ );
  2431. return this;
  2432. }
  2433. setFromPoints( points ) {
  2434. this.makeEmpty();
  2435. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2436. this.expandByPoint( points[ i ] );
  2437. }
  2438. return this;
  2439. }
  2440. setFromCenterAndSize( center, size ) {
  2441. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  2442. this.min.copy( center ).sub( halfSize );
  2443. this.max.copy( center ).add( halfSize );
  2444. return this;
  2445. }
  2446. setFromObject( object ) {
  2447. this.makeEmpty();
  2448. return this.expandByObject( object );
  2449. }
  2450. clone() {
  2451. return new this.constructor().copy( this );
  2452. }
  2453. copy( box ) {
  2454. this.min.copy( box.min );
  2455. this.max.copy( box.max );
  2456. return this;
  2457. }
  2458. makeEmpty() {
  2459. this.min.x = this.min.y = this.min.z = + Infinity;
  2460. this.max.x = this.max.y = this.max.z = - Infinity;
  2461. return this;
  2462. }
  2463. isEmpty() {
  2464. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2465. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2466. }
  2467. getCenter( target ) {
  2468. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2469. }
  2470. getSize( target ) {
  2471. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  2472. }
  2473. expandByPoint( point ) {
  2474. this.min.min( point );
  2475. this.max.max( point );
  2476. return this;
  2477. }
  2478. expandByVector( vector ) {
  2479. this.min.sub( vector );
  2480. this.max.add( vector );
  2481. return this;
  2482. }
  2483. expandByScalar( scalar ) {
  2484. this.min.addScalar( - scalar );
  2485. this.max.addScalar( scalar );
  2486. return this;
  2487. }
  2488. expandByObject( object ) {
  2489. // Computes the world-axis-aligned bounding box of an object (including its children),
  2490. // accounting for both the object's, and children's, world transforms
  2491. object.updateWorldMatrix( false, false );
  2492. const geometry = object.geometry;
  2493. if ( geometry !== undefined ) {
  2494. if ( geometry.boundingBox === null ) {
  2495. geometry.computeBoundingBox();
  2496. }
  2497. _box$3.copy( geometry.boundingBox );
  2498. _box$3.applyMatrix4( object.matrixWorld );
  2499. this.union( _box$3 );
  2500. }
  2501. const children = object.children;
  2502. for ( let i = 0, l = children.length; i < l; i ++ ) {
  2503. this.expandByObject( children[ i ] );
  2504. }
  2505. return this;
  2506. }
  2507. containsPoint( point ) {
  2508. return point.x < this.min.x || point.x > this.max.x ||
  2509. point.y < this.min.y || point.y > this.max.y ||
  2510. point.z < this.min.z || point.z > this.max.z ? false : true;
  2511. }
  2512. containsBox( box ) {
  2513. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  2514. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  2515. this.min.z <= box.min.z && box.max.z <= this.max.z;
  2516. }
  2517. getParameter( point, target ) {
  2518. // This can potentially have a divide by zero if the box
  2519. // has a size dimension of 0.
  2520. return target.set(
  2521. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2522. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2523. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2524. );
  2525. }
  2526. intersectsBox( box ) {
  2527. // using 6 splitting planes to rule out intersections.
  2528. return box.max.x < this.min.x || box.min.x > this.max.x ||
  2529. box.max.y < this.min.y || box.min.y > this.max.y ||
  2530. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  2531. }
  2532. intersectsSphere( sphere ) {
  2533. // Find the point on the AABB closest to the sphere center.
  2534. this.clampPoint( sphere.center, _vector$b );
  2535. // If that point is inside the sphere, the AABB and sphere intersect.
  2536. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  2537. }
  2538. intersectsPlane( plane ) {
  2539. // We compute the minimum and maximum dot product values. If those values
  2540. // are on the same side (back or front) of the plane, then there is no intersection.
  2541. let min, max;
  2542. if ( plane.normal.x > 0 ) {
  2543. min = plane.normal.x * this.min.x;
  2544. max = plane.normal.x * this.max.x;
  2545. } else {
  2546. min = plane.normal.x * this.max.x;
  2547. max = plane.normal.x * this.min.x;
  2548. }
  2549. if ( plane.normal.y > 0 ) {
  2550. min += plane.normal.y * this.min.y;
  2551. max += plane.normal.y * this.max.y;
  2552. } else {
  2553. min += plane.normal.y * this.max.y;
  2554. max += plane.normal.y * this.min.y;
  2555. }
  2556. if ( plane.normal.z > 0 ) {
  2557. min += plane.normal.z * this.min.z;
  2558. max += plane.normal.z * this.max.z;
  2559. } else {
  2560. min += plane.normal.z * this.max.z;
  2561. max += plane.normal.z * this.min.z;
  2562. }
  2563. return ( min <= - plane.constant && max >= - plane.constant );
  2564. }
  2565. intersectsTriangle( triangle ) {
  2566. if ( this.isEmpty() ) {
  2567. return false;
  2568. }
  2569. // compute box center and extents
  2570. this.getCenter( _center );
  2571. _extents.subVectors( this.max, _center );
  2572. // translate triangle to aabb origin
  2573. _v0$2.subVectors( triangle.a, _center );
  2574. _v1$7.subVectors( triangle.b, _center );
  2575. _v2$3.subVectors( triangle.c, _center );
  2576. // compute edge vectors for triangle
  2577. _f0.subVectors( _v1$7, _v0$2 );
  2578. _f1.subVectors( _v2$3, _v1$7 );
  2579. _f2.subVectors( _v0$2, _v2$3 );
  2580. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  2581. // 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
  2582. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2583. let axes = [
  2584. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  2585. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  2586. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  2587. ];
  2588. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents ) ) {
  2589. return false;
  2590. }
  2591. // test 3 face normals from the aabb
  2592. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  2593. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents ) ) {
  2594. return false;
  2595. }
  2596. // finally testing the face normal of the triangle
  2597. // use already existing triangle edge vectors here
  2598. _triangleNormal.crossVectors( _f0, _f1 );
  2599. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  2600. return satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents );
  2601. }
  2602. clampPoint( point, target ) {
  2603. return target.copy( point ).clamp( this.min, this.max );
  2604. }
  2605. distanceToPoint( point ) {
  2606. const clampedPoint = _vector$b.copy( point ).clamp( this.min, this.max );
  2607. return clampedPoint.sub( point ).length();
  2608. }
  2609. getBoundingSphere( target ) {
  2610. this.getCenter( target.center );
  2611. target.radius = this.getSize( _vector$b ).length() * 0.5;
  2612. return target;
  2613. }
  2614. intersect( box ) {
  2615. this.min.max( box.min );
  2616. this.max.min( box.max );
  2617. // 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.
  2618. if ( this.isEmpty() ) this.makeEmpty();
  2619. return this;
  2620. }
  2621. union( box ) {
  2622. this.min.min( box.min );
  2623. this.max.max( box.max );
  2624. return this;
  2625. }
  2626. applyMatrix4( matrix ) {
  2627. // transform of empty box is an empty box.
  2628. if ( this.isEmpty() ) return this;
  2629. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2630. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2631. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2632. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2633. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2634. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2635. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2636. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2637. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2638. this.setFromPoints( _points );
  2639. return this;
  2640. }
  2641. translate( offset ) {
  2642. this.min.add( offset );
  2643. this.max.add( offset );
  2644. return this;
  2645. }
  2646. equals( box ) {
  2647. return box.min.equals( this.min ) && box.max.equals( this.max );
  2648. }
  2649. }
  2650. Box3.prototype.isBox3 = true;
  2651. const _points = [
  2652. /*@__PURE__*/ new Vector3(),
  2653. /*@__PURE__*/ new Vector3(),
  2654. /*@__PURE__*/ new Vector3(),
  2655. /*@__PURE__*/ new Vector3(),
  2656. /*@__PURE__*/ new Vector3(),
  2657. /*@__PURE__*/ new Vector3(),
  2658. /*@__PURE__*/ new Vector3(),
  2659. /*@__PURE__*/ new Vector3()
  2660. ];
  2661. const _vector$b = /*@__PURE__*/ new Vector3();
  2662. const _box$3 = /*@__PURE__*/ new Box3();
  2663. // triangle centered vertices
  2664. const _v0$2 = /*@__PURE__*/ new Vector3();
  2665. const _v1$7 = /*@__PURE__*/ new Vector3();
  2666. const _v2$3 = /*@__PURE__*/ new Vector3();
  2667. // triangle edge vectors
  2668. const _f0 = /*@__PURE__*/ new Vector3();
  2669. const _f1 = /*@__PURE__*/ new Vector3();
  2670. const _f2 = /*@__PURE__*/ new Vector3();
  2671. const _center = /*@__PURE__*/ new Vector3();
  2672. const _extents = /*@__PURE__*/ new Vector3();
  2673. const _triangleNormal = /*@__PURE__*/ new Vector3();
  2674. const _testAxis = /*@__PURE__*/ new Vector3();
  2675. function satForAxes( axes, v0, v1, v2, extents ) {
  2676. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  2677. _testAxis.fromArray( axes, i );
  2678. // project the aabb onto the seperating axis
  2679. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  2680. // project all 3 vertices of the triangle onto the seperating axis
  2681. const p0 = v0.dot( _testAxis );
  2682. const p1 = v1.dot( _testAxis );
  2683. const p2 = v2.dot( _testAxis );
  2684. // actual test, basically see if either of the most extreme of the triangle points intersects r
  2685. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  2686. // points of the projected triangle are outside the projected half-length of the aabb
  2687. // the axis is seperating and we can exit
  2688. return false;
  2689. }
  2690. }
  2691. return true;
  2692. }
  2693. const _box$2 = /*@__PURE__*/ new Box3();
  2694. const _v1$6 = /*@__PURE__*/ new Vector3();
  2695. const _toFarthestPoint = /*@__PURE__*/ new Vector3();
  2696. const _toPoint = /*@__PURE__*/ new Vector3();
  2697. class Sphere {
  2698. constructor( center = new Vector3(), radius = - 1 ) {
  2699. this.center = center;
  2700. this.radius = radius;
  2701. }
  2702. set( center, radius ) {
  2703. this.center.copy( center );
  2704. this.radius = radius;
  2705. return this;
  2706. }
  2707. setFromPoints( points, optionalCenter ) {
  2708. const center = this.center;
  2709. if ( optionalCenter !== undefined ) {
  2710. center.copy( optionalCenter );
  2711. } else {
  2712. _box$2.setFromPoints( points ).getCenter( center );
  2713. }
  2714. let maxRadiusSq = 0;
  2715. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2716. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  2717. }
  2718. this.radius = Math.sqrt( maxRadiusSq );
  2719. return this;
  2720. }
  2721. copy( sphere ) {
  2722. this.center.copy( sphere.center );
  2723. this.radius = sphere.radius;
  2724. return this;
  2725. }
  2726. isEmpty() {
  2727. return ( this.radius < 0 );
  2728. }
  2729. makeEmpty() {
  2730. this.center.set( 0, 0, 0 );
  2731. this.radius = - 1;
  2732. return this;
  2733. }
  2734. containsPoint( point ) {
  2735. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  2736. }
  2737. distanceToPoint( point ) {
  2738. return ( point.distanceTo( this.center ) - this.radius );
  2739. }
  2740. intersectsSphere( sphere ) {
  2741. const radiusSum = this.radius + sphere.radius;
  2742. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  2743. }
  2744. intersectsBox( box ) {
  2745. return box.intersectsSphere( this );
  2746. }
  2747. intersectsPlane( plane ) {
  2748. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  2749. }
  2750. clampPoint( point, target ) {
  2751. const deltaLengthSq = this.center.distanceToSquared( point );
  2752. target.copy( point );
  2753. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  2754. target.sub( this.center ).normalize();
  2755. target.multiplyScalar( this.radius ).add( this.center );
  2756. }
  2757. return target;
  2758. }
  2759. getBoundingBox( target ) {
  2760. if ( this.isEmpty() ) {
  2761. // Empty sphere produces empty bounding box
  2762. target.makeEmpty();
  2763. return target;
  2764. }
  2765. target.set( this.center, this.center );
  2766. target.expandByScalar( this.radius );
  2767. return target;
  2768. }
  2769. applyMatrix4( matrix ) {
  2770. this.center.applyMatrix4( matrix );
  2771. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  2772. return this;
  2773. }
  2774. translate( offset ) {
  2775. this.center.add( offset );
  2776. return this;
  2777. }
  2778. expandByPoint( point ) {
  2779. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L649-L671
  2780. _toPoint.subVectors( point, this.center );
  2781. const lengthSq = _toPoint.lengthSq();
  2782. if ( lengthSq > ( this.radius * this.radius ) ) {
  2783. const length = Math.sqrt( lengthSq );
  2784. const missingRadiusHalf = ( length - this.radius ) * 0.5;
  2785. // Nudge this sphere towards the target point. Add half the missing distance to radius,
  2786. // and the other half to position. This gives a tighter enclosure, instead of if
  2787. // the whole missing distance were just added to radius.
  2788. this.center.add( _toPoint.multiplyScalar( missingRadiusHalf / length ) );
  2789. this.radius += missingRadiusHalf;
  2790. }
  2791. return this;
  2792. }
  2793. union( sphere ) {
  2794. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L759-L769
  2795. // To enclose another sphere into this sphere, we only need to enclose two points:
  2796. // 1) Enclose the farthest point on the other sphere into this sphere.
  2797. // 2) Enclose the opposite point of the farthest point into this sphere.
  2798. _toFarthestPoint.subVectors( sphere.center, this.center ).normalize().multiplyScalar( sphere.radius );
  2799. this.expandByPoint( _v1$6.copy( sphere.center ).add( _toFarthestPoint ) );
  2800. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _toFarthestPoint ) );
  2801. return this;
  2802. }
  2803. equals( sphere ) {
  2804. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  2805. }
  2806. clone() {
  2807. return new this.constructor().copy( this );
  2808. }
  2809. }
  2810. const _vector$a = /*@__PURE__*/ new Vector3();
  2811. const _segCenter = /*@__PURE__*/ new Vector3();
  2812. const _segDir = /*@__PURE__*/ new Vector3();
  2813. const _diff = /*@__PURE__*/ new Vector3();
  2814. const _edge1 = /*@__PURE__*/ new Vector3();
  2815. const _edge2 = /*@__PURE__*/ new Vector3();
  2816. const _normal$1 = /*@__PURE__*/ new Vector3();
  2817. class Ray {
  2818. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  2819. this.origin = origin;
  2820. this.direction = direction;
  2821. }
  2822. set( origin, direction ) {
  2823. this.origin.copy( origin );
  2824. this.direction.copy( direction );
  2825. return this;
  2826. }
  2827. copy( ray ) {
  2828. this.origin.copy( ray.origin );
  2829. this.direction.copy( ray.direction );
  2830. return this;
  2831. }
  2832. at( t, target ) {
  2833. return target.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  2834. }
  2835. lookAt( v ) {
  2836. this.direction.copy( v ).sub( this.origin ).normalize();
  2837. return this;
  2838. }
  2839. recast( t ) {
  2840. this.origin.copy( this.at( t, _vector$a ) );
  2841. return this;
  2842. }
  2843. closestPointToPoint( point, target ) {
  2844. target.subVectors( point, this.origin );
  2845. const directionDistance = target.dot( this.direction );
  2846. if ( directionDistance < 0 ) {
  2847. return target.copy( this.origin );
  2848. }
  2849. return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  2850. }
  2851. distanceToPoint( point ) {
  2852. return Math.sqrt( this.distanceSqToPoint( point ) );
  2853. }
  2854. distanceSqToPoint( point ) {
  2855. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  2856. // point behind the ray
  2857. if ( directionDistance < 0 ) {
  2858. return this.origin.distanceToSquared( point );
  2859. }
  2860. _vector$a.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  2861. return _vector$a.distanceToSquared( point );
  2862. }
  2863. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  2864. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  2865. // It returns the min distance between the ray and the segment
  2866. // defined by v0 and v1
  2867. // It can also set two optional targets :
  2868. // - The closest point on the ray
  2869. // - The closest point on the segment
  2870. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  2871. _segDir.copy( v1 ).sub( v0 ).normalize();
  2872. _diff.copy( this.origin ).sub( _segCenter );
  2873. const segExtent = v0.distanceTo( v1 ) * 0.5;
  2874. const a01 = - this.direction.dot( _segDir );
  2875. const b0 = _diff.dot( this.direction );
  2876. const b1 = - _diff.dot( _segDir );
  2877. const c = _diff.lengthSq();
  2878. const det = Math.abs( 1 - a01 * a01 );
  2879. let s0, s1, sqrDist, extDet;
  2880. if ( det > 0 ) {
  2881. // The ray and segment are not parallel.
  2882. s0 = a01 * b1 - b0;
  2883. s1 = a01 * b0 - b1;
  2884. extDet = segExtent * det;
  2885. if ( s0 >= 0 ) {
  2886. if ( s1 >= - extDet ) {
  2887. if ( s1 <= extDet ) {
  2888. // region 0
  2889. // Minimum at interior points of ray and segment.
  2890. const invDet = 1 / det;
  2891. s0 *= invDet;
  2892. s1 *= invDet;
  2893. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  2894. } else {
  2895. // region 1
  2896. s1 = segExtent;
  2897. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  2898. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  2899. }
  2900. } else {
  2901. // region 5
  2902. s1 = - segExtent;
  2903. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  2904. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  2905. }
  2906. } else {
  2907. if ( s1 <= - extDet ) {
  2908. // region 4
  2909. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  2910. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  2911. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  2912. } else if ( s1 <= extDet ) {
  2913. // region 3
  2914. s0 = 0;
  2915. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  2916. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  2917. } else {
  2918. // region 2
  2919. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  2920. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  2921. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  2922. }
  2923. }
  2924. } else {
  2925. // Ray and segment are parallel.
  2926. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  2927. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  2928. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  2929. }
  2930. if ( optionalPointOnRay ) {
  2931. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  2932. }
  2933. if ( optionalPointOnSegment ) {
  2934. optionalPointOnSegment.copy( _segDir ).multiplyScalar( s1 ).add( _segCenter );
  2935. }
  2936. return sqrDist;
  2937. }
  2938. intersectSphere( sphere, target ) {
  2939. _vector$a.subVectors( sphere.center, this.origin );
  2940. const tca = _vector$a.dot( this.direction );
  2941. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  2942. const radius2 = sphere.radius * sphere.radius;
  2943. if ( d2 > radius2 ) return null;
  2944. const thc = Math.sqrt( radius2 - d2 );
  2945. // t0 = first intersect point - entrance on front of sphere
  2946. const t0 = tca - thc;
  2947. // t1 = second intersect point - exit point on back of sphere
  2948. const t1 = tca + thc;
  2949. // test to see if both t0 and t1 are behind the ray - if so, return null
  2950. if ( t0 < 0 && t1 < 0 ) return null;
  2951. // test to see if t0 is behind the ray:
  2952. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  2953. // in order to always return an intersect point that is in front of the ray.
  2954. if ( t0 < 0 ) return this.at( t1, target );
  2955. // else t0 is in front of the ray, so return the first collision point scaled by t0
  2956. return this.at( t0, target );
  2957. }
  2958. intersectsSphere( sphere ) {
  2959. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  2960. }
  2961. distanceToPlane( plane ) {
  2962. const denominator = plane.normal.dot( this.direction );
  2963. if ( denominator === 0 ) {
  2964. // line is coplanar, return origin
  2965. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  2966. return 0;
  2967. }
  2968. // Null is preferable to undefined since undefined means.... it is undefined
  2969. return null;
  2970. }
  2971. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  2972. // Return if the ray never intersects the plane
  2973. return t >= 0 ? t : null;
  2974. }
  2975. intersectPlane( plane, target ) {
  2976. const t = this.distanceToPlane( plane );
  2977. if ( t === null ) {
  2978. return null;
  2979. }
  2980. return this.at( t, target );
  2981. }
  2982. intersectsPlane( plane ) {
  2983. // check if the ray lies on the plane first
  2984. const distToPoint = plane.distanceToPoint( this.origin );
  2985. if ( distToPoint === 0 ) {
  2986. return true;
  2987. }
  2988. const denominator = plane.normal.dot( this.direction );
  2989. if ( denominator * distToPoint < 0 ) {
  2990. return true;
  2991. }
  2992. // ray origin is behind the plane (and is pointing behind it)
  2993. return false;
  2994. }
  2995. intersectBox( box, target ) {
  2996. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  2997. const invdirx = 1 / this.direction.x,
  2998. invdiry = 1 / this.direction.y,
  2999. invdirz = 1 / this.direction.z;
  3000. const origin = this.origin;
  3001. if ( invdirx >= 0 ) {
  3002. tmin = ( box.min.x - origin.x ) * invdirx;
  3003. tmax = ( box.max.x - origin.x ) * invdirx;
  3004. } else {
  3005. tmin = ( box.max.x - origin.x ) * invdirx;
  3006. tmax = ( box.min.x - origin.x ) * invdirx;
  3007. }
  3008. if ( invdiry >= 0 ) {
  3009. tymin = ( box.min.y - origin.y ) * invdiry;
  3010. tymax = ( box.max.y - origin.y ) * invdiry;
  3011. } else {
  3012. tymin = ( box.max.y - origin.y ) * invdiry;
  3013. tymax = ( box.min.y - origin.y ) * invdiry;
  3014. }
  3015. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3016. // These lines also handle the case where tmin or tmax is NaN
  3017. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3018. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  3019. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  3020. if ( invdirz >= 0 ) {
  3021. tzmin = ( box.min.z - origin.z ) * invdirz;
  3022. tzmax = ( box.max.z - origin.z ) * invdirz;
  3023. } else {
  3024. tzmin = ( box.max.z - origin.z ) * invdirz;
  3025. tzmax = ( box.min.z - origin.z ) * invdirz;
  3026. }
  3027. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3028. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3029. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3030. //return point closest to the ray (positive side)
  3031. if ( tmax < 0 ) return null;
  3032. return this.at( tmin >= 0 ? tmin : tmax, target );
  3033. }
  3034. intersectsBox( box ) {
  3035. return this.intersectBox( box, _vector$a ) !== null;
  3036. }
  3037. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3038. // Compute the offset origin, edges, and normal.
  3039. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3040. _edge1.subVectors( b, a );
  3041. _edge2.subVectors( c, a );
  3042. _normal$1.crossVectors( _edge1, _edge2 );
  3043. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3044. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3045. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3046. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3047. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3048. let DdN = this.direction.dot( _normal$1 );
  3049. let sign;
  3050. if ( DdN > 0 ) {
  3051. if ( backfaceCulling ) return null;
  3052. sign = 1;
  3053. } else if ( DdN < 0 ) {
  3054. sign = - 1;
  3055. DdN = - DdN;
  3056. } else {
  3057. return null;
  3058. }
  3059. _diff.subVectors( this.origin, a );
  3060. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3061. // b1 < 0, no intersection
  3062. if ( DdQxE2 < 0 ) {
  3063. return null;
  3064. }
  3065. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3066. // b2 < 0, no intersection
  3067. if ( DdE1xQ < 0 ) {
  3068. return null;
  3069. }
  3070. // b1+b2 > 1, no intersection
  3071. if ( DdQxE2 + DdE1xQ > DdN ) {
  3072. return null;
  3073. }
  3074. // Line intersects triangle, check if ray does.
  3075. const QdN = - sign * _diff.dot( _normal$1 );
  3076. // t < 0, no intersection
  3077. if ( QdN < 0 ) {
  3078. return null;
  3079. }
  3080. // Ray intersects triangle.
  3081. return this.at( QdN / DdN, target );
  3082. }
  3083. applyMatrix4( matrix4 ) {
  3084. this.origin.applyMatrix4( matrix4 );
  3085. this.direction.transformDirection( matrix4 );
  3086. return this;
  3087. }
  3088. equals( ray ) {
  3089. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3090. }
  3091. clone() {
  3092. return new this.constructor().copy( this );
  3093. }
  3094. }
  3095. class Matrix4 {
  3096. constructor() {
  3097. this.elements = [
  3098. 1, 0, 0, 0,
  3099. 0, 1, 0, 0,
  3100. 0, 0, 1, 0,
  3101. 0, 0, 0, 1
  3102. ];
  3103. if ( arguments.length > 0 ) {
  3104. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  3105. }
  3106. }
  3107. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3108. const te = this.elements;
  3109. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3110. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3111. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3112. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3113. return this;
  3114. }
  3115. identity() {
  3116. this.set(
  3117. 1, 0, 0, 0,
  3118. 0, 1, 0, 0,
  3119. 0, 0, 1, 0,
  3120. 0, 0, 0, 1
  3121. );
  3122. return this;
  3123. }
  3124. clone() {
  3125. return new Matrix4().fromArray( this.elements );
  3126. }
  3127. copy( m ) {
  3128. const te = this.elements;
  3129. const me = m.elements;
  3130. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3131. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3132. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3133. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3134. return this;
  3135. }
  3136. copyPosition( m ) {
  3137. const te = this.elements, me = m.elements;
  3138. te[ 12 ] = me[ 12 ];
  3139. te[ 13 ] = me[ 13 ];
  3140. te[ 14 ] = me[ 14 ];
  3141. return this;
  3142. }
  3143. setFromMatrix3( m ) {
  3144. const me = m.elements;
  3145. this.set(
  3146. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3147. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3148. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3149. 0, 0, 0, 1
  3150. );
  3151. return this;
  3152. }
  3153. extractBasis( xAxis, yAxis, zAxis ) {
  3154. xAxis.setFromMatrixColumn( this, 0 );
  3155. yAxis.setFromMatrixColumn( this, 1 );
  3156. zAxis.setFromMatrixColumn( this, 2 );
  3157. return this;
  3158. }
  3159. makeBasis( xAxis, yAxis, zAxis ) {
  3160. this.set(
  3161. xAxis.x, yAxis.x, zAxis.x, 0,
  3162. xAxis.y, yAxis.y, zAxis.y, 0,
  3163. xAxis.z, yAxis.z, zAxis.z, 0,
  3164. 0, 0, 0, 1
  3165. );
  3166. return this;
  3167. }
  3168. extractRotation( m ) {
  3169. // this method does not support reflection matrices
  3170. const te = this.elements;
  3171. const me = m.elements;
  3172. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  3173. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  3174. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  3175. te[ 0 ] = me[ 0 ] * scaleX;
  3176. te[ 1 ] = me[ 1 ] * scaleX;
  3177. te[ 2 ] = me[ 2 ] * scaleX;
  3178. te[ 3 ] = 0;
  3179. te[ 4 ] = me[ 4 ] * scaleY;
  3180. te[ 5 ] = me[ 5 ] * scaleY;
  3181. te[ 6 ] = me[ 6 ] * scaleY;
  3182. te[ 7 ] = 0;
  3183. te[ 8 ] = me[ 8 ] * scaleZ;
  3184. te[ 9 ] = me[ 9 ] * scaleZ;
  3185. te[ 10 ] = me[ 10 ] * scaleZ;
  3186. te[ 11 ] = 0;
  3187. te[ 12 ] = 0;
  3188. te[ 13 ] = 0;
  3189. te[ 14 ] = 0;
  3190. te[ 15 ] = 1;
  3191. return this;
  3192. }
  3193. makeRotationFromEuler( euler ) {
  3194. if ( ! ( euler && euler.isEuler ) ) {
  3195. console.error( 'THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  3196. }
  3197. const te = this.elements;
  3198. const x = euler.x, y = euler.y, z = euler.z;
  3199. const a = Math.cos( x ), b = Math.sin( x );
  3200. const c = Math.cos( y ), d = Math.sin( y );
  3201. const e = Math.cos( z ), f = Math.sin( z );
  3202. if ( euler.order === 'XYZ' ) {
  3203. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3204. te[ 0 ] = c * e;
  3205. te[ 4 ] = - c * f;
  3206. te[ 8 ] = d;
  3207. te[ 1 ] = af + be * d;
  3208. te[ 5 ] = ae - bf * d;
  3209. te[ 9 ] = - b * c;
  3210. te[ 2 ] = bf - ae * d;
  3211. te[ 6 ] = be + af * d;
  3212. te[ 10 ] = a * c;
  3213. } else if ( euler.order === 'YXZ' ) {
  3214. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3215. te[ 0 ] = ce + df * b;
  3216. te[ 4 ] = de * b - cf;
  3217. te[ 8 ] = a * d;
  3218. te[ 1 ] = a * f;
  3219. te[ 5 ] = a * e;
  3220. te[ 9 ] = - b;
  3221. te[ 2 ] = cf * b - de;
  3222. te[ 6 ] = df + ce * b;
  3223. te[ 10 ] = a * c;
  3224. } else if ( euler.order === 'ZXY' ) {
  3225. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3226. te[ 0 ] = ce - df * b;
  3227. te[ 4 ] = - a * f;
  3228. te[ 8 ] = de + cf * b;
  3229. te[ 1 ] = cf + de * b;
  3230. te[ 5 ] = a * e;
  3231. te[ 9 ] = df - ce * b;
  3232. te[ 2 ] = - a * d;
  3233. te[ 6 ] = b;
  3234. te[ 10 ] = a * c;
  3235. } else if ( euler.order === 'ZYX' ) {
  3236. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3237. te[ 0 ] = c * e;
  3238. te[ 4 ] = be * d - af;
  3239. te[ 8 ] = ae * d + bf;
  3240. te[ 1 ] = c * f;
  3241. te[ 5 ] = bf * d + ae;
  3242. te[ 9 ] = af * d - be;
  3243. te[ 2 ] = - d;
  3244. te[ 6 ] = b * c;
  3245. te[ 10 ] = a * c;
  3246. } else if ( euler.order === 'YZX' ) {
  3247. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3248. te[ 0 ] = c * e;
  3249. te[ 4 ] = bd - ac * f;
  3250. te[ 8 ] = bc * f + ad;
  3251. te[ 1 ] = f;
  3252. te[ 5 ] = a * e;
  3253. te[ 9 ] = - b * e;
  3254. te[ 2 ] = - d * e;
  3255. te[ 6 ] = ad * f + bc;
  3256. te[ 10 ] = ac - bd * f;
  3257. } else if ( euler.order === 'XZY' ) {
  3258. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3259. te[ 0 ] = c * e;
  3260. te[ 4 ] = - f;
  3261. te[ 8 ] = d * e;
  3262. te[ 1 ] = ac * f + bd;
  3263. te[ 5 ] = a * e;
  3264. te[ 9 ] = ad * f - bc;
  3265. te[ 2 ] = bc * f - ad;
  3266. te[ 6 ] = b * e;
  3267. te[ 10 ] = bd * f + ac;
  3268. }
  3269. // bottom row
  3270. te[ 3 ] = 0;
  3271. te[ 7 ] = 0;
  3272. te[ 11 ] = 0;
  3273. // last column
  3274. te[ 12 ] = 0;
  3275. te[ 13 ] = 0;
  3276. te[ 14 ] = 0;
  3277. te[ 15 ] = 1;
  3278. return this;
  3279. }
  3280. makeRotationFromQuaternion( q ) {
  3281. return this.compose( _zero, q, _one );
  3282. }
  3283. lookAt( eye, target, up ) {
  3284. const te = this.elements;
  3285. _z.subVectors( eye, target );
  3286. if ( _z.lengthSq() === 0 ) {
  3287. // eye and target are in the same position
  3288. _z.z = 1;
  3289. }
  3290. _z.normalize();
  3291. _x.crossVectors( up, _z );
  3292. if ( _x.lengthSq() === 0 ) {
  3293. // up and z are parallel
  3294. if ( Math.abs( up.z ) === 1 ) {
  3295. _z.x += 0.0001;
  3296. } else {
  3297. _z.z += 0.0001;
  3298. }
  3299. _z.normalize();
  3300. _x.crossVectors( up, _z );
  3301. }
  3302. _x.normalize();
  3303. _y.crossVectors( _z, _x );
  3304. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3305. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3306. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3307. return this;
  3308. }
  3309. multiply( m, n ) {
  3310. if ( n !== undefined ) {
  3311. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  3312. return this.multiplyMatrices( m, n );
  3313. }
  3314. return this.multiplyMatrices( this, m );
  3315. }
  3316. premultiply( m ) {
  3317. return this.multiplyMatrices( m, this );
  3318. }
  3319. multiplyMatrices( a, b ) {
  3320. const ae = a.elements;
  3321. const be = b.elements;
  3322. const te = this.elements;
  3323. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3324. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3325. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3326. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3327. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3328. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3329. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3330. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3331. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3332. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3333. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3334. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3335. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3336. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3337. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3338. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3339. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3340. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3341. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3342. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3343. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3344. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3345. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3346. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3347. return this;
  3348. }
  3349. multiplyScalar( s ) {
  3350. const te = this.elements;
  3351. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3352. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3353. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3354. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3355. return this;
  3356. }
  3357. determinant() {
  3358. const te = this.elements;
  3359. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3360. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3361. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3362. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3363. //TODO: make this more efficient
  3364. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3365. return (
  3366. n41 * (
  3367. + n14 * n23 * n32
  3368. - n13 * n24 * n32
  3369. - n14 * n22 * n33
  3370. + n12 * n24 * n33
  3371. + n13 * n22 * n34
  3372. - n12 * n23 * n34
  3373. ) +
  3374. n42 * (
  3375. + n11 * n23 * n34
  3376. - n11 * n24 * n33
  3377. + n14 * n21 * n33
  3378. - n13 * n21 * n34
  3379. + n13 * n24 * n31
  3380. - n14 * n23 * n31
  3381. ) +
  3382. n43 * (
  3383. + n11 * n24 * n32
  3384. - n11 * n22 * n34
  3385. - n14 * n21 * n32
  3386. + n12 * n21 * n34
  3387. + n14 * n22 * n31
  3388. - n12 * n24 * n31
  3389. ) +
  3390. n44 * (
  3391. - n13 * n22 * n31
  3392. - n11 * n23 * n32
  3393. + n11 * n22 * n33
  3394. + n13 * n21 * n32
  3395. - n12 * n21 * n33
  3396. + n12 * n23 * n31
  3397. )
  3398. );
  3399. }
  3400. transpose() {
  3401. const te = this.elements;
  3402. let tmp;
  3403. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3404. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3405. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3406. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3407. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3408. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3409. return this;
  3410. }
  3411. setPosition( x, y, z ) {
  3412. const te = this.elements;
  3413. if ( x.isVector3 ) {
  3414. te[ 12 ] = x.x;
  3415. te[ 13 ] = x.y;
  3416. te[ 14 ] = x.z;
  3417. } else {
  3418. te[ 12 ] = x;
  3419. te[ 13 ] = y;
  3420. te[ 14 ] = z;
  3421. }
  3422. return this;
  3423. }
  3424. invert() {
  3425. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3426. const te = this.elements,
  3427. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  3428. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  3429. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  3430. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  3431. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3432. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3433. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3434. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3435. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3436. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  3437. const detInv = 1 / det;
  3438. te[ 0 ] = t11 * detInv;
  3439. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  3440. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  3441. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  3442. te[ 4 ] = t12 * detInv;
  3443. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  3444. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  3445. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  3446. te[ 8 ] = t13 * detInv;
  3447. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  3448. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  3449. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  3450. te[ 12 ] = t14 * detInv;
  3451. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  3452. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  3453. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  3454. return this;
  3455. }
  3456. scale( v ) {
  3457. const te = this.elements;
  3458. const x = v.x, y = v.y, z = v.z;
  3459. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3460. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3461. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3462. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3463. return this;
  3464. }
  3465. getMaxScaleOnAxis() {
  3466. const te = this.elements;
  3467. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3468. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3469. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3470. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3471. }
  3472. makeTranslation( x, y, z ) {
  3473. this.set(
  3474. 1, 0, 0, x,
  3475. 0, 1, 0, y,
  3476. 0, 0, 1, z,
  3477. 0, 0, 0, 1
  3478. );
  3479. return this;
  3480. }
  3481. makeRotationX( theta ) {
  3482. const c = Math.cos( theta ), s = Math.sin( theta );
  3483. this.set(
  3484. 1, 0, 0, 0,
  3485. 0, c, - s, 0,
  3486. 0, s, c, 0,
  3487. 0, 0, 0, 1
  3488. );
  3489. return this;
  3490. }
  3491. makeRotationY( theta ) {
  3492. const c = Math.cos( theta ), s = Math.sin( theta );
  3493. this.set(
  3494. c, 0, s, 0,
  3495. 0, 1, 0, 0,
  3496. - s, 0, c, 0,
  3497. 0, 0, 0, 1
  3498. );
  3499. return this;
  3500. }
  3501. makeRotationZ( theta ) {
  3502. const c = Math.cos( theta ), s = Math.sin( theta );
  3503. this.set(
  3504. c, - s, 0, 0,
  3505. s, c, 0, 0,
  3506. 0, 0, 1, 0,
  3507. 0, 0, 0, 1
  3508. );
  3509. return this;
  3510. }
  3511. makeRotationAxis( axis, angle ) {
  3512. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3513. const c = Math.cos( angle );
  3514. const s = Math.sin( angle );
  3515. const t = 1 - c;
  3516. const x = axis.x, y = axis.y, z = axis.z;
  3517. const tx = t * x, ty = t * y;
  3518. this.set(
  3519. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3520. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3521. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3522. 0, 0, 0, 1
  3523. );
  3524. return this;
  3525. }
  3526. makeScale( x, y, z ) {
  3527. this.set(
  3528. x, 0, 0, 0,
  3529. 0, y, 0, 0,
  3530. 0, 0, z, 0,
  3531. 0, 0, 0, 1
  3532. );
  3533. return this;
  3534. }
  3535. makeShear( xy, xz, yx, yz, zx, zy ) {
  3536. this.set(
  3537. 1, yx, zx, 0,
  3538. xy, 1, zy, 0,
  3539. xz, yz, 1, 0,
  3540. 0, 0, 0, 1
  3541. );
  3542. return this;
  3543. }
  3544. compose( position, quaternion, scale ) {
  3545. const te = this.elements;
  3546. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  3547. const x2 = x + x, y2 = y + y, z2 = z + z;
  3548. const xx = x * x2, xy = x * y2, xz = x * z2;
  3549. const yy = y * y2, yz = y * z2, zz = z * z2;
  3550. const wx = w * x2, wy = w * y2, wz = w * z2;
  3551. const sx = scale.x, sy = scale.y, sz = scale.z;
  3552. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  3553. te[ 1 ] = ( xy + wz ) * sx;
  3554. te[ 2 ] = ( xz - wy ) * sx;
  3555. te[ 3 ] = 0;
  3556. te[ 4 ] = ( xy - wz ) * sy;
  3557. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  3558. te[ 6 ] = ( yz + wx ) * sy;
  3559. te[ 7 ] = 0;
  3560. te[ 8 ] = ( xz + wy ) * sz;
  3561. te[ 9 ] = ( yz - wx ) * sz;
  3562. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  3563. te[ 11 ] = 0;
  3564. te[ 12 ] = position.x;
  3565. te[ 13 ] = position.y;
  3566. te[ 14 ] = position.z;
  3567. te[ 15 ] = 1;
  3568. return this;
  3569. }
  3570. decompose( position, quaternion, scale ) {
  3571. const te = this.elements;
  3572. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  3573. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  3574. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  3575. // if determine is negative, we need to invert one scale
  3576. const det = this.determinant();
  3577. if ( det < 0 ) sx = - sx;
  3578. position.x = te[ 12 ];
  3579. position.y = te[ 13 ];
  3580. position.z = te[ 14 ];
  3581. // scale the rotation part
  3582. _m1$2.copy( this );
  3583. const invSX = 1 / sx;
  3584. const invSY = 1 / sy;
  3585. const invSZ = 1 / sz;
  3586. _m1$2.elements[ 0 ] *= invSX;
  3587. _m1$2.elements[ 1 ] *= invSX;
  3588. _m1$2.elements[ 2 ] *= invSX;
  3589. _m1$2.elements[ 4 ] *= invSY;
  3590. _m1$2.elements[ 5 ] *= invSY;
  3591. _m1$2.elements[ 6 ] *= invSY;
  3592. _m1$2.elements[ 8 ] *= invSZ;
  3593. _m1$2.elements[ 9 ] *= invSZ;
  3594. _m1$2.elements[ 10 ] *= invSZ;
  3595. quaternion.setFromRotationMatrix( _m1$2 );
  3596. scale.x = sx;
  3597. scale.y = sy;
  3598. scale.z = sz;
  3599. return this;
  3600. }
  3601. makePerspective( left, right, top, bottom, near, far ) {
  3602. if ( far === undefined ) {
  3603. console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' );
  3604. }
  3605. const te = this.elements;
  3606. const x = 2 * near / ( right - left );
  3607. const y = 2 * near / ( top - bottom );
  3608. const a = ( right + left ) / ( right - left );
  3609. const b = ( top + bottom ) / ( top - bottom );
  3610. const c = - ( far + near ) / ( far - near );
  3611. const d = - 2 * far * near / ( far - near );
  3612. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  3613. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  3614. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  3615. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  3616. return this;
  3617. }
  3618. makeOrthographic( left, right, top, bottom, near, far ) {
  3619. const te = this.elements;
  3620. const w = 1.0 / ( right - left );
  3621. const h = 1.0 / ( top - bottom );
  3622. const p = 1.0 / ( far - near );
  3623. const x = ( right + left ) * w;
  3624. const y = ( top + bottom ) * h;
  3625. const z = ( far + near ) * p;
  3626. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  3627. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  3628. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  3629. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  3630. return this;
  3631. }
  3632. equals( matrix ) {
  3633. const te = this.elements;
  3634. const me = matrix.elements;
  3635. for ( let i = 0; i < 16; i ++ ) {
  3636. if ( te[ i ] !== me[ i ] ) return false;
  3637. }
  3638. return true;
  3639. }
  3640. fromArray( array, offset = 0 ) {
  3641. for ( let i = 0; i < 16; i ++ ) {
  3642. this.elements[ i ] = array[ i + offset ];
  3643. }
  3644. return this;
  3645. }
  3646. toArray( array = [], offset = 0 ) {
  3647. const te = this.elements;
  3648. array[ offset ] = te[ 0 ];
  3649. array[ offset + 1 ] = te[ 1 ];
  3650. array[ offset + 2 ] = te[ 2 ];
  3651. array[ offset + 3 ] = te[ 3 ];
  3652. array[ offset + 4 ] = te[ 4 ];
  3653. array[ offset + 5 ] = te[ 5 ];
  3654. array[ offset + 6 ] = te[ 6 ];
  3655. array[ offset + 7 ] = te[ 7 ];
  3656. array[ offset + 8 ] = te[ 8 ];
  3657. array[ offset + 9 ] = te[ 9 ];
  3658. array[ offset + 10 ] = te[ 10 ];
  3659. array[ offset + 11 ] = te[ 11 ];
  3660. array[ offset + 12 ] = te[ 12 ];
  3661. array[ offset + 13 ] = te[ 13 ];
  3662. array[ offset + 14 ] = te[ 14 ];
  3663. array[ offset + 15 ] = te[ 15 ];
  3664. return array;
  3665. }
  3666. }
  3667. Matrix4.prototype.isMatrix4 = true;
  3668. const _v1$5 = /*@__PURE__*/ new Vector3();
  3669. const _m1$2 = /*@__PURE__*/ new Matrix4();
  3670. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  3671. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  3672. const _x = /*@__PURE__*/ new Vector3();
  3673. const _y = /*@__PURE__*/ new Vector3();
  3674. const _z = /*@__PURE__*/ new Vector3();
  3675. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  3676. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  3677. class Euler {
  3678. constructor( x = 0, y = 0, z = 0, order = Euler.DefaultOrder ) {
  3679. this._x = x;
  3680. this._y = y;
  3681. this._z = z;
  3682. this._order = order;
  3683. }
  3684. get x() {
  3685. return this._x;
  3686. }
  3687. set x( value ) {
  3688. this._x = value;
  3689. this._onChangeCallback();
  3690. }
  3691. get y() {
  3692. return this._y;
  3693. }
  3694. set y( value ) {
  3695. this._y = value;
  3696. this._onChangeCallback();
  3697. }
  3698. get z() {
  3699. return this._z;
  3700. }
  3701. set z( value ) {
  3702. this._z = value;
  3703. this._onChangeCallback();
  3704. }
  3705. get order() {
  3706. return this._order;
  3707. }
  3708. set order( value ) {
  3709. this._order = value;
  3710. this._onChangeCallback();
  3711. }
  3712. set( x, y, z, order = this._order ) {
  3713. this._x = x;
  3714. this._y = y;
  3715. this._z = z;
  3716. this._order = order;
  3717. this._onChangeCallback();
  3718. return this;
  3719. }
  3720. clone() {
  3721. return new this.constructor( this._x, this._y, this._z, this._order );
  3722. }
  3723. copy( euler ) {
  3724. this._x = euler._x;
  3725. this._y = euler._y;
  3726. this._z = euler._z;
  3727. this._order = euler._order;
  3728. this._onChangeCallback();
  3729. return this;
  3730. }
  3731. setFromRotationMatrix( m, order = this._order, update = true ) {
  3732. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3733. const te = m.elements;
  3734. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  3735. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  3736. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  3737. switch ( order ) {
  3738. case 'XYZ':
  3739. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  3740. if ( Math.abs( m13 ) < 0.9999999 ) {
  3741. this._x = Math.atan2( - m23, m33 );
  3742. this._z = Math.atan2( - m12, m11 );
  3743. } else {
  3744. this._x = Math.atan2( m32, m22 );
  3745. this._z = 0;
  3746. }
  3747. break;
  3748. case 'YXZ':
  3749. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  3750. if ( Math.abs( m23 ) < 0.9999999 ) {
  3751. this._y = Math.atan2( m13, m33 );
  3752. this._z = Math.atan2( m21, m22 );
  3753. } else {
  3754. this._y = Math.atan2( - m31, m11 );
  3755. this._z = 0;
  3756. }
  3757. break;
  3758. case 'ZXY':
  3759. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  3760. if ( Math.abs( m32 ) < 0.9999999 ) {
  3761. this._y = Math.atan2( - m31, m33 );
  3762. this._z = Math.atan2( - m12, m22 );
  3763. } else {
  3764. this._y = 0;
  3765. this._z = Math.atan2( m21, m11 );
  3766. }
  3767. break;
  3768. case 'ZYX':
  3769. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  3770. if ( Math.abs( m31 ) < 0.9999999 ) {
  3771. this._x = Math.atan2( m32, m33 );
  3772. this._z = Math.atan2( m21, m11 );
  3773. } else {
  3774. this._x = 0;
  3775. this._z = Math.atan2( - m12, m22 );
  3776. }
  3777. break;
  3778. case 'YZX':
  3779. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  3780. if ( Math.abs( m21 ) < 0.9999999 ) {
  3781. this._x = Math.atan2( - m23, m22 );
  3782. this._y = Math.atan2( - m31, m11 );
  3783. } else {
  3784. this._x = 0;
  3785. this._y = Math.atan2( m13, m33 );
  3786. }
  3787. break;
  3788. case 'XZY':
  3789. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  3790. if ( Math.abs( m12 ) < 0.9999999 ) {
  3791. this._x = Math.atan2( m32, m22 );
  3792. this._y = Math.atan2( m13, m11 );
  3793. } else {
  3794. this._x = Math.atan2( - m23, m33 );
  3795. this._y = 0;
  3796. }
  3797. break;
  3798. default:
  3799. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  3800. }
  3801. this._order = order;
  3802. if ( update === true ) this._onChangeCallback();
  3803. return this;
  3804. }
  3805. setFromQuaternion( q, order, update ) {
  3806. _matrix$1.makeRotationFromQuaternion( q );
  3807. return this.setFromRotationMatrix( _matrix$1, order, update );
  3808. }
  3809. setFromVector3( v, order = this._order ) {
  3810. return this.set( v.x, v.y, v.z, order );
  3811. }
  3812. reorder( newOrder ) {
  3813. // WARNING: this discards revolution information -bhouston
  3814. _quaternion$3.setFromEuler( this );
  3815. return this.setFromQuaternion( _quaternion$3, newOrder );
  3816. }
  3817. equals( euler ) {
  3818. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  3819. }
  3820. fromArray( array ) {
  3821. this._x = array[ 0 ];
  3822. this._y = array[ 1 ];
  3823. this._z = array[ 2 ];
  3824. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  3825. this._onChangeCallback();
  3826. return this;
  3827. }
  3828. toArray( array = [], offset = 0 ) {
  3829. array[ offset ] = this._x;
  3830. array[ offset + 1 ] = this._y;
  3831. array[ offset + 2 ] = this._z;
  3832. array[ offset + 3 ] = this._order;
  3833. return array;
  3834. }
  3835. toVector3( optionalResult ) {
  3836. if ( optionalResult ) {
  3837. return optionalResult.set( this._x, this._y, this._z );
  3838. } else {
  3839. return new Vector3( this._x, this._y, this._z );
  3840. }
  3841. }
  3842. _onChange( callback ) {
  3843. this._onChangeCallback = callback;
  3844. return this;
  3845. }
  3846. _onChangeCallback() {}
  3847. }
  3848. Euler.prototype.isEuler = true;
  3849. Euler.DefaultOrder = 'XYZ';
  3850. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  3851. class Layers {
  3852. constructor() {
  3853. this.mask = 1 | 0;
  3854. }
  3855. set( channel ) {
  3856. this.mask = 1 << channel | 0;
  3857. }
  3858. enable( channel ) {
  3859. this.mask |= 1 << channel | 0;
  3860. }
  3861. enableAll() {
  3862. this.mask = 0xffffffff | 0;
  3863. }
  3864. toggle( channel ) {
  3865. this.mask ^= 1 << channel | 0;
  3866. }
  3867. disable( channel ) {
  3868. this.mask &= ~ ( 1 << channel | 0 );
  3869. }
  3870. disableAll() {
  3871. this.mask = 0;
  3872. }
  3873. test( layers ) {
  3874. return ( this.mask & layers.mask ) !== 0;
  3875. }
  3876. }
  3877. let _object3DId = 0;
  3878. const _v1$4 = /*@__PURE__*/ new Vector3();
  3879. const _q1 = /*@__PURE__*/ new Quaternion();
  3880. const _m1$1 = /*@__PURE__*/ new Matrix4();
  3881. const _target = /*@__PURE__*/ new Vector3();
  3882. const _position$3 = /*@__PURE__*/ new Vector3();
  3883. const _scale$2 = /*@__PURE__*/ new Vector3();
  3884. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  3885. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  3886. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  3887. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  3888. const _addedEvent = { type: 'added' };
  3889. const _removedEvent = { type: 'removed' };
  3890. class Object3D extends EventDispatcher {
  3891. constructor() {
  3892. super();
  3893. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  3894. this.uuid = generateUUID();
  3895. this.name = '';
  3896. this.type = 'Object3D';
  3897. this.parent = null;
  3898. this.children = [];
  3899. this.up = Object3D.DefaultUp.clone();
  3900. const position = new Vector3();
  3901. const rotation = new Euler();
  3902. const quaternion = new Quaternion();
  3903. const scale = new Vector3( 1, 1, 1 );
  3904. function onRotationChange() {
  3905. quaternion.setFromEuler( rotation, false );
  3906. }
  3907. function onQuaternionChange() {
  3908. rotation.setFromQuaternion( quaternion, undefined, false );
  3909. }
  3910. rotation._onChange( onRotationChange );
  3911. quaternion._onChange( onQuaternionChange );
  3912. Object.defineProperties( this, {
  3913. position: {
  3914. configurable: true,
  3915. enumerable: true,
  3916. value: position
  3917. },
  3918. rotation: {
  3919. configurable: true,
  3920. enumerable: true,
  3921. value: rotation
  3922. },
  3923. quaternion: {
  3924. configurable: true,
  3925. enumerable: true,
  3926. value: quaternion
  3927. },
  3928. scale: {
  3929. configurable: true,
  3930. enumerable: true,
  3931. value: scale
  3932. },
  3933. modelViewMatrix: {
  3934. value: new Matrix4()
  3935. },
  3936. normalMatrix: {
  3937. value: new Matrix3()
  3938. }
  3939. } );
  3940. this.matrix = new Matrix4();
  3941. this.matrixWorld = new Matrix4();
  3942. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  3943. this.matrixWorldNeedsUpdate = false;
  3944. this.layers = new Layers();
  3945. this.visible = true;
  3946. this.castShadow = false;
  3947. this.receiveShadow = false;
  3948. this.frustumCulled = true;
  3949. this.renderOrder = 0;
  3950. this.animations = [];
  3951. this.userData = {};
  3952. }
  3953. onBeforeRender() {}
  3954. onAfterRender() {}
  3955. applyMatrix4( matrix ) {
  3956. if ( this.matrixAutoUpdate ) this.updateMatrix();
  3957. this.matrix.premultiply( matrix );
  3958. this.matrix.decompose( this.position, this.quaternion, this.scale );
  3959. }
  3960. applyQuaternion( q ) {
  3961. this.quaternion.premultiply( q );
  3962. return this;
  3963. }
  3964. setRotationFromAxisAngle( axis, angle ) {
  3965. // assumes axis is normalized
  3966. this.quaternion.setFromAxisAngle( axis, angle );
  3967. }
  3968. setRotationFromEuler( euler ) {
  3969. this.quaternion.setFromEuler( euler, true );
  3970. }
  3971. setRotationFromMatrix( m ) {
  3972. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3973. this.quaternion.setFromRotationMatrix( m );
  3974. }
  3975. setRotationFromQuaternion( q ) {
  3976. // assumes q is normalized
  3977. this.quaternion.copy( q );
  3978. }
  3979. rotateOnAxis( axis, angle ) {
  3980. // rotate object on axis in object space
  3981. // axis is assumed to be normalized
  3982. _q1.setFromAxisAngle( axis, angle );
  3983. this.quaternion.multiply( _q1 );
  3984. return this;
  3985. }
  3986. rotateOnWorldAxis( axis, angle ) {
  3987. // rotate object on axis in world space
  3988. // axis is assumed to be normalized
  3989. // method assumes no rotated parent
  3990. _q1.setFromAxisAngle( axis, angle );
  3991. this.quaternion.premultiply( _q1 );
  3992. return this;
  3993. }
  3994. rotateX( angle ) {
  3995. return this.rotateOnAxis( _xAxis, angle );
  3996. }
  3997. rotateY( angle ) {
  3998. return this.rotateOnAxis( _yAxis, angle );
  3999. }
  4000. rotateZ( angle ) {
  4001. return this.rotateOnAxis( _zAxis, angle );
  4002. }
  4003. translateOnAxis( axis, distance ) {
  4004. // translate object by distance along axis in object space
  4005. // axis is assumed to be normalized
  4006. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  4007. this.position.add( _v1$4.multiplyScalar( distance ) );
  4008. return this;
  4009. }
  4010. translateX( distance ) {
  4011. return this.translateOnAxis( _xAxis, distance );
  4012. }
  4013. translateY( distance ) {
  4014. return this.translateOnAxis( _yAxis, distance );
  4015. }
  4016. translateZ( distance ) {
  4017. return this.translateOnAxis( _zAxis, distance );
  4018. }
  4019. localToWorld( vector ) {
  4020. return vector.applyMatrix4( this.matrixWorld );
  4021. }
  4022. worldToLocal( vector ) {
  4023. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  4024. }
  4025. lookAt( x, y, z ) {
  4026. // This method does not support objects having non-uniformly-scaled parent(s)
  4027. if ( x.isVector3 ) {
  4028. _target.copy( x );
  4029. } else {
  4030. _target.set( x, y, z );
  4031. }
  4032. const parent = this.parent;
  4033. this.updateWorldMatrix( true, false );
  4034. _position$3.setFromMatrixPosition( this.matrixWorld );
  4035. if ( this.isCamera || this.isLight ) {
  4036. _m1$1.lookAt( _position$3, _target, this.up );
  4037. } else {
  4038. _m1$1.lookAt( _target, _position$3, this.up );
  4039. }
  4040. this.quaternion.setFromRotationMatrix( _m1$1 );
  4041. if ( parent ) {
  4042. _m1$1.extractRotation( parent.matrixWorld );
  4043. _q1.setFromRotationMatrix( _m1$1 );
  4044. this.quaternion.premultiply( _q1.invert() );
  4045. }
  4046. }
  4047. add( object ) {
  4048. if ( arguments.length > 1 ) {
  4049. for ( let i = 0; i < arguments.length; i ++ ) {
  4050. this.add( arguments[ i ] );
  4051. }
  4052. return this;
  4053. }
  4054. if ( object === this ) {
  4055. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4056. return this;
  4057. }
  4058. if ( object && object.isObject3D ) {
  4059. if ( object.parent !== null ) {
  4060. object.parent.remove( object );
  4061. }
  4062. object.parent = this;
  4063. this.children.push( object );
  4064. object.dispatchEvent( _addedEvent );
  4065. } else {
  4066. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4067. }
  4068. return this;
  4069. }
  4070. remove( object ) {
  4071. if ( arguments.length > 1 ) {
  4072. for ( let i = 0; i < arguments.length; i ++ ) {
  4073. this.remove( arguments[ i ] );
  4074. }
  4075. return this;
  4076. }
  4077. const index = this.children.indexOf( object );
  4078. if ( index !== - 1 ) {
  4079. object.parent = null;
  4080. this.children.splice( index, 1 );
  4081. object.dispatchEvent( _removedEvent );
  4082. }
  4083. return this;
  4084. }
  4085. removeFromParent() {
  4086. const parent = this.parent;
  4087. if ( parent !== null ) {
  4088. parent.remove( this );
  4089. }
  4090. return this;
  4091. }
  4092. clear() {
  4093. for ( let i = 0; i < this.children.length; i ++ ) {
  4094. const object = this.children[ i ];
  4095. object.parent = null;
  4096. object.dispatchEvent( _removedEvent );
  4097. }
  4098. this.children.length = 0;
  4099. return this;
  4100. }
  4101. attach( object ) {
  4102. // adds object as a child of this, while maintaining the object's world transform
  4103. this.updateWorldMatrix( true, false );
  4104. _m1$1.copy( this.matrixWorld ).invert();
  4105. if ( object.parent !== null ) {
  4106. object.parent.updateWorldMatrix( true, false );
  4107. _m1$1.multiply( object.parent.matrixWorld );
  4108. }
  4109. object.applyMatrix4( _m1$1 );
  4110. this.add( object );
  4111. object.updateWorldMatrix( false, true );
  4112. return this;
  4113. }
  4114. getObjectById( id ) {
  4115. return this.getObjectByProperty( 'id', id );
  4116. }
  4117. getObjectByName( name ) {
  4118. return this.getObjectByProperty( 'name', name );
  4119. }
  4120. getObjectByProperty( name, value ) {
  4121. if ( this[ name ] === value ) return this;
  4122. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4123. const child = this.children[ i ];
  4124. const object = child.getObjectByProperty( name, value );
  4125. if ( object !== undefined ) {
  4126. return object;
  4127. }
  4128. }
  4129. return undefined;
  4130. }
  4131. getWorldPosition( target ) {
  4132. this.updateWorldMatrix( true, false );
  4133. return target.setFromMatrixPosition( this.matrixWorld );
  4134. }
  4135. getWorldQuaternion( target ) {
  4136. this.updateWorldMatrix( true, false );
  4137. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  4138. return target;
  4139. }
  4140. getWorldScale( target ) {
  4141. this.updateWorldMatrix( true, false );
  4142. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  4143. return target;
  4144. }
  4145. getWorldDirection( target ) {
  4146. this.updateWorldMatrix( true, false );
  4147. const e = this.matrixWorld.elements;
  4148. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4149. }
  4150. raycast() {}
  4151. traverse( callback ) {
  4152. callback( this );
  4153. const children = this.children;
  4154. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4155. children[ i ].traverse( callback );
  4156. }
  4157. }
  4158. traverseVisible( callback ) {
  4159. if ( this.visible === false ) return;
  4160. callback( this );
  4161. const children = this.children;
  4162. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4163. children[ i ].traverseVisible( callback );
  4164. }
  4165. }
  4166. traverseAncestors( callback ) {
  4167. const parent = this.parent;
  4168. if ( parent !== null ) {
  4169. callback( parent );
  4170. parent.traverseAncestors( callback );
  4171. }
  4172. }
  4173. updateMatrix() {
  4174. this.matrix.compose( this.position, this.quaternion, this.scale );
  4175. this.matrixWorldNeedsUpdate = true;
  4176. }
  4177. updateMatrixWorld( force ) {
  4178. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4179. if ( this.matrixWorldNeedsUpdate || force ) {
  4180. if ( this.parent === null ) {
  4181. this.matrixWorld.copy( this.matrix );
  4182. } else {
  4183. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4184. }
  4185. this.matrixWorldNeedsUpdate = false;
  4186. force = true;
  4187. }
  4188. // update children
  4189. const children = this.children;
  4190. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4191. children[ i ].updateMatrixWorld( force );
  4192. }
  4193. }
  4194. updateWorldMatrix( updateParents, updateChildren ) {
  4195. const parent = this.parent;
  4196. if ( updateParents === true && parent !== null ) {
  4197. parent.updateWorldMatrix( true, false );
  4198. }
  4199. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4200. if ( this.parent === null ) {
  4201. this.matrixWorld.copy( this.matrix );
  4202. } else {
  4203. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4204. }
  4205. // update children
  4206. if ( updateChildren === true ) {
  4207. const children = this.children;
  4208. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4209. children[ i ].updateWorldMatrix( false, true );
  4210. }
  4211. }
  4212. }
  4213. toJSON( meta ) {
  4214. // meta is a string when called from JSON.stringify
  4215. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4216. const output = {};
  4217. // meta is a hash used to collect geometries, materials.
  4218. // not providing it implies that this is the root object
  4219. // being serialized.
  4220. if ( isRootObject ) {
  4221. // initialize meta obj
  4222. meta = {
  4223. geometries: {},
  4224. materials: {},
  4225. textures: {},
  4226. images: {},
  4227. shapes: {},
  4228. skeletons: {},
  4229. animations: {}
  4230. };
  4231. output.metadata = {
  4232. version: 4.5,
  4233. type: 'Object',
  4234. generator: 'Object3D.toJSON'
  4235. };
  4236. }
  4237. // standard Object3D serialization
  4238. const object = {};
  4239. object.uuid = this.uuid;
  4240. object.type = this.type;
  4241. if ( this.name !== '' ) object.name = this.name;
  4242. if ( this.castShadow === true ) object.castShadow = true;
  4243. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4244. if ( this.visible === false ) object.visible = false;
  4245. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4246. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4247. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  4248. object.layers = this.layers.mask;
  4249. object.matrix = this.matrix.toArray();
  4250. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4251. // object specific properties
  4252. if ( this.isInstancedMesh ) {
  4253. object.type = 'InstancedMesh';
  4254. object.count = this.count;
  4255. object.instanceMatrix = this.instanceMatrix.toJSON();
  4256. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  4257. }
  4258. //
  4259. function serialize( library, element ) {
  4260. if ( library[ element.uuid ] === undefined ) {
  4261. library[ element.uuid ] = element.toJSON( meta );
  4262. }
  4263. return element.uuid;
  4264. }
  4265. if ( this.isScene ) {
  4266. if ( this.background ) {
  4267. if ( this.background.isColor ) {
  4268. object.background = this.background.toJSON();
  4269. } else if ( this.background.isTexture ) {
  4270. object.background = this.background.toJSON( meta ).uuid;
  4271. }
  4272. }
  4273. if ( this.environment && this.environment.isTexture ) {
  4274. object.environment = this.environment.toJSON( meta ).uuid;
  4275. }
  4276. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  4277. object.geometry = serialize( meta.geometries, this.geometry );
  4278. const parameters = this.geometry.parameters;
  4279. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4280. const shapes = parameters.shapes;
  4281. if ( Array.isArray( shapes ) ) {
  4282. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4283. const shape = shapes[ i ];
  4284. serialize( meta.shapes, shape );
  4285. }
  4286. } else {
  4287. serialize( meta.shapes, shapes );
  4288. }
  4289. }
  4290. }
  4291. if ( this.isSkinnedMesh ) {
  4292. object.bindMode = this.bindMode;
  4293. object.bindMatrix = this.bindMatrix.toArray();
  4294. if ( this.skeleton !== undefined ) {
  4295. serialize( meta.skeletons, this.skeleton );
  4296. object.skeleton = this.skeleton.uuid;
  4297. }
  4298. }
  4299. if ( this.material !== undefined ) {
  4300. if ( Array.isArray( this.material ) ) {
  4301. const uuids = [];
  4302. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4303. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4304. }
  4305. object.material = uuids;
  4306. } else {
  4307. object.material = serialize( meta.materials, this.material );
  4308. }
  4309. }
  4310. //
  4311. if ( this.children.length > 0 ) {
  4312. object.children = [];
  4313. for ( let i = 0; i < this.children.length; i ++ ) {
  4314. object.children.push( this.children[ i ].toJSON( meta ).object );
  4315. }
  4316. }
  4317. //
  4318. if ( this.animations.length > 0 ) {
  4319. object.animations = [];
  4320. for ( let i = 0; i < this.animations.length; i ++ ) {
  4321. const animation = this.animations[ i ];
  4322. object.animations.push( serialize( meta.animations, animation ) );
  4323. }
  4324. }
  4325. if ( isRootObject ) {
  4326. const geometries = extractFromCache( meta.geometries );
  4327. const materials = extractFromCache( meta.materials );
  4328. const textures = extractFromCache( meta.textures );
  4329. const images = extractFromCache( meta.images );
  4330. const shapes = extractFromCache( meta.shapes );
  4331. const skeletons = extractFromCache( meta.skeletons );
  4332. const animations = extractFromCache( meta.animations );
  4333. if ( geometries.length > 0 ) output.geometries = geometries;
  4334. if ( materials.length > 0 ) output.materials = materials;
  4335. if ( textures.length > 0 ) output.textures = textures;
  4336. if ( images.length > 0 ) output.images = images;
  4337. if ( shapes.length > 0 ) output.shapes = shapes;
  4338. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4339. if ( animations.length > 0 ) output.animations = animations;
  4340. }
  4341. output.object = object;
  4342. return output;
  4343. // extract data from the cache hash
  4344. // remove metadata on each item
  4345. // and return as array
  4346. function extractFromCache( cache ) {
  4347. const values = [];
  4348. for ( const key in cache ) {
  4349. const data = cache[ key ];
  4350. delete data.metadata;
  4351. values.push( data );
  4352. }
  4353. return values;
  4354. }
  4355. }
  4356. clone( recursive ) {
  4357. return new this.constructor().copy( this, recursive );
  4358. }
  4359. copy( source, recursive = true ) {
  4360. this.name = source.name;
  4361. this.up.copy( source.up );
  4362. this.position.copy( source.position );
  4363. this.rotation.order = source.rotation.order;
  4364. this.quaternion.copy( source.quaternion );
  4365. this.scale.copy( source.scale );
  4366. this.matrix.copy( source.matrix );
  4367. this.matrixWorld.copy( source.matrixWorld );
  4368. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4369. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4370. this.layers.mask = source.layers.mask;
  4371. this.visible = source.visible;
  4372. this.castShadow = source.castShadow;
  4373. this.receiveShadow = source.receiveShadow;
  4374. this.frustumCulled = source.frustumCulled;
  4375. this.renderOrder = source.renderOrder;
  4376. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4377. if ( recursive === true ) {
  4378. for ( let i = 0; i < source.children.length; i ++ ) {
  4379. const child = source.children[ i ];
  4380. this.add( child.clone() );
  4381. }
  4382. }
  4383. return this;
  4384. }
  4385. }
  4386. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  4387. Object3D.DefaultMatrixAutoUpdate = true;
  4388. Object3D.prototype.isObject3D = true;
  4389. const _v0$1 = /*@__PURE__*/ new Vector3();
  4390. const _v1$3 = /*@__PURE__*/ new Vector3();
  4391. const _v2$2 = /*@__PURE__*/ new Vector3();
  4392. const _v3$1 = /*@__PURE__*/ new Vector3();
  4393. const _vab = /*@__PURE__*/ new Vector3();
  4394. const _vac = /*@__PURE__*/ new Vector3();
  4395. const _vbc = /*@__PURE__*/ new Vector3();
  4396. const _vap = /*@__PURE__*/ new Vector3();
  4397. const _vbp = /*@__PURE__*/ new Vector3();
  4398. const _vcp = /*@__PURE__*/ new Vector3();
  4399. class Triangle {
  4400. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  4401. this.a = a;
  4402. this.b = b;
  4403. this.c = c;
  4404. }
  4405. static getNormal( a, b, c, target ) {
  4406. target.subVectors( c, b );
  4407. _v0$1.subVectors( a, b );
  4408. target.cross( _v0$1 );
  4409. const targetLengthSq = target.lengthSq();
  4410. if ( targetLengthSq > 0 ) {
  4411. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  4412. }
  4413. return target.set( 0, 0, 0 );
  4414. }
  4415. // static/instance method to calculate barycentric coordinates
  4416. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4417. static getBarycoord( point, a, b, c, target ) {
  4418. _v0$1.subVectors( c, a );
  4419. _v1$3.subVectors( b, a );
  4420. _v2$2.subVectors( point, a );
  4421. const dot00 = _v0$1.dot( _v0$1 );
  4422. const dot01 = _v0$1.dot( _v1$3 );
  4423. const dot02 = _v0$1.dot( _v2$2 );
  4424. const dot11 = _v1$3.dot( _v1$3 );
  4425. const dot12 = _v1$3.dot( _v2$2 );
  4426. const denom = ( dot00 * dot11 - dot01 * dot01 );
  4427. // collinear or singular triangle
  4428. if ( denom === 0 ) {
  4429. // arbitrary location outside of triangle?
  4430. // not sure if this is the best idea, maybe should be returning undefined
  4431. return target.set( - 2, - 1, - 1 );
  4432. }
  4433. const invDenom = 1 / denom;
  4434. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4435. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4436. // barycentric coordinates must always sum to 1
  4437. return target.set( 1 - u - v, v, u );
  4438. }
  4439. static containsPoint( point, a, b, c ) {
  4440. this.getBarycoord( point, a, b, c, _v3$1 );
  4441. return ( _v3$1.x >= 0 ) && ( _v3$1.y >= 0 ) && ( ( _v3$1.x + _v3$1.y ) <= 1 );
  4442. }
  4443. static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) {
  4444. this.getBarycoord( point, p1, p2, p3, _v3$1 );
  4445. target.set( 0, 0 );
  4446. target.addScaledVector( uv1, _v3$1.x );
  4447. target.addScaledVector( uv2, _v3$1.y );
  4448. target.addScaledVector( uv3, _v3$1.z );
  4449. return target;
  4450. }
  4451. static isFrontFacing( a, b, c, direction ) {
  4452. _v0$1.subVectors( c, b );
  4453. _v1$3.subVectors( a, b );
  4454. // strictly front facing
  4455. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  4456. }
  4457. set( a, b, c ) {
  4458. this.a.copy( a );
  4459. this.b.copy( b );
  4460. this.c.copy( c );
  4461. return this;
  4462. }
  4463. setFromPointsAndIndices( points, i0, i1, i2 ) {
  4464. this.a.copy( points[ i0 ] );
  4465. this.b.copy( points[ i1 ] );
  4466. this.c.copy( points[ i2 ] );
  4467. return this;
  4468. }
  4469. clone() {
  4470. return new this.constructor().copy( this );
  4471. }
  4472. copy( triangle ) {
  4473. this.a.copy( triangle.a );
  4474. this.b.copy( triangle.b );
  4475. this.c.copy( triangle.c );
  4476. return this;
  4477. }
  4478. getArea() {
  4479. _v0$1.subVectors( this.c, this.b );
  4480. _v1$3.subVectors( this.a, this.b );
  4481. return _v0$1.cross( _v1$3 ).length() * 0.5;
  4482. }
  4483. getMidpoint( target ) {
  4484. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4485. }
  4486. getNormal( target ) {
  4487. return Triangle.getNormal( this.a, this.b, this.c, target );
  4488. }
  4489. getPlane( target ) {
  4490. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  4491. }
  4492. getBarycoord( point, target ) {
  4493. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  4494. }
  4495. getUV( point, uv1, uv2, uv3, target ) {
  4496. return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target );
  4497. }
  4498. containsPoint( point ) {
  4499. return Triangle.containsPoint( point, this.a, this.b, this.c );
  4500. }
  4501. isFrontFacing( direction ) {
  4502. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  4503. }
  4504. intersectsBox( box ) {
  4505. return box.intersectsTriangle( this );
  4506. }
  4507. closestPointToPoint( p, target ) {
  4508. const a = this.a, b = this.b, c = this.c;
  4509. let v, w;
  4510. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  4511. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  4512. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  4513. // basically, we're distinguishing which of the voronoi regions of the triangle
  4514. // the point lies in with the minimum amount of redundant computation.
  4515. _vab.subVectors( b, a );
  4516. _vac.subVectors( c, a );
  4517. _vap.subVectors( p, a );
  4518. const d1 = _vab.dot( _vap );
  4519. const d2 = _vac.dot( _vap );
  4520. if ( d1 <= 0 && d2 <= 0 ) {
  4521. // vertex region of A; barycentric coords (1, 0, 0)
  4522. return target.copy( a );
  4523. }
  4524. _vbp.subVectors( p, b );
  4525. const d3 = _vab.dot( _vbp );
  4526. const d4 = _vac.dot( _vbp );
  4527. if ( d3 >= 0 && d4 <= d3 ) {
  4528. // vertex region of B; barycentric coords (0, 1, 0)
  4529. return target.copy( b );
  4530. }
  4531. const vc = d1 * d4 - d3 * d2;
  4532. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  4533. v = d1 / ( d1 - d3 );
  4534. // edge region of AB; barycentric coords (1-v, v, 0)
  4535. return target.copy( a ).addScaledVector( _vab, v );
  4536. }
  4537. _vcp.subVectors( p, c );
  4538. const d5 = _vab.dot( _vcp );
  4539. const d6 = _vac.dot( _vcp );
  4540. if ( d6 >= 0 && d5 <= d6 ) {
  4541. // vertex region of C; barycentric coords (0, 0, 1)
  4542. return target.copy( c );
  4543. }
  4544. const vb = d5 * d2 - d1 * d6;
  4545. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  4546. w = d2 / ( d2 - d6 );
  4547. // edge region of AC; barycentric coords (1-w, 0, w)
  4548. return target.copy( a ).addScaledVector( _vac, w );
  4549. }
  4550. const va = d3 * d6 - d5 * d4;
  4551. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  4552. _vbc.subVectors( c, b );
  4553. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  4554. // edge region of BC; barycentric coords (0, 1-w, w)
  4555. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  4556. }
  4557. // face region
  4558. const denom = 1 / ( va + vb + vc );
  4559. // u = va * denom
  4560. v = vb * denom;
  4561. w = vc * denom;
  4562. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  4563. }
  4564. equals( triangle ) {
  4565. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  4566. }
  4567. }
  4568. let materialId = 0;
  4569. class Material extends EventDispatcher {
  4570. constructor() {
  4571. super();
  4572. Object.defineProperty( this, 'id', { value: materialId ++ } );
  4573. this.uuid = generateUUID();
  4574. this.name = '';
  4575. this.type = 'Material';
  4576. this.fog = true;
  4577. this.blending = NormalBlending;
  4578. this.side = FrontSide;
  4579. this.vertexColors = false;
  4580. this.opacity = 1;
  4581. this.transparent = false;
  4582. this.blendSrc = SrcAlphaFactor;
  4583. this.blendDst = OneMinusSrcAlphaFactor;
  4584. this.blendEquation = AddEquation;
  4585. this.blendSrcAlpha = null;
  4586. this.blendDstAlpha = null;
  4587. this.blendEquationAlpha = null;
  4588. this.depthFunc = LessEqualDepth;
  4589. this.depthTest = true;
  4590. this.depthWrite = true;
  4591. this.stencilWriteMask = 0xff;
  4592. this.stencilFunc = AlwaysStencilFunc;
  4593. this.stencilRef = 0;
  4594. this.stencilFuncMask = 0xff;
  4595. this.stencilFail = KeepStencilOp;
  4596. this.stencilZFail = KeepStencilOp;
  4597. this.stencilZPass = KeepStencilOp;
  4598. this.stencilWrite = false;
  4599. this.clippingPlanes = null;
  4600. this.clipIntersection = false;
  4601. this.clipShadows = false;
  4602. this.shadowSide = null;
  4603. this.colorWrite = true;
  4604. this.precision = null; // override the renderer's default precision for this material
  4605. this.polygonOffset = false;
  4606. this.polygonOffsetFactor = 0;
  4607. this.polygonOffsetUnits = 0;
  4608. this.dithering = false;
  4609. this.alphaTest = 0;
  4610. this.alphaToCoverage = false;
  4611. this.premultipliedAlpha = false;
  4612. this.visible = true;
  4613. this.toneMapped = true;
  4614. this.userData = {};
  4615. this.version = 0;
  4616. }
  4617. onBuild( /* shaderobject, renderer */ ) {}
  4618. onBeforeCompile( /* shaderobject, renderer */ ) {}
  4619. customProgramCacheKey() {
  4620. return this.onBeforeCompile.toString();
  4621. }
  4622. setValues( values ) {
  4623. if ( values === undefined ) return;
  4624. for ( const key in values ) {
  4625. const newValue = values[ key ];
  4626. if ( newValue === undefined ) {
  4627. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  4628. continue;
  4629. }
  4630. // for backward compatability if shading is set in the constructor
  4631. if ( key === 'shading' ) {
  4632. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  4633. this.flatShading = ( newValue === FlatShading ) ? true : false;
  4634. continue;
  4635. }
  4636. const currentValue = this[ key ];
  4637. if ( currentValue === undefined ) {
  4638. console.warn( 'THREE.' + this.type + ': \'' + key + '\' is not a property of this material.' );
  4639. continue;
  4640. }
  4641. if ( currentValue && currentValue.isColor ) {
  4642. currentValue.set( newValue );
  4643. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  4644. currentValue.copy( newValue );
  4645. } else {
  4646. this[ key ] = newValue;
  4647. }
  4648. }
  4649. }
  4650. toJSON( meta ) {
  4651. const isRoot = ( meta === undefined || typeof meta === 'string' );
  4652. if ( isRoot ) {
  4653. meta = {
  4654. textures: {},
  4655. images: {}
  4656. };
  4657. }
  4658. const data = {
  4659. metadata: {
  4660. version: 4.5,
  4661. type: 'Material',
  4662. generator: 'Material.toJSON'
  4663. }
  4664. };
  4665. // standard Material serialization
  4666. data.uuid = this.uuid;
  4667. data.type = this.type;
  4668. if ( this.name !== '' ) data.name = this.name;
  4669. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  4670. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  4671. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  4672. if ( this.sheen && this.sheen.isColor ) data.sheen = this.sheen.getHex();
  4673. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  4674. if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  4675. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  4676. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  4677. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  4678. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  4679. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  4680. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  4681. }
  4682. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  4683. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  4684. }
  4685. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  4686. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  4687. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  4688. }
  4689. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  4690. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  4691. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  4692. if ( this.lightMap && this.lightMap.isTexture ) {
  4693. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  4694. data.lightMapIntensity = this.lightMapIntensity;
  4695. }
  4696. if ( this.aoMap && this.aoMap.isTexture ) {
  4697. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  4698. data.aoMapIntensity = this.aoMapIntensity;
  4699. }
  4700. if ( this.bumpMap && this.bumpMap.isTexture ) {
  4701. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  4702. data.bumpScale = this.bumpScale;
  4703. }
  4704. if ( this.normalMap && this.normalMap.isTexture ) {
  4705. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  4706. data.normalMapType = this.normalMapType;
  4707. data.normalScale = this.normalScale.toArray();
  4708. }
  4709. if ( this.displacementMap && this.displacementMap.isTexture ) {
  4710. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  4711. data.displacementScale = this.displacementScale;
  4712. data.displacementBias = this.displacementBias;
  4713. }
  4714. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  4715. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  4716. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  4717. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  4718. if ( this.envMap && this.envMap.isTexture ) {
  4719. data.envMap = this.envMap.toJSON( meta ).uuid;
  4720. if ( this.combine !== undefined ) data.combine = this.combine;
  4721. }
  4722. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  4723. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  4724. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  4725. if ( this.gradientMap && this.gradientMap.isTexture ) {
  4726. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  4727. }
  4728. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  4729. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  4730. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  4731. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  4732. if ( this.attenuationDistance !== undefined ) data.attenuationDistance = this.attenuationDistance;
  4733. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  4734. if ( this.size !== undefined ) data.size = this.size;
  4735. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  4736. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  4737. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  4738. if ( this.side !== FrontSide ) data.side = this.side;
  4739. if ( this.vertexColors ) data.vertexColors = true;
  4740. if ( this.opacity < 1 ) data.opacity = this.opacity;
  4741. if ( this.transparent === true ) data.transparent = this.transparent;
  4742. data.depthFunc = this.depthFunc;
  4743. data.depthTest = this.depthTest;
  4744. data.depthWrite = this.depthWrite;
  4745. data.colorWrite = this.colorWrite;
  4746. data.stencilWrite = this.stencilWrite;
  4747. data.stencilWriteMask = this.stencilWriteMask;
  4748. data.stencilFunc = this.stencilFunc;
  4749. data.stencilRef = this.stencilRef;
  4750. data.stencilFuncMask = this.stencilFuncMask;
  4751. data.stencilFail = this.stencilFail;
  4752. data.stencilZFail = this.stencilZFail;
  4753. data.stencilZPass = this.stencilZPass;
  4754. // rotation (SpriteMaterial)
  4755. if ( this.rotation && this.rotation !== 0 ) data.rotation = this.rotation;
  4756. if ( this.polygonOffset === true ) data.polygonOffset = true;
  4757. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  4758. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  4759. if ( this.linewidth && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  4760. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  4761. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  4762. if ( this.scale !== undefined ) data.scale = this.scale;
  4763. if ( this.dithering === true ) data.dithering = true;
  4764. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  4765. if ( this.alphaToCoverage === true ) data.alphaToCoverage = this.alphaToCoverage;
  4766. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  4767. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  4768. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  4769. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  4770. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  4771. if ( this.morphTargets === true ) data.morphTargets = true;
  4772. if ( this.morphNormals === true ) data.morphNormals = true;
  4773. if ( this.flatShading === true ) data.flatShading = this.flatShading;
  4774. if ( this.visible === false ) data.visible = false;
  4775. if ( this.toneMapped === false ) data.toneMapped = false;
  4776. if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData;
  4777. // TODO: Copied from Object3D.toJSON
  4778. function extractFromCache( cache ) {
  4779. const values = [];
  4780. for ( const key in cache ) {
  4781. const data = cache[ key ];
  4782. delete data.metadata;
  4783. values.push( data );
  4784. }
  4785. return values;
  4786. }
  4787. if ( isRoot ) {
  4788. const textures = extractFromCache( meta.textures );
  4789. const images = extractFromCache( meta.images );
  4790. if ( textures.length > 0 ) data.textures = textures;
  4791. if ( images.length > 0 ) data.images = images;
  4792. }
  4793. return data;
  4794. }
  4795. clone() {
  4796. return new this.constructor().copy( this );
  4797. }
  4798. copy( source ) {
  4799. this.name = source.name;
  4800. this.fog = source.fog;
  4801. this.blending = source.blending;
  4802. this.side = source.side;
  4803. this.vertexColors = source.vertexColors;
  4804. this.opacity = source.opacity;
  4805. this.transparent = source.transparent;
  4806. this.blendSrc = source.blendSrc;
  4807. this.blendDst = source.blendDst;
  4808. this.blendEquation = source.blendEquation;
  4809. this.blendSrcAlpha = source.blendSrcAlpha;
  4810. this.blendDstAlpha = source.blendDstAlpha;
  4811. this.blendEquationAlpha = source.blendEquationAlpha;
  4812. this.depthFunc = source.depthFunc;
  4813. this.depthTest = source.depthTest;
  4814. this.depthWrite = source.depthWrite;
  4815. this.stencilWriteMask = source.stencilWriteMask;
  4816. this.stencilFunc = source.stencilFunc;
  4817. this.stencilRef = source.stencilRef;
  4818. this.stencilFuncMask = source.stencilFuncMask;
  4819. this.stencilFail = source.stencilFail;
  4820. this.stencilZFail = source.stencilZFail;
  4821. this.stencilZPass = source.stencilZPass;
  4822. this.stencilWrite = source.stencilWrite;
  4823. const srcPlanes = source.clippingPlanes;
  4824. let dstPlanes = null;
  4825. if ( srcPlanes !== null ) {
  4826. const n = srcPlanes.length;
  4827. dstPlanes = new Array( n );
  4828. for ( let i = 0; i !== n; ++ i ) {
  4829. dstPlanes[ i ] = srcPlanes[ i ].clone();
  4830. }
  4831. }
  4832. this.clippingPlanes = dstPlanes;
  4833. this.clipIntersection = source.clipIntersection;
  4834. this.clipShadows = source.clipShadows;
  4835. this.shadowSide = source.shadowSide;
  4836. this.colorWrite = source.colorWrite;
  4837. this.precision = source.precision;
  4838. this.polygonOffset = source.polygonOffset;
  4839. this.polygonOffsetFactor = source.polygonOffsetFactor;
  4840. this.polygonOffsetUnits = source.polygonOffsetUnits;
  4841. this.dithering = source.dithering;
  4842. this.alphaTest = source.alphaTest;
  4843. this.alphaToCoverage = source.alphaToCoverage;
  4844. this.premultipliedAlpha = source.premultipliedAlpha;
  4845. this.visible = source.visible;
  4846. this.toneMapped = source.toneMapped;
  4847. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4848. return this;
  4849. }
  4850. dispose() {
  4851. this.dispatchEvent( { type: 'dispose' } );
  4852. }
  4853. set needsUpdate( value ) {
  4854. if ( value === true ) this.version ++;
  4855. }
  4856. }
  4857. Material.prototype.isMaterial = true;
  4858. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  4859. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  4860. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  4861. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  4862. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  4863. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  4864. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  4865. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  4866. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  4867. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  4868. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  4869. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  4870. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  4871. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  4872. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  4873. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  4874. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  4875. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  4876. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  4877. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  4878. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  4879. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  4880. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  4881. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  4882. const _hslA = { h: 0, s: 0, l: 0 };
  4883. const _hslB = { h: 0, s: 0, l: 0 };
  4884. function hue2rgb( p, q, t ) {
  4885. if ( t < 0 ) t += 1;
  4886. if ( t > 1 ) t -= 1;
  4887. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  4888. if ( t < 1 / 2 ) return q;
  4889. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  4890. return p;
  4891. }
  4892. function SRGBToLinear( c ) {
  4893. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  4894. }
  4895. function LinearToSRGB( c ) {
  4896. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  4897. }
  4898. class Color {
  4899. constructor( r, g, b ) {
  4900. if ( g === undefined && b === undefined ) {
  4901. // r is THREE.Color, hex or string
  4902. return this.set( r );
  4903. }
  4904. return this.setRGB( r, g, b );
  4905. }
  4906. set( value ) {
  4907. if ( value && value.isColor ) {
  4908. this.copy( value );
  4909. } else if ( typeof value === 'number' ) {
  4910. this.setHex( value );
  4911. } else if ( typeof value === 'string' ) {
  4912. this.setStyle( value );
  4913. }
  4914. return this;
  4915. }
  4916. setScalar( scalar ) {
  4917. this.r = scalar;
  4918. this.g = scalar;
  4919. this.b = scalar;
  4920. return this;
  4921. }
  4922. setHex( hex ) {
  4923. hex = Math.floor( hex );
  4924. this.r = ( hex >> 16 & 255 ) / 255;
  4925. this.g = ( hex >> 8 & 255 ) / 255;
  4926. this.b = ( hex & 255 ) / 255;
  4927. return this;
  4928. }
  4929. setRGB( r, g, b ) {
  4930. this.r = r;
  4931. this.g = g;
  4932. this.b = b;
  4933. return this;
  4934. }
  4935. setHSL( h, s, l ) {
  4936. // h,s,l ranges are in 0.0 - 1.0
  4937. h = euclideanModulo( h, 1 );
  4938. s = clamp( s, 0, 1 );
  4939. l = clamp( l, 0, 1 );
  4940. if ( s === 0 ) {
  4941. this.r = this.g = this.b = l;
  4942. } else {
  4943. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  4944. const q = ( 2 * l ) - p;
  4945. this.r = hue2rgb( q, p, h + 1 / 3 );
  4946. this.g = hue2rgb( q, p, h );
  4947. this.b = hue2rgb( q, p, h - 1 / 3 );
  4948. }
  4949. return this;
  4950. }
  4951. setStyle( style ) {
  4952. function handleAlpha( string ) {
  4953. if ( string === undefined ) return;
  4954. if ( parseFloat( string ) < 1 ) {
  4955. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  4956. }
  4957. }
  4958. let m;
  4959. if ( m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec( style ) ) {
  4960. // rgb / hsl
  4961. let color;
  4962. const name = m[ 1 ];
  4963. const components = m[ 2 ];
  4964. switch ( name ) {
  4965. case 'rgb':
  4966. case 'rgba':
  4967. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  4968. // rgb(255,0,0) rgba(255,0,0,0.5)
  4969. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  4970. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  4971. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  4972. handleAlpha( color[ 4 ] );
  4973. return this;
  4974. }
  4975. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  4976. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  4977. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  4978. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  4979. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  4980. handleAlpha( color[ 4 ] );
  4981. return this;
  4982. }
  4983. break;
  4984. case 'hsl':
  4985. case 'hsla':
  4986. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  4987. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  4988. const h = parseFloat( color[ 1 ] ) / 360;
  4989. const s = parseInt( color[ 2 ], 10 ) / 100;
  4990. const l = parseInt( color[ 3 ], 10 ) / 100;
  4991. handleAlpha( color[ 4 ] );
  4992. return this.setHSL( h, s, l );
  4993. }
  4994. break;
  4995. }
  4996. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  4997. // hex color
  4998. const hex = m[ 1 ];
  4999. const size = hex.length;
  5000. if ( size === 3 ) {
  5001. // #ff0
  5002. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  5003. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  5004. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  5005. return this;
  5006. } else if ( size === 6 ) {
  5007. // #ff0000
  5008. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  5009. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  5010. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  5011. return this;
  5012. }
  5013. }
  5014. if ( style && style.length > 0 ) {
  5015. return this.setColorName( style );
  5016. }
  5017. return this;
  5018. }
  5019. setColorName( style ) {
  5020. // color keywords
  5021. const hex = _colorKeywords[ style.toLowerCase() ];
  5022. if ( hex !== undefined ) {
  5023. // red
  5024. this.setHex( hex );
  5025. } else {
  5026. // unknown color
  5027. console.warn( 'THREE.Color: Unknown color ' + style );
  5028. }
  5029. return this;
  5030. }
  5031. clone() {
  5032. return new this.constructor( this.r, this.g, this.b );
  5033. }
  5034. copy( color ) {
  5035. this.r = color.r;
  5036. this.g = color.g;
  5037. this.b = color.b;
  5038. return this;
  5039. }
  5040. copyGammaToLinear( color, gammaFactor = 2.0 ) {
  5041. this.r = Math.pow( color.r, gammaFactor );
  5042. this.g = Math.pow( color.g, gammaFactor );
  5043. this.b = Math.pow( color.b, gammaFactor );
  5044. return this;
  5045. }
  5046. copyLinearToGamma( color, gammaFactor = 2.0 ) {
  5047. const safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  5048. this.r = Math.pow( color.r, safeInverse );
  5049. this.g = Math.pow( color.g, safeInverse );
  5050. this.b = Math.pow( color.b, safeInverse );
  5051. return this;
  5052. }
  5053. convertGammaToLinear( gammaFactor ) {
  5054. this.copyGammaToLinear( this, gammaFactor );
  5055. return this;
  5056. }
  5057. convertLinearToGamma( gammaFactor ) {
  5058. this.copyLinearToGamma( this, gammaFactor );
  5059. return this;
  5060. }
  5061. copySRGBToLinear( color ) {
  5062. this.r = SRGBToLinear( color.r );
  5063. this.g = SRGBToLinear( color.g );
  5064. this.b = SRGBToLinear( color.b );
  5065. return this;
  5066. }
  5067. copyLinearToSRGB( color ) {
  5068. this.r = LinearToSRGB( color.r );
  5069. this.g = LinearToSRGB( color.g );
  5070. this.b = LinearToSRGB( color.b );
  5071. return this;
  5072. }
  5073. convertSRGBToLinear() {
  5074. this.copySRGBToLinear( this );
  5075. return this;
  5076. }
  5077. convertLinearToSRGB() {
  5078. this.copyLinearToSRGB( this );
  5079. return this;
  5080. }
  5081. getHex() {
  5082. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  5083. }
  5084. getHexString() {
  5085. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  5086. }
  5087. getHSL( target ) {
  5088. // h,s,l ranges are in 0.0 - 1.0
  5089. const r = this.r, g = this.g, b = this.b;
  5090. const max = Math.max( r, g, b );
  5091. const min = Math.min( r, g, b );
  5092. let hue, saturation;
  5093. const lightness = ( min + max ) / 2.0;
  5094. if ( min === max ) {
  5095. hue = 0;
  5096. saturation = 0;
  5097. } else {
  5098. const delta = max - min;
  5099. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  5100. switch ( max ) {
  5101. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  5102. case g: hue = ( b - r ) / delta + 2; break;
  5103. case b: hue = ( r - g ) / delta + 4; break;
  5104. }
  5105. hue /= 6;
  5106. }
  5107. target.h = hue;
  5108. target.s = saturation;
  5109. target.l = lightness;
  5110. return target;
  5111. }
  5112. getStyle() {
  5113. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  5114. }
  5115. offsetHSL( h, s, l ) {
  5116. this.getHSL( _hslA );
  5117. _hslA.h += h; _hslA.s += s; _hslA.l += l;
  5118. this.setHSL( _hslA.h, _hslA.s, _hslA.l );
  5119. return this;
  5120. }
  5121. add( color ) {
  5122. this.r += color.r;
  5123. this.g += color.g;
  5124. this.b += color.b;
  5125. return this;
  5126. }
  5127. addColors( color1, color2 ) {
  5128. this.r = color1.r + color2.r;
  5129. this.g = color1.g + color2.g;
  5130. this.b = color1.b + color2.b;
  5131. return this;
  5132. }
  5133. addScalar( s ) {
  5134. this.r += s;
  5135. this.g += s;
  5136. this.b += s;
  5137. return this;
  5138. }
  5139. sub( color ) {
  5140. this.r = Math.max( 0, this.r - color.r );
  5141. this.g = Math.max( 0, this.g - color.g );
  5142. this.b = Math.max( 0, this.b - color.b );
  5143. return this;
  5144. }
  5145. multiply( color ) {
  5146. this.r *= color.r;
  5147. this.g *= color.g;
  5148. this.b *= color.b;
  5149. return this;
  5150. }
  5151. multiplyScalar( s ) {
  5152. this.r *= s;
  5153. this.g *= s;
  5154. this.b *= s;
  5155. return this;
  5156. }
  5157. lerp( color, alpha ) {
  5158. this.r += ( color.r - this.r ) * alpha;
  5159. this.g += ( color.g - this.g ) * alpha;
  5160. this.b += ( color.b - this.b ) * alpha;
  5161. return this;
  5162. }
  5163. lerpColors( color1, color2, alpha ) {
  5164. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  5165. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  5166. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  5167. return this;
  5168. }
  5169. lerpHSL( color, alpha ) {
  5170. this.getHSL( _hslA );
  5171. color.getHSL( _hslB );
  5172. const h = lerp( _hslA.h, _hslB.h, alpha );
  5173. const s = lerp( _hslA.s, _hslB.s, alpha );
  5174. const l = lerp( _hslA.l, _hslB.l, alpha );
  5175. this.setHSL( h, s, l );
  5176. return this;
  5177. }
  5178. equals( c ) {
  5179. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  5180. }
  5181. fromArray( array, offset = 0 ) {
  5182. this.r = array[ offset ];
  5183. this.g = array[ offset + 1 ];
  5184. this.b = array[ offset + 2 ];
  5185. return this;
  5186. }
  5187. toArray( array = [], offset = 0 ) {
  5188. array[ offset ] = this.r;
  5189. array[ offset + 1 ] = this.g;
  5190. array[ offset + 2 ] = this.b;
  5191. return array;
  5192. }
  5193. fromBufferAttribute( attribute, index ) {
  5194. this.r = attribute.getX( index );
  5195. this.g = attribute.getY( index );
  5196. this.b = attribute.getZ( index );
  5197. if ( attribute.normalized === true ) {
  5198. // assuming Uint8Array
  5199. this.r /= 255;
  5200. this.g /= 255;
  5201. this.b /= 255;
  5202. }
  5203. return this;
  5204. }
  5205. toJSON() {
  5206. return this.getHex();
  5207. }
  5208. }
  5209. Color.NAMES = _colorKeywords;
  5210. Color.prototype.isColor = true;
  5211. Color.prototype.r = 1;
  5212. Color.prototype.g = 1;
  5213. Color.prototype.b = 1;
  5214. /**
  5215. * parameters = {
  5216. * color: <hex>,
  5217. * opacity: <float>,
  5218. * map: new THREE.Texture( <Image> ),
  5219. *
  5220. * lightMap: new THREE.Texture( <Image> ),
  5221. * lightMapIntensity: <float>
  5222. *
  5223. * aoMap: new THREE.Texture( <Image> ),
  5224. * aoMapIntensity: <float>
  5225. *
  5226. * specularMap: new THREE.Texture( <Image> ),
  5227. *
  5228. * alphaMap: new THREE.Texture( <Image> ),
  5229. *
  5230. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  5231. * combine: THREE.Multiply,
  5232. * reflectivity: <float>,
  5233. * refractionRatio: <float>,
  5234. *
  5235. * depthTest: <bool>,
  5236. * depthWrite: <bool>,
  5237. *
  5238. * wireframe: <boolean>,
  5239. * wireframeLinewidth: <float>,
  5240. *
  5241. * morphTargets: <bool>
  5242. * }
  5243. */
  5244. class MeshBasicMaterial extends Material {
  5245. constructor( parameters ) {
  5246. super();
  5247. this.type = 'MeshBasicMaterial';
  5248. this.color = new Color( 0xffffff ); // emissive
  5249. this.map = null;
  5250. this.lightMap = null;
  5251. this.lightMapIntensity = 1.0;
  5252. this.aoMap = null;
  5253. this.aoMapIntensity = 1.0;
  5254. this.specularMap = null;
  5255. this.alphaMap = null;
  5256. this.envMap = null;
  5257. this.combine = MultiplyOperation;
  5258. this.reflectivity = 1;
  5259. this.refractionRatio = 0.98;
  5260. this.wireframe = false;
  5261. this.wireframeLinewidth = 1;
  5262. this.wireframeLinecap = 'round';
  5263. this.wireframeLinejoin = 'round';
  5264. this.morphTargets = false;
  5265. this.setValues( parameters );
  5266. }
  5267. copy( source ) {
  5268. super.copy( source );
  5269. this.color.copy( source.color );
  5270. this.map = source.map;
  5271. this.lightMap = source.lightMap;
  5272. this.lightMapIntensity = source.lightMapIntensity;
  5273. this.aoMap = source.aoMap;
  5274. this.aoMapIntensity = source.aoMapIntensity;
  5275. this.specularMap = source.specularMap;
  5276. this.alphaMap = source.alphaMap;
  5277. this.envMap = source.envMap;
  5278. this.combine = source.combine;
  5279. this.reflectivity = source.reflectivity;
  5280. this.refractionRatio = source.refractionRatio;
  5281. this.wireframe = source.wireframe;
  5282. this.wireframeLinewidth = source.wireframeLinewidth;
  5283. this.wireframeLinecap = source.wireframeLinecap;
  5284. this.wireframeLinejoin = source.wireframeLinejoin;
  5285. this.morphTargets = source.morphTargets;
  5286. return this;
  5287. }
  5288. }
  5289. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  5290. const _vector$9 = /*@__PURE__*/ new Vector3();
  5291. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5292. class BufferAttribute {
  5293. constructor( array, itemSize, normalized ) {
  5294. if ( Array.isArray( array ) ) {
  5295. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5296. }
  5297. this.name = '';
  5298. this.array = array;
  5299. this.itemSize = itemSize;
  5300. this.count = array !== undefined ? array.length / itemSize : 0;
  5301. this.normalized = normalized === true;
  5302. this.usage = StaticDrawUsage;
  5303. this.updateRange = { offset: 0, count: - 1 };
  5304. this.version = 0;
  5305. }
  5306. onUploadCallback() {}
  5307. set needsUpdate( value ) {
  5308. if ( value === true ) this.version ++;
  5309. }
  5310. setUsage( value ) {
  5311. this.usage = value;
  5312. return this;
  5313. }
  5314. copy( source ) {
  5315. this.name = source.name;
  5316. this.array = new source.array.constructor( source.array );
  5317. this.itemSize = source.itemSize;
  5318. this.count = source.count;
  5319. this.normalized = source.normalized;
  5320. this.usage = source.usage;
  5321. return this;
  5322. }
  5323. copyAt( index1, attribute, index2 ) {
  5324. index1 *= this.itemSize;
  5325. index2 *= attribute.itemSize;
  5326. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  5327. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5328. }
  5329. return this;
  5330. }
  5331. copyArray( array ) {
  5332. this.array.set( array );
  5333. return this;
  5334. }
  5335. copyColorsArray( colors ) {
  5336. const array = this.array;
  5337. let offset = 0;
  5338. for ( let i = 0, l = colors.length; i < l; i ++ ) {
  5339. let color = colors[ i ];
  5340. if ( color === undefined ) {
  5341. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  5342. color = new Color();
  5343. }
  5344. array[ offset ++ ] = color.r;
  5345. array[ offset ++ ] = color.g;
  5346. array[ offset ++ ] = color.b;
  5347. }
  5348. return this;
  5349. }
  5350. copyVector2sArray( vectors ) {
  5351. const array = this.array;
  5352. let offset = 0;
  5353. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  5354. let vector = vectors[ i ];
  5355. if ( vector === undefined ) {
  5356. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  5357. vector = new Vector2();
  5358. }
  5359. array[ offset ++ ] = vector.x;
  5360. array[ offset ++ ] = vector.y;
  5361. }
  5362. return this;
  5363. }
  5364. copyVector3sArray( vectors ) {
  5365. const array = this.array;
  5366. let offset = 0;
  5367. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  5368. let vector = vectors[ i ];
  5369. if ( vector === undefined ) {
  5370. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  5371. vector = new Vector3();
  5372. }
  5373. array[ offset ++ ] = vector.x;
  5374. array[ offset ++ ] = vector.y;
  5375. array[ offset ++ ] = vector.z;
  5376. }
  5377. return this;
  5378. }
  5379. copyVector4sArray( vectors ) {
  5380. const array = this.array;
  5381. let offset = 0;
  5382. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  5383. let vector = vectors[ i ];
  5384. if ( vector === undefined ) {
  5385. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  5386. vector = new Vector4();
  5387. }
  5388. array[ offset ++ ] = vector.x;
  5389. array[ offset ++ ] = vector.y;
  5390. array[ offset ++ ] = vector.z;
  5391. array[ offset ++ ] = vector.w;
  5392. }
  5393. return this;
  5394. }
  5395. applyMatrix3( m ) {
  5396. if ( this.itemSize === 2 ) {
  5397. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5398. _vector2$1.fromBufferAttribute( this, i );
  5399. _vector2$1.applyMatrix3( m );
  5400. this.setXY( i, _vector2$1.x, _vector2$1.y );
  5401. }
  5402. } else if ( this.itemSize === 3 ) {
  5403. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5404. _vector$9.fromBufferAttribute( this, i );
  5405. _vector$9.applyMatrix3( m );
  5406. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5407. }
  5408. }
  5409. return this;
  5410. }
  5411. applyMatrix4( m ) {
  5412. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5413. _vector$9.x = this.getX( i );
  5414. _vector$9.y = this.getY( i );
  5415. _vector$9.z = this.getZ( i );
  5416. _vector$9.applyMatrix4( m );
  5417. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5418. }
  5419. return this;
  5420. }
  5421. applyNormalMatrix( m ) {
  5422. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5423. _vector$9.x = this.getX( i );
  5424. _vector$9.y = this.getY( i );
  5425. _vector$9.z = this.getZ( i );
  5426. _vector$9.applyNormalMatrix( m );
  5427. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5428. }
  5429. return this;
  5430. }
  5431. transformDirection( m ) {
  5432. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5433. _vector$9.x = this.getX( i );
  5434. _vector$9.y = this.getY( i );
  5435. _vector$9.z = this.getZ( i );
  5436. _vector$9.transformDirection( m );
  5437. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5438. }
  5439. return this;
  5440. }
  5441. set( value, offset = 0 ) {
  5442. this.array.set( value, offset );
  5443. return this;
  5444. }
  5445. getX( index ) {
  5446. return this.array[ index * this.itemSize ];
  5447. }
  5448. setX( index, x ) {
  5449. this.array[ index * this.itemSize ] = x;
  5450. return this;
  5451. }
  5452. getY( index ) {
  5453. return this.array[ index * this.itemSize + 1 ];
  5454. }
  5455. setY( index, y ) {
  5456. this.array[ index * this.itemSize + 1 ] = y;
  5457. return this;
  5458. }
  5459. getZ( index ) {
  5460. return this.array[ index * this.itemSize + 2 ];
  5461. }
  5462. setZ( index, z ) {
  5463. this.array[ index * this.itemSize + 2 ] = z;
  5464. return this;
  5465. }
  5466. getW( index ) {
  5467. return this.array[ index * this.itemSize + 3 ];
  5468. }
  5469. setW( index, w ) {
  5470. this.array[ index * this.itemSize + 3 ] = w;
  5471. return this;
  5472. }
  5473. setXY( index, x, y ) {
  5474. index *= this.itemSize;
  5475. this.array[ index + 0 ] = x;
  5476. this.array[ index + 1 ] = y;
  5477. return this;
  5478. }
  5479. setXYZ( index, x, y, z ) {
  5480. index *= this.itemSize;
  5481. this.array[ index + 0 ] = x;
  5482. this.array[ index + 1 ] = y;
  5483. this.array[ index + 2 ] = z;
  5484. return this;
  5485. }
  5486. setXYZW( index, x, y, z, w ) {
  5487. index *= this.itemSize;
  5488. this.array[ index + 0 ] = x;
  5489. this.array[ index + 1 ] = y;
  5490. this.array[ index + 2 ] = z;
  5491. this.array[ index + 3 ] = w;
  5492. return this;
  5493. }
  5494. onUpload( callback ) {
  5495. this.onUploadCallback = callback;
  5496. return this;
  5497. }
  5498. clone() {
  5499. return new this.constructor( this.array, this.itemSize ).copy( this );
  5500. }
  5501. toJSON() {
  5502. const data = {
  5503. itemSize: this.itemSize,
  5504. type: this.array.constructor.name,
  5505. array: Array.prototype.slice.call( this.array ),
  5506. normalized: this.normalized
  5507. };
  5508. if ( this.name !== '' ) data.name = this.name;
  5509. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  5510. if ( this.updateRange.offset !== 0 || this.updateRange.count !== - 1 ) data.updateRange = this.updateRange;
  5511. return data;
  5512. }
  5513. }
  5514. BufferAttribute.prototype.isBufferAttribute = true;
  5515. class Uint16BufferAttribute extends BufferAttribute {
  5516. constructor( array, itemSize, normalized ) {
  5517. super( new Uint16Array( array ), itemSize, normalized );
  5518. }
  5519. }
  5520. class Uint32BufferAttribute extends BufferAttribute {
  5521. constructor( array, itemSize, normalized ) {
  5522. super( new Uint32Array( array ), itemSize, normalized );
  5523. }
  5524. }
  5525. class Float16BufferAttribute extends BufferAttribute {
  5526. constructor( array, itemSize, normalized ) {
  5527. super( new Uint16Array( array ), itemSize, normalized );
  5528. }
  5529. }
  5530. Float16BufferAttribute.prototype.isFloat16BufferAttribute = true;
  5531. class Float32BufferAttribute extends BufferAttribute {
  5532. constructor( array, itemSize, normalized ) {
  5533. super( new Float32Array( array ), itemSize, normalized );
  5534. }
  5535. }
  5536. function arrayMax( array ) {
  5537. if ( array.length === 0 ) return - Infinity;
  5538. let max = array[ 0 ];
  5539. for ( let i = 1, l = array.length; i < l; ++ i ) {
  5540. if ( array[ i ] > max ) max = array[ i ];
  5541. }
  5542. return max;
  5543. }
  5544. let _id = 0;
  5545. const _m1 = /*@__PURE__*/ new Matrix4();
  5546. const _obj = /*@__PURE__*/ new Object3D();
  5547. const _offset$1 = /*@__PURE__*/ new Vector3();
  5548. const _box$1 = /*@__PURE__*/ new Box3();
  5549. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  5550. const _vector$8 = /*@__PURE__*/ new Vector3();
  5551. class BufferGeometry extends EventDispatcher {
  5552. constructor() {
  5553. super();
  5554. Object.defineProperty( this, 'id', { value: _id ++ } );
  5555. this.uuid = generateUUID();
  5556. this.name = '';
  5557. this.type = 'BufferGeometry';
  5558. this.index = null;
  5559. this.attributes = {};
  5560. this.morphAttributes = {};
  5561. this.morphTargetsRelative = false;
  5562. this.groups = [];
  5563. this.boundingBox = null;
  5564. this.boundingSphere = null;
  5565. this.drawRange = { start: 0, count: Infinity };
  5566. this.userData = {};
  5567. }
  5568. getIndex() {
  5569. return this.index;
  5570. }
  5571. setIndex( index ) {
  5572. if ( Array.isArray( index ) ) {
  5573. this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  5574. } else {
  5575. this.index = index;
  5576. }
  5577. return this;
  5578. }
  5579. getAttribute( name ) {
  5580. return this.attributes[ name ];
  5581. }
  5582. setAttribute( name, attribute ) {
  5583. this.attributes[ name ] = attribute;
  5584. return this;
  5585. }
  5586. deleteAttribute( name ) {
  5587. delete this.attributes[ name ];
  5588. return this;
  5589. }
  5590. hasAttribute( name ) {
  5591. return this.attributes[ name ] !== undefined;
  5592. }
  5593. addGroup( start, count, materialIndex = 0 ) {
  5594. this.groups.push( {
  5595. start: start,
  5596. count: count,
  5597. materialIndex: materialIndex
  5598. } );
  5599. }
  5600. clearGroups() {
  5601. this.groups = [];
  5602. }
  5603. setDrawRange( start, count ) {
  5604. this.drawRange.start = start;
  5605. this.drawRange.count = count;
  5606. }
  5607. applyMatrix4( matrix ) {
  5608. const position = this.attributes.position;
  5609. if ( position !== undefined ) {
  5610. position.applyMatrix4( matrix );
  5611. position.needsUpdate = true;
  5612. }
  5613. const normal = this.attributes.normal;
  5614. if ( normal !== undefined ) {
  5615. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  5616. normal.applyNormalMatrix( normalMatrix );
  5617. normal.needsUpdate = true;
  5618. }
  5619. const tangent = this.attributes.tangent;
  5620. if ( tangent !== undefined ) {
  5621. tangent.transformDirection( matrix );
  5622. tangent.needsUpdate = true;
  5623. }
  5624. if ( this.boundingBox !== null ) {
  5625. this.computeBoundingBox();
  5626. }
  5627. if ( this.boundingSphere !== null ) {
  5628. this.computeBoundingSphere();
  5629. }
  5630. return this;
  5631. }
  5632. applyQuaternion( q ) {
  5633. _m1.makeRotationFromQuaternion( q );
  5634. this.applyMatrix4( _m1 );
  5635. return this;
  5636. }
  5637. rotateX( angle ) {
  5638. // rotate geometry around world x-axis
  5639. _m1.makeRotationX( angle );
  5640. this.applyMatrix4( _m1 );
  5641. return this;
  5642. }
  5643. rotateY( angle ) {
  5644. // rotate geometry around world y-axis
  5645. _m1.makeRotationY( angle );
  5646. this.applyMatrix4( _m1 );
  5647. return this;
  5648. }
  5649. rotateZ( angle ) {
  5650. // rotate geometry around world z-axis
  5651. _m1.makeRotationZ( angle );
  5652. this.applyMatrix4( _m1 );
  5653. return this;
  5654. }
  5655. translate( x, y, z ) {
  5656. // translate geometry
  5657. _m1.makeTranslation( x, y, z );
  5658. this.applyMatrix4( _m1 );
  5659. return this;
  5660. }
  5661. scale( x, y, z ) {
  5662. // scale geometry
  5663. _m1.makeScale( x, y, z );
  5664. this.applyMatrix4( _m1 );
  5665. return this;
  5666. }
  5667. lookAt( vector ) {
  5668. _obj.lookAt( vector );
  5669. _obj.updateMatrix();
  5670. this.applyMatrix4( _obj.matrix );
  5671. return this;
  5672. }
  5673. center() {
  5674. this.computeBoundingBox();
  5675. this.boundingBox.getCenter( _offset$1 ).negate();
  5676. this.translate( _offset$1.x, _offset$1.y, _offset$1.z );
  5677. return this;
  5678. }
  5679. setFromPoints( points ) {
  5680. const position = [];
  5681. for ( let i = 0, l = points.length; i < l; i ++ ) {
  5682. const point = points[ i ];
  5683. position.push( point.x, point.y, point.z || 0 );
  5684. }
  5685. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  5686. return this;
  5687. }
  5688. computeBoundingBox() {
  5689. if ( this.boundingBox === null ) {
  5690. this.boundingBox = new Box3();
  5691. }
  5692. const position = this.attributes.position;
  5693. const morphAttributesPosition = this.morphAttributes.position;
  5694. if ( position && position.isGLBufferAttribute ) {
  5695. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this );
  5696. this.boundingBox.set(
  5697. new Vector3( - Infinity, - Infinity, - Infinity ),
  5698. new Vector3( + Infinity, + Infinity, + Infinity )
  5699. );
  5700. return;
  5701. }
  5702. if ( position !== undefined ) {
  5703. this.boundingBox.setFromBufferAttribute( position );
  5704. // process morph attributes if present
  5705. if ( morphAttributesPosition ) {
  5706. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  5707. const morphAttribute = morphAttributesPosition[ i ];
  5708. _box$1.setFromBufferAttribute( morphAttribute );
  5709. if ( this.morphTargetsRelative ) {
  5710. _vector$8.addVectors( this.boundingBox.min, _box$1.min );
  5711. this.boundingBox.expandByPoint( _vector$8 );
  5712. _vector$8.addVectors( this.boundingBox.max, _box$1.max );
  5713. this.boundingBox.expandByPoint( _vector$8 );
  5714. } else {
  5715. this.boundingBox.expandByPoint( _box$1.min );
  5716. this.boundingBox.expandByPoint( _box$1.max );
  5717. }
  5718. }
  5719. }
  5720. } else {
  5721. this.boundingBox.makeEmpty();
  5722. }
  5723. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  5724. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  5725. }
  5726. }
  5727. computeBoundingSphere() {
  5728. if ( this.boundingSphere === null ) {
  5729. this.boundingSphere = new Sphere();
  5730. }
  5731. const position = this.attributes.position;
  5732. const morphAttributesPosition = this.morphAttributes.position;
  5733. if ( position && position.isGLBufferAttribute ) {
  5734. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this );
  5735. this.boundingSphere.set( new Vector3(), Infinity );
  5736. return;
  5737. }
  5738. if ( position ) {
  5739. // first, find the center of the bounding sphere
  5740. const center = this.boundingSphere.center;
  5741. _box$1.setFromBufferAttribute( position );
  5742. // process morph attributes if present
  5743. if ( morphAttributesPosition ) {
  5744. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  5745. const morphAttribute = morphAttributesPosition[ i ];
  5746. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  5747. if ( this.morphTargetsRelative ) {
  5748. _vector$8.addVectors( _box$1.min, _boxMorphTargets.min );
  5749. _box$1.expandByPoint( _vector$8 );
  5750. _vector$8.addVectors( _box$1.max, _boxMorphTargets.max );
  5751. _box$1.expandByPoint( _vector$8 );
  5752. } else {
  5753. _box$1.expandByPoint( _boxMorphTargets.min );
  5754. _box$1.expandByPoint( _boxMorphTargets.max );
  5755. }
  5756. }
  5757. }
  5758. _box$1.getCenter( center );
  5759. // second, try to find a boundingSphere with a radius smaller than the
  5760. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  5761. let maxRadiusSq = 0;
  5762. for ( let i = 0, il = position.count; i < il; i ++ ) {
  5763. _vector$8.fromBufferAttribute( position, i );
  5764. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  5765. }
  5766. // process morph attributes if present
  5767. if ( morphAttributesPosition ) {
  5768. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  5769. const morphAttribute = morphAttributesPosition[ i ];
  5770. const morphTargetsRelative = this.morphTargetsRelative;
  5771. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  5772. _vector$8.fromBufferAttribute( morphAttribute, j );
  5773. if ( morphTargetsRelative ) {
  5774. _offset$1.fromBufferAttribute( position, j );
  5775. _vector$8.add( _offset$1 );
  5776. }
  5777. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  5778. }
  5779. }
  5780. }
  5781. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  5782. if ( isNaN( this.boundingSphere.radius ) ) {
  5783. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  5784. }
  5785. }
  5786. }
  5787. computeFaceNormals() {
  5788. // backwards compatibility
  5789. }
  5790. computeTangents() {
  5791. const index = this.index;
  5792. const attributes = this.attributes;
  5793. // based on http://www.terathon.com/code/tangent.html
  5794. // (per vertex tangents)
  5795. if ( index === null ||
  5796. attributes.position === undefined ||
  5797. attributes.normal === undefined ||
  5798. attributes.uv === undefined ) {
  5799. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  5800. return;
  5801. }
  5802. const indices = index.array;
  5803. const positions = attributes.position.array;
  5804. const normals = attributes.normal.array;
  5805. const uvs = attributes.uv.array;
  5806. const nVertices = positions.length / 3;
  5807. if ( attributes.tangent === undefined ) {
  5808. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) );
  5809. }
  5810. const tangents = attributes.tangent.array;
  5811. const tan1 = [], tan2 = [];
  5812. for ( let i = 0; i < nVertices; i ++ ) {
  5813. tan1[ i ] = new Vector3();
  5814. tan2[ i ] = new Vector3();
  5815. }
  5816. const vA = new Vector3(),
  5817. vB = new Vector3(),
  5818. vC = new Vector3(),
  5819. uvA = new Vector2(),
  5820. uvB = new Vector2(),
  5821. uvC = new Vector2(),
  5822. sdir = new Vector3(),
  5823. tdir = new Vector3();
  5824. function handleTriangle( a, b, c ) {
  5825. vA.fromArray( positions, a * 3 );
  5826. vB.fromArray( positions, b * 3 );
  5827. vC.fromArray( positions, c * 3 );
  5828. uvA.fromArray( uvs, a * 2 );
  5829. uvB.fromArray( uvs, b * 2 );
  5830. uvC.fromArray( uvs, c * 2 );
  5831. vB.sub( vA );
  5832. vC.sub( vA );
  5833. uvB.sub( uvA );
  5834. uvC.sub( uvA );
  5835. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  5836. // silently ignore degenerate uv triangles having coincident or colinear vertices
  5837. if ( ! isFinite( r ) ) return;
  5838. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  5839. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  5840. tan1[ a ].add( sdir );
  5841. tan1[ b ].add( sdir );
  5842. tan1[ c ].add( sdir );
  5843. tan2[ a ].add( tdir );
  5844. tan2[ b ].add( tdir );
  5845. tan2[ c ].add( tdir );
  5846. }
  5847. let groups = this.groups;
  5848. if ( groups.length === 0 ) {
  5849. groups = [ {
  5850. start: 0,
  5851. count: indices.length
  5852. } ];
  5853. }
  5854. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  5855. const group = groups[ i ];
  5856. const start = group.start;
  5857. const count = group.count;
  5858. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  5859. handleTriangle(
  5860. indices[ j + 0 ],
  5861. indices[ j + 1 ],
  5862. indices[ j + 2 ]
  5863. );
  5864. }
  5865. }
  5866. const tmp = new Vector3(), tmp2 = new Vector3();
  5867. const n = new Vector3(), n2 = new Vector3();
  5868. function handleVertex( v ) {
  5869. n.fromArray( normals, v * 3 );
  5870. n2.copy( n );
  5871. const t = tan1[ v ];
  5872. // Gram-Schmidt orthogonalize
  5873. tmp.copy( t );
  5874. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5875. // Calculate handedness
  5876. tmp2.crossVectors( n2, t );
  5877. const test = tmp2.dot( tan2[ v ] );
  5878. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  5879. tangents[ v * 4 ] = tmp.x;
  5880. tangents[ v * 4 + 1 ] = tmp.y;
  5881. tangents[ v * 4 + 2 ] = tmp.z;
  5882. tangents[ v * 4 + 3 ] = w;
  5883. }
  5884. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  5885. const group = groups[ i ];
  5886. const start = group.start;
  5887. const count = group.count;
  5888. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  5889. handleVertex( indices[ j + 0 ] );
  5890. handleVertex( indices[ j + 1 ] );
  5891. handleVertex( indices[ j + 2 ] );
  5892. }
  5893. }
  5894. }
  5895. computeVertexNormals() {
  5896. const index = this.index;
  5897. const positionAttribute = this.getAttribute( 'position' );
  5898. if ( positionAttribute !== undefined ) {
  5899. let normalAttribute = this.getAttribute( 'normal' );
  5900. if ( normalAttribute === undefined ) {
  5901. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  5902. this.setAttribute( 'normal', normalAttribute );
  5903. } else {
  5904. // reset existing normals to zero
  5905. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  5906. normalAttribute.setXYZ( i, 0, 0, 0 );
  5907. }
  5908. }
  5909. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  5910. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  5911. const cb = new Vector3(), ab = new Vector3();
  5912. // indexed elements
  5913. if ( index ) {
  5914. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  5915. const vA = index.getX( i + 0 );
  5916. const vB = index.getX( i + 1 );
  5917. const vC = index.getX( i + 2 );
  5918. pA.fromBufferAttribute( positionAttribute, vA );
  5919. pB.fromBufferAttribute( positionAttribute, vB );
  5920. pC.fromBufferAttribute( positionAttribute, vC );
  5921. cb.subVectors( pC, pB );
  5922. ab.subVectors( pA, pB );
  5923. cb.cross( ab );
  5924. nA.fromBufferAttribute( normalAttribute, vA );
  5925. nB.fromBufferAttribute( normalAttribute, vB );
  5926. nC.fromBufferAttribute( normalAttribute, vC );
  5927. nA.add( cb );
  5928. nB.add( cb );
  5929. nC.add( cb );
  5930. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  5931. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  5932. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  5933. }
  5934. } else {
  5935. // non-indexed elements (unconnected triangle soup)
  5936. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  5937. pA.fromBufferAttribute( positionAttribute, i + 0 );
  5938. pB.fromBufferAttribute( positionAttribute, i + 1 );
  5939. pC.fromBufferAttribute( positionAttribute, i + 2 );
  5940. cb.subVectors( pC, pB );
  5941. ab.subVectors( pA, pB );
  5942. cb.cross( ab );
  5943. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  5944. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  5945. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  5946. }
  5947. }
  5948. this.normalizeNormals();
  5949. normalAttribute.needsUpdate = true;
  5950. }
  5951. }
  5952. merge( geometry, offset ) {
  5953. if ( ! ( geometry && geometry.isBufferGeometry ) ) {
  5954. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  5955. return;
  5956. }
  5957. if ( offset === undefined ) {
  5958. offset = 0;
  5959. console.warn(
  5960. 'THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. '
  5961. + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.'
  5962. );
  5963. }
  5964. const attributes = this.attributes;
  5965. for ( const key in attributes ) {
  5966. if ( geometry.attributes[ key ] === undefined ) continue;
  5967. const attribute1 = attributes[ key ];
  5968. const attributeArray1 = attribute1.array;
  5969. const attribute2 = geometry.attributes[ key ];
  5970. const attributeArray2 = attribute2.array;
  5971. const attributeOffset = attribute2.itemSize * offset;
  5972. const length = Math.min( attributeArray2.length, attributeArray1.length - attributeOffset );
  5973. for ( let i = 0, j = attributeOffset; i < length; i ++, j ++ ) {
  5974. attributeArray1[ j ] = attributeArray2[ i ];
  5975. }
  5976. }
  5977. return this;
  5978. }
  5979. normalizeNormals() {
  5980. const normals = this.attributes.normal;
  5981. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  5982. _vector$8.fromBufferAttribute( normals, i );
  5983. _vector$8.normalize();
  5984. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  5985. }
  5986. }
  5987. toNonIndexed() {
  5988. function convertBufferAttribute( attribute, indices ) {
  5989. const array = attribute.array;
  5990. const itemSize = attribute.itemSize;
  5991. const normalized = attribute.normalized;
  5992. const array2 = new array.constructor( indices.length * itemSize );
  5993. let index = 0, index2 = 0;
  5994. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  5995. if ( attribute.isInterleavedBufferAttribute ) {
  5996. index = indices[ i ] * attribute.data.stride + attribute.offset;
  5997. } else {
  5998. index = indices[ i ] * itemSize;
  5999. }
  6000. for ( let j = 0; j < itemSize; j ++ ) {
  6001. array2[ index2 ++ ] = array[ index ++ ];
  6002. }
  6003. }
  6004. return new BufferAttribute( array2, itemSize, normalized );
  6005. }
  6006. //
  6007. if ( this.index === null ) {
  6008. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6009. return this;
  6010. }
  6011. const geometry2 = new BufferGeometry();
  6012. const indices = this.index.array;
  6013. const attributes = this.attributes;
  6014. // attributes
  6015. for ( const name in attributes ) {
  6016. const attribute = attributes[ name ];
  6017. const newAttribute = convertBufferAttribute( attribute, indices );
  6018. geometry2.setAttribute( name, newAttribute );
  6019. }
  6020. // morph attributes
  6021. const morphAttributes = this.morphAttributes;
  6022. for ( const name in morphAttributes ) {
  6023. const morphArray = [];
  6024. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6025. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6026. const attribute = morphAttribute[ i ];
  6027. const newAttribute = convertBufferAttribute( attribute, indices );
  6028. morphArray.push( newAttribute );
  6029. }
  6030. geometry2.morphAttributes[ name ] = morphArray;
  6031. }
  6032. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6033. // groups
  6034. const groups = this.groups;
  6035. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6036. const group = groups[ i ];
  6037. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6038. }
  6039. return geometry2;
  6040. }
  6041. toJSON() {
  6042. const data = {
  6043. metadata: {
  6044. version: 4.5,
  6045. type: 'BufferGeometry',
  6046. generator: 'BufferGeometry.toJSON'
  6047. }
  6048. };
  6049. // standard BufferGeometry serialization
  6050. data.uuid = this.uuid;
  6051. data.type = this.type;
  6052. if ( this.name !== '' ) data.name = this.name;
  6053. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6054. if ( this.parameters !== undefined ) {
  6055. const parameters = this.parameters;
  6056. for ( const key in parameters ) {
  6057. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6058. }
  6059. return data;
  6060. }
  6061. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6062. data.data = { attributes: {} };
  6063. const index = this.index;
  6064. if ( index !== null ) {
  6065. data.data.index = {
  6066. type: index.array.constructor.name,
  6067. array: Array.prototype.slice.call( index.array )
  6068. };
  6069. }
  6070. const attributes = this.attributes;
  6071. for ( const key in attributes ) {
  6072. const attribute = attributes[ key ];
  6073. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6074. }
  6075. const morphAttributes = {};
  6076. let hasMorphAttributes = false;
  6077. for ( const key in this.morphAttributes ) {
  6078. const attributeArray = this.morphAttributes[ key ];
  6079. const array = [];
  6080. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6081. const attribute = attributeArray[ i ];
  6082. array.push( attribute.toJSON( data.data ) );
  6083. }
  6084. if ( array.length > 0 ) {
  6085. morphAttributes[ key ] = array;
  6086. hasMorphAttributes = true;
  6087. }
  6088. }
  6089. if ( hasMorphAttributes ) {
  6090. data.data.morphAttributes = morphAttributes;
  6091. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6092. }
  6093. const groups = this.groups;
  6094. if ( groups.length > 0 ) {
  6095. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6096. }
  6097. const boundingSphere = this.boundingSphere;
  6098. if ( boundingSphere !== null ) {
  6099. data.data.boundingSphere = {
  6100. center: boundingSphere.center.toArray(),
  6101. radius: boundingSphere.radius
  6102. };
  6103. }
  6104. return data;
  6105. }
  6106. clone() {
  6107. /*
  6108. // Handle primitives
  6109. const parameters = this.parameters;
  6110. if ( parameters !== undefined ) {
  6111. const values = [];
  6112. for ( const key in parameters ) {
  6113. values.push( parameters[ key ] );
  6114. }
  6115. const geometry = Object.create( this.constructor.prototype );
  6116. this.constructor.apply( geometry, values );
  6117. return geometry;
  6118. }
  6119. return new this.constructor().copy( this );
  6120. */
  6121. return new BufferGeometry().copy( this );
  6122. }
  6123. copy( source ) {
  6124. // reset
  6125. this.index = null;
  6126. this.attributes = {};
  6127. this.morphAttributes = {};
  6128. this.groups = [];
  6129. this.boundingBox = null;
  6130. this.boundingSphere = null;
  6131. // used for storing cloned, shared data
  6132. const data = {};
  6133. // name
  6134. this.name = source.name;
  6135. // index
  6136. const index = source.index;
  6137. if ( index !== null ) {
  6138. this.setIndex( index.clone( data ) );
  6139. }
  6140. // attributes
  6141. const attributes = source.attributes;
  6142. for ( const name in attributes ) {
  6143. const attribute = attributes[ name ];
  6144. this.setAttribute( name, attribute.clone( data ) );
  6145. }
  6146. // morph attributes
  6147. const morphAttributes = source.morphAttributes;
  6148. for ( const name in morphAttributes ) {
  6149. const array = [];
  6150. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6151. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6152. array.push( morphAttribute[ i ].clone( data ) );
  6153. }
  6154. this.morphAttributes[ name ] = array;
  6155. }
  6156. this.morphTargetsRelative = source.morphTargetsRelative;
  6157. // groups
  6158. const groups = source.groups;
  6159. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6160. const group = groups[ i ];
  6161. this.addGroup( group.start, group.count, group.materialIndex );
  6162. }
  6163. // bounding box
  6164. const boundingBox = source.boundingBox;
  6165. if ( boundingBox !== null ) {
  6166. this.boundingBox = boundingBox.clone();
  6167. }
  6168. // bounding sphere
  6169. const boundingSphere = source.boundingSphere;
  6170. if ( boundingSphere !== null ) {
  6171. this.boundingSphere = boundingSphere.clone();
  6172. }
  6173. // draw range
  6174. this.drawRange.start = source.drawRange.start;
  6175. this.drawRange.count = source.drawRange.count;
  6176. // user data
  6177. this.userData = source.userData;
  6178. return this;
  6179. }
  6180. dispose() {
  6181. this.dispatchEvent( { type: 'dispose' } );
  6182. }
  6183. }
  6184. BufferGeometry.prototype.isBufferGeometry = true;
  6185. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  6186. const _ray$2 = /*@__PURE__*/ new Ray();
  6187. const _sphere$3 = /*@__PURE__*/ new Sphere();
  6188. const _vA$1 = /*@__PURE__*/ new Vector3();
  6189. const _vB$1 = /*@__PURE__*/ new Vector3();
  6190. const _vC$1 = /*@__PURE__*/ new Vector3();
  6191. const _tempA = /*@__PURE__*/ new Vector3();
  6192. const _tempB = /*@__PURE__*/ new Vector3();
  6193. const _tempC = /*@__PURE__*/ new Vector3();
  6194. const _morphA = /*@__PURE__*/ new Vector3();
  6195. const _morphB = /*@__PURE__*/ new Vector3();
  6196. const _morphC = /*@__PURE__*/ new Vector3();
  6197. const _uvA$1 = /*@__PURE__*/ new Vector2();
  6198. const _uvB$1 = /*@__PURE__*/ new Vector2();
  6199. const _uvC$1 = /*@__PURE__*/ new Vector2();
  6200. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6201. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6202. class Mesh extends Object3D {
  6203. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6204. super();
  6205. this.type = 'Mesh';
  6206. this.geometry = geometry;
  6207. this.material = material;
  6208. this.updateMorphTargets();
  6209. }
  6210. copy( source ) {
  6211. super.copy( source );
  6212. if ( source.morphTargetInfluences !== undefined ) {
  6213. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6214. }
  6215. if ( source.morphTargetDictionary !== undefined ) {
  6216. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6217. }
  6218. this.material = source.material;
  6219. this.geometry = source.geometry;
  6220. return this;
  6221. }
  6222. updateMorphTargets() {
  6223. const geometry = this.geometry;
  6224. if ( geometry.isBufferGeometry ) {
  6225. const morphAttributes = geometry.morphAttributes;
  6226. const keys = Object.keys( morphAttributes );
  6227. if ( keys.length > 0 ) {
  6228. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6229. if ( morphAttribute !== undefined ) {
  6230. this.morphTargetInfluences = [];
  6231. this.morphTargetDictionary = {};
  6232. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6233. const name = morphAttribute[ m ].name || String( m );
  6234. this.morphTargetInfluences.push( 0 );
  6235. this.morphTargetDictionary[ name ] = m;
  6236. }
  6237. }
  6238. }
  6239. } else {
  6240. const morphTargets = geometry.morphTargets;
  6241. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  6242. console.error( 'THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  6243. }
  6244. }
  6245. }
  6246. raycast( raycaster, intersects ) {
  6247. const geometry = this.geometry;
  6248. const material = this.material;
  6249. const matrixWorld = this.matrixWorld;
  6250. if ( material === undefined ) return;
  6251. // Checking boundingSphere distance to ray
  6252. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6253. _sphere$3.copy( geometry.boundingSphere );
  6254. _sphere$3.applyMatrix4( matrixWorld );
  6255. if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return;
  6256. //
  6257. _inverseMatrix$2.copy( matrixWorld ).invert();
  6258. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  6259. // Check boundingBox before continuing
  6260. if ( geometry.boundingBox !== null ) {
  6261. if ( _ray$2.intersectsBox( geometry.boundingBox ) === false ) return;
  6262. }
  6263. let intersection;
  6264. if ( geometry.isBufferGeometry ) {
  6265. const index = geometry.index;
  6266. const position = geometry.attributes.position;
  6267. const morphPosition = geometry.morphAttributes.position;
  6268. const morphTargetsRelative = geometry.morphTargetsRelative;
  6269. const uv = geometry.attributes.uv;
  6270. const uv2 = geometry.attributes.uv2;
  6271. const groups = geometry.groups;
  6272. const drawRange = geometry.drawRange;
  6273. if ( index !== null ) {
  6274. // indexed buffer geometry
  6275. if ( Array.isArray( material ) ) {
  6276. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6277. const group = groups[ i ];
  6278. const groupMaterial = material[ group.materialIndex ];
  6279. const start = Math.max( group.start, drawRange.start );
  6280. const end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  6281. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6282. const a = index.getX( j );
  6283. const b = index.getX( j + 1 );
  6284. const c = index.getX( j + 2 );
  6285. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6286. if ( intersection ) {
  6287. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  6288. intersection.face.materialIndex = group.materialIndex;
  6289. intersects.push( intersection );
  6290. }
  6291. }
  6292. }
  6293. } else {
  6294. const start = Math.max( 0, drawRange.start );
  6295. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  6296. for ( let i = start, il = end; i < il; i += 3 ) {
  6297. const a = index.getX( i );
  6298. const b = index.getX( i + 1 );
  6299. const c = index.getX( i + 2 );
  6300. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6301. if ( intersection ) {
  6302. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  6303. intersects.push( intersection );
  6304. }
  6305. }
  6306. }
  6307. } else if ( position !== undefined ) {
  6308. // non-indexed buffer geometry
  6309. if ( Array.isArray( material ) ) {
  6310. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6311. const group = groups[ i ];
  6312. const groupMaterial = material[ group.materialIndex ];
  6313. const start = Math.max( group.start, drawRange.start );
  6314. const end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  6315. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6316. const a = j;
  6317. const b = j + 1;
  6318. const c = j + 2;
  6319. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6320. if ( intersection ) {
  6321. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  6322. intersection.face.materialIndex = group.materialIndex;
  6323. intersects.push( intersection );
  6324. }
  6325. }
  6326. }
  6327. } else {
  6328. const start = Math.max( 0, drawRange.start );
  6329. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  6330. for ( let i = start, il = end; i < il; i += 3 ) {
  6331. const a = i;
  6332. const b = i + 1;
  6333. const c = i + 2;
  6334. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6335. if ( intersection ) {
  6336. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  6337. intersects.push( intersection );
  6338. }
  6339. }
  6340. }
  6341. }
  6342. } else if ( geometry.isGeometry ) {
  6343. console.error( 'THREE.Mesh.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  6344. }
  6345. }
  6346. }
  6347. Mesh.prototype.isMesh = true;
  6348. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  6349. let intersect;
  6350. if ( material.side === BackSide ) {
  6351. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  6352. } else {
  6353. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  6354. }
  6355. if ( intersect === null ) return null;
  6356. _intersectionPointWorld.copy( point );
  6357. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  6358. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  6359. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  6360. return {
  6361. distance: distance,
  6362. point: _intersectionPointWorld.clone(),
  6363. object: object
  6364. };
  6365. }
  6366. function checkBufferGeometryIntersection( object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ) {
  6367. _vA$1.fromBufferAttribute( position, a );
  6368. _vB$1.fromBufferAttribute( position, b );
  6369. _vC$1.fromBufferAttribute( position, c );
  6370. const morphInfluences = object.morphTargetInfluences;
  6371. if ( material.morphTargets && morphPosition && morphInfluences ) {
  6372. _morphA.set( 0, 0, 0 );
  6373. _morphB.set( 0, 0, 0 );
  6374. _morphC.set( 0, 0, 0 );
  6375. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6376. const influence = morphInfluences[ i ];
  6377. const morphAttribute = morphPosition[ i ];
  6378. if ( influence === 0 ) continue;
  6379. _tempA.fromBufferAttribute( morphAttribute, a );
  6380. _tempB.fromBufferAttribute( morphAttribute, b );
  6381. _tempC.fromBufferAttribute( morphAttribute, c );
  6382. if ( morphTargetsRelative ) {
  6383. _morphA.addScaledVector( _tempA, influence );
  6384. _morphB.addScaledVector( _tempB, influence );
  6385. _morphC.addScaledVector( _tempC, influence );
  6386. } else {
  6387. _morphA.addScaledVector( _tempA.sub( _vA$1 ), influence );
  6388. _morphB.addScaledVector( _tempB.sub( _vB$1 ), influence );
  6389. _morphC.addScaledVector( _tempC.sub( _vC$1 ), influence );
  6390. }
  6391. }
  6392. _vA$1.add( _morphA );
  6393. _vB$1.add( _morphB );
  6394. _vC$1.add( _morphC );
  6395. }
  6396. if ( object.isSkinnedMesh ) {
  6397. object.boneTransform( a, _vA$1 );
  6398. object.boneTransform( b, _vB$1 );
  6399. object.boneTransform( c, _vC$1 );
  6400. }
  6401. const intersection = checkIntersection( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  6402. if ( intersection ) {
  6403. if ( uv ) {
  6404. _uvA$1.fromBufferAttribute( uv, a );
  6405. _uvB$1.fromBufferAttribute( uv, b );
  6406. _uvC$1.fromBufferAttribute( uv, c );
  6407. intersection.uv = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6408. }
  6409. if ( uv2 ) {
  6410. _uvA$1.fromBufferAttribute( uv2, a );
  6411. _uvB$1.fromBufferAttribute( uv2, b );
  6412. _uvC$1.fromBufferAttribute( uv2, c );
  6413. intersection.uv2 = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6414. }
  6415. const face = {
  6416. a: a,
  6417. b: b,
  6418. c: c,
  6419. normal: new Vector3(),
  6420. materialIndex: 0
  6421. };
  6422. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  6423. intersection.face = face;
  6424. }
  6425. return intersection;
  6426. }
  6427. class BoxGeometry extends BufferGeometry {
  6428. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  6429. super();
  6430. this.type = 'BoxGeometry';
  6431. this.parameters = {
  6432. width: width,
  6433. height: height,
  6434. depth: depth,
  6435. widthSegments: widthSegments,
  6436. heightSegments: heightSegments,
  6437. depthSegments: depthSegments
  6438. };
  6439. const scope = this;
  6440. // segments
  6441. widthSegments = Math.floor( widthSegments );
  6442. heightSegments = Math.floor( heightSegments );
  6443. depthSegments = Math.floor( depthSegments );
  6444. // buffers
  6445. const indices = [];
  6446. const vertices = [];
  6447. const normals = [];
  6448. const uvs = [];
  6449. // helper variables
  6450. let numberOfVertices = 0;
  6451. let groupStart = 0;
  6452. // build each side of the box geometry
  6453. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  6454. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  6455. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  6456. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  6457. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  6458. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  6459. // build geometry
  6460. this.setIndex( indices );
  6461. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  6462. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  6463. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  6464. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  6465. const segmentWidth = width / gridX;
  6466. const segmentHeight = height / gridY;
  6467. const widthHalf = width / 2;
  6468. const heightHalf = height / 2;
  6469. const depthHalf = depth / 2;
  6470. const gridX1 = gridX + 1;
  6471. const gridY1 = gridY + 1;
  6472. let vertexCounter = 0;
  6473. let groupCount = 0;
  6474. const vector = new Vector3();
  6475. // generate vertices, normals and uvs
  6476. for ( let iy = 0; iy < gridY1; iy ++ ) {
  6477. const y = iy * segmentHeight - heightHalf;
  6478. for ( let ix = 0; ix < gridX1; ix ++ ) {
  6479. const x = ix * segmentWidth - widthHalf;
  6480. // set values to correct vector component
  6481. vector[ u ] = x * udir;
  6482. vector[ v ] = y * vdir;
  6483. vector[ w ] = depthHalf;
  6484. // now apply vector to vertex buffer
  6485. vertices.push( vector.x, vector.y, vector.z );
  6486. // set values to correct vector component
  6487. vector[ u ] = 0;
  6488. vector[ v ] = 0;
  6489. vector[ w ] = depth > 0 ? 1 : - 1;
  6490. // now apply vector to normal buffer
  6491. normals.push( vector.x, vector.y, vector.z );
  6492. // uvs
  6493. uvs.push( ix / gridX );
  6494. uvs.push( 1 - ( iy / gridY ) );
  6495. // counters
  6496. vertexCounter += 1;
  6497. }
  6498. }
  6499. // indices
  6500. // 1. you need three indices to draw a single face
  6501. // 2. a single segment consists of two faces
  6502. // 3. so we need to generate six (2*3) indices per segment
  6503. for ( let iy = 0; iy < gridY; iy ++ ) {
  6504. for ( let ix = 0; ix < gridX; ix ++ ) {
  6505. const a = numberOfVertices + ix + gridX1 * iy;
  6506. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  6507. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  6508. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  6509. // faces
  6510. indices.push( a, b, d );
  6511. indices.push( b, c, d );
  6512. // increase counter
  6513. groupCount += 6;
  6514. }
  6515. }
  6516. // add a group to the geometry. this will ensure multi material support
  6517. scope.addGroup( groupStart, groupCount, materialIndex );
  6518. // calculate new start value for groups
  6519. groupStart += groupCount;
  6520. // update total number of vertices
  6521. numberOfVertices += vertexCounter;
  6522. }
  6523. }
  6524. static fromJSON( data ) {
  6525. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  6526. }
  6527. }
  6528. /**
  6529. * Uniform Utilities
  6530. */
  6531. function cloneUniforms( src ) {
  6532. const dst = {};
  6533. for ( const u in src ) {
  6534. dst[ u ] = {};
  6535. for ( const p in src[ u ] ) {
  6536. const property = src[ u ][ p ];
  6537. if ( property && ( property.isColor ||
  6538. property.isMatrix3 || property.isMatrix4 ||
  6539. property.isVector2 || property.isVector3 || property.isVector4 ||
  6540. property.isTexture || property.isQuaternion ) ) {
  6541. dst[ u ][ p ] = property.clone();
  6542. } else if ( Array.isArray( property ) ) {
  6543. dst[ u ][ p ] = property.slice();
  6544. } else {
  6545. dst[ u ][ p ] = property;
  6546. }
  6547. }
  6548. }
  6549. return dst;
  6550. }
  6551. function mergeUniforms( uniforms ) {
  6552. const merged = {};
  6553. for ( let u = 0; u < uniforms.length; u ++ ) {
  6554. const tmp = cloneUniforms( uniforms[ u ] );
  6555. for ( const p in tmp ) {
  6556. merged[ p ] = tmp[ p ];
  6557. }
  6558. }
  6559. return merged;
  6560. }
  6561. // Legacy
  6562. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  6563. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  6564. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  6565. /**
  6566. * parameters = {
  6567. * defines: { "label" : "value" },
  6568. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  6569. *
  6570. * fragmentShader: <string>,
  6571. * vertexShader: <string>,
  6572. *
  6573. * wireframe: <boolean>,
  6574. * wireframeLinewidth: <float>,
  6575. *
  6576. * lights: <bool>,
  6577. *
  6578. * morphTargets: <bool>,
  6579. * morphNormals: <bool>
  6580. * }
  6581. */
  6582. class ShaderMaterial extends Material {
  6583. constructor( parameters ) {
  6584. super();
  6585. this.type = 'ShaderMaterial';
  6586. this.defines = {};
  6587. this.uniforms = {};
  6588. this.vertexShader = default_vertex;
  6589. this.fragmentShader = default_fragment;
  6590. this.linewidth = 1;
  6591. this.wireframe = false;
  6592. this.wireframeLinewidth = 1;
  6593. this.fog = false; // set to use scene fog
  6594. this.lights = false; // set to use scene lights
  6595. this.clipping = false; // set to use user-defined clipping planes
  6596. this.morphTargets = false; // set to use morph targets
  6597. this.morphNormals = false; // set to use morph normals
  6598. this.extensions = {
  6599. derivatives: false, // set to use derivatives
  6600. fragDepth: false, // set to use fragment depth values
  6601. drawBuffers: false, // set to use draw buffers
  6602. shaderTextureLOD: false // set to use shader texture LOD
  6603. };
  6604. // When rendered geometry doesn't include these attributes but the material does,
  6605. // use these default values in WebGL. This avoids errors when buffer data is missing.
  6606. this.defaultAttributeValues = {
  6607. 'color': [ 1, 1, 1 ],
  6608. 'uv': [ 0, 0 ],
  6609. 'uv2': [ 0, 0 ]
  6610. };
  6611. this.index0AttributeName = undefined;
  6612. this.uniformsNeedUpdate = false;
  6613. this.glslVersion = null;
  6614. if ( parameters !== undefined ) {
  6615. if ( parameters.attributes !== undefined ) {
  6616. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  6617. }
  6618. this.setValues( parameters );
  6619. }
  6620. }
  6621. copy( source ) {
  6622. super.copy( source );
  6623. this.fragmentShader = source.fragmentShader;
  6624. this.vertexShader = source.vertexShader;
  6625. this.uniforms = cloneUniforms( source.uniforms );
  6626. this.defines = Object.assign( {}, source.defines );
  6627. this.wireframe = source.wireframe;
  6628. this.wireframeLinewidth = source.wireframeLinewidth;
  6629. this.lights = source.lights;
  6630. this.clipping = source.clipping;
  6631. this.morphTargets = source.morphTargets;
  6632. this.morphNormals = source.morphNormals;
  6633. this.extensions = Object.assign( {}, source.extensions );
  6634. this.glslVersion = source.glslVersion;
  6635. return this;
  6636. }
  6637. toJSON( meta ) {
  6638. const data = super.toJSON( meta );
  6639. data.glslVersion = this.glslVersion;
  6640. data.uniforms = {};
  6641. for ( const name in this.uniforms ) {
  6642. const uniform = this.uniforms[ name ];
  6643. const value = uniform.value;
  6644. if ( value && value.isTexture ) {
  6645. data.uniforms[ name ] = {
  6646. type: 't',
  6647. value: value.toJSON( meta ).uuid
  6648. };
  6649. } else if ( value && value.isColor ) {
  6650. data.uniforms[ name ] = {
  6651. type: 'c',
  6652. value: value.getHex()
  6653. };
  6654. } else if ( value && value.isVector2 ) {
  6655. data.uniforms[ name ] = {
  6656. type: 'v2',
  6657. value: value.toArray()
  6658. };
  6659. } else if ( value && value.isVector3 ) {
  6660. data.uniforms[ name ] = {
  6661. type: 'v3',
  6662. value: value.toArray()
  6663. };
  6664. } else if ( value && value.isVector4 ) {
  6665. data.uniforms[ name ] = {
  6666. type: 'v4',
  6667. value: value.toArray()
  6668. };
  6669. } else if ( value && value.isMatrix3 ) {
  6670. data.uniforms[ name ] = {
  6671. type: 'm3',
  6672. value: value.toArray()
  6673. };
  6674. } else if ( value && value.isMatrix4 ) {
  6675. data.uniforms[ name ] = {
  6676. type: 'm4',
  6677. value: value.toArray()
  6678. };
  6679. } else {
  6680. data.uniforms[ name ] = {
  6681. value: value
  6682. };
  6683. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  6684. }
  6685. }
  6686. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  6687. data.vertexShader = this.vertexShader;
  6688. data.fragmentShader = this.fragmentShader;
  6689. const extensions = {};
  6690. for ( const key in this.extensions ) {
  6691. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  6692. }
  6693. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  6694. return data;
  6695. }
  6696. }
  6697. ShaderMaterial.prototype.isShaderMaterial = true;
  6698. class Camera extends Object3D {
  6699. constructor() {
  6700. super();
  6701. this.type = 'Camera';
  6702. this.matrixWorldInverse = new Matrix4();
  6703. this.projectionMatrix = new Matrix4();
  6704. this.projectionMatrixInverse = new Matrix4();
  6705. }
  6706. copy( source, recursive ) {
  6707. super.copy( source, recursive );
  6708. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  6709. this.projectionMatrix.copy( source.projectionMatrix );
  6710. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  6711. return this;
  6712. }
  6713. getWorldDirection( target ) {
  6714. this.updateWorldMatrix( true, false );
  6715. const e = this.matrixWorld.elements;
  6716. return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize();
  6717. }
  6718. updateMatrixWorld( force ) {
  6719. super.updateMatrixWorld( force );
  6720. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  6721. }
  6722. updateWorldMatrix( updateParents, updateChildren ) {
  6723. super.updateWorldMatrix( updateParents, updateChildren );
  6724. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  6725. }
  6726. clone() {
  6727. return new this.constructor().copy( this );
  6728. }
  6729. }
  6730. Camera.prototype.isCamera = true;
  6731. class PerspectiveCamera extends Camera {
  6732. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  6733. super();
  6734. this.type = 'PerspectiveCamera';
  6735. this.fov = fov;
  6736. this.zoom = 1;
  6737. this.near = near;
  6738. this.far = far;
  6739. this.focus = 10;
  6740. this.aspect = aspect;
  6741. this.view = null;
  6742. this.filmGauge = 35; // width of the film (default in millimeters)
  6743. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  6744. this.updateProjectionMatrix();
  6745. }
  6746. copy( source, recursive ) {
  6747. super.copy( source, recursive );
  6748. this.fov = source.fov;
  6749. this.zoom = source.zoom;
  6750. this.near = source.near;
  6751. this.far = source.far;
  6752. this.focus = source.focus;
  6753. this.aspect = source.aspect;
  6754. this.view = source.view === null ? null : Object.assign( {}, source.view );
  6755. this.filmGauge = source.filmGauge;
  6756. this.filmOffset = source.filmOffset;
  6757. return this;
  6758. }
  6759. /**
  6760. * Sets the FOV by focal length in respect to the current .filmGauge.
  6761. *
  6762. * The default film gauge is 35, so that the focal length can be specified for
  6763. * a 35mm (full frame) camera.
  6764. *
  6765. * Values for focal length and film gauge must have the same unit.
  6766. */
  6767. setFocalLength( focalLength ) {
  6768. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  6769. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  6770. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  6771. this.updateProjectionMatrix();
  6772. }
  6773. /**
  6774. * Calculates the focal length from the current .fov and .filmGauge.
  6775. */
  6776. getFocalLength() {
  6777. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  6778. return 0.5 * this.getFilmHeight() / vExtentSlope;
  6779. }
  6780. getEffectiveFOV() {
  6781. return RAD2DEG * 2 * Math.atan(
  6782. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  6783. }
  6784. getFilmWidth() {
  6785. // film not completely covered in portrait format (aspect < 1)
  6786. return this.filmGauge * Math.min( this.aspect, 1 );
  6787. }
  6788. getFilmHeight() {
  6789. // film not completely covered in landscape format (aspect > 1)
  6790. return this.filmGauge / Math.max( this.aspect, 1 );
  6791. }
  6792. /**
  6793. * Sets an offset in a larger frustum. This is useful for multi-window or
  6794. * multi-monitor/multi-machine setups.
  6795. *
  6796. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  6797. * the monitors are in grid like this
  6798. *
  6799. * +---+---+---+
  6800. * | A | B | C |
  6801. * +---+---+---+
  6802. * | D | E | F |
  6803. * +---+---+---+
  6804. *
  6805. * then for each monitor you would call it like this
  6806. *
  6807. * const w = 1920;
  6808. * const h = 1080;
  6809. * const fullWidth = w * 3;
  6810. * const fullHeight = h * 2;
  6811. *
  6812. * --A--
  6813. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  6814. * --B--
  6815. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  6816. * --C--
  6817. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  6818. * --D--
  6819. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  6820. * --E--
  6821. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  6822. * --F--
  6823. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  6824. *
  6825. * Note there is no reason monitors have to be the same size or in a grid.
  6826. */
  6827. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  6828. this.aspect = fullWidth / fullHeight;
  6829. if ( this.view === null ) {
  6830. this.view = {
  6831. enabled: true,
  6832. fullWidth: 1,
  6833. fullHeight: 1,
  6834. offsetX: 0,
  6835. offsetY: 0,
  6836. width: 1,
  6837. height: 1
  6838. };
  6839. }
  6840. this.view.enabled = true;
  6841. this.view.fullWidth = fullWidth;
  6842. this.view.fullHeight = fullHeight;
  6843. this.view.offsetX = x;
  6844. this.view.offsetY = y;
  6845. this.view.width = width;
  6846. this.view.height = height;
  6847. this.updateProjectionMatrix();
  6848. }
  6849. clearViewOffset() {
  6850. if ( this.view !== null ) {
  6851. this.view.enabled = false;
  6852. }
  6853. this.updateProjectionMatrix();
  6854. }
  6855. updateProjectionMatrix() {
  6856. const near = this.near;
  6857. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  6858. let height = 2 * top;
  6859. let width = this.aspect * height;
  6860. let left = - 0.5 * width;
  6861. const view = this.view;
  6862. if ( this.view !== null && this.view.enabled ) {
  6863. const fullWidth = view.fullWidth,
  6864. fullHeight = view.fullHeight;
  6865. left += view.offsetX * width / fullWidth;
  6866. top -= view.offsetY * height / fullHeight;
  6867. width *= view.width / fullWidth;
  6868. height *= view.height / fullHeight;
  6869. }
  6870. const skew = this.filmOffset;
  6871. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  6872. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  6873. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  6874. }
  6875. toJSON( meta ) {
  6876. const data = super.toJSON( meta );
  6877. data.object.fov = this.fov;
  6878. data.object.zoom = this.zoom;
  6879. data.object.near = this.near;
  6880. data.object.far = this.far;
  6881. data.object.focus = this.focus;
  6882. data.object.aspect = this.aspect;
  6883. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  6884. data.object.filmGauge = this.filmGauge;
  6885. data.object.filmOffset = this.filmOffset;
  6886. return data;
  6887. }
  6888. }
  6889. PerspectiveCamera.prototype.isPerspectiveCamera = true;
  6890. const fov = 90, aspect = 1;
  6891. class CubeCamera extends Object3D {
  6892. constructor( near, far, renderTarget ) {
  6893. super();
  6894. this.type = 'CubeCamera';
  6895. if ( renderTarget.isWebGLCubeRenderTarget !== true ) {
  6896. console.error( 'THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.' );
  6897. return;
  6898. }
  6899. this.renderTarget = renderTarget;
  6900. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  6901. cameraPX.layers = this.layers;
  6902. cameraPX.up.set( 0, - 1, 0 );
  6903. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  6904. this.add( cameraPX );
  6905. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  6906. cameraNX.layers = this.layers;
  6907. cameraNX.up.set( 0, - 1, 0 );
  6908. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  6909. this.add( cameraNX );
  6910. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  6911. cameraPY.layers = this.layers;
  6912. cameraPY.up.set( 0, 0, 1 );
  6913. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  6914. this.add( cameraPY );
  6915. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  6916. cameraNY.layers = this.layers;
  6917. cameraNY.up.set( 0, 0, - 1 );
  6918. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  6919. this.add( cameraNY );
  6920. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  6921. cameraPZ.layers = this.layers;
  6922. cameraPZ.up.set( 0, - 1, 0 );
  6923. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  6924. this.add( cameraPZ );
  6925. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  6926. cameraNZ.layers = this.layers;
  6927. cameraNZ.up.set( 0, - 1, 0 );
  6928. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  6929. this.add( cameraNZ );
  6930. }
  6931. update( renderer, scene ) {
  6932. if ( this.parent === null ) this.updateMatrixWorld();
  6933. const renderTarget = this.renderTarget;
  6934. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  6935. const currentXrEnabled = renderer.xr.enabled;
  6936. const currentRenderTarget = renderer.getRenderTarget();
  6937. renderer.xr.enabled = false;
  6938. const generateMipmaps = renderTarget.texture.generateMipmaps;
  6939. renderTarget.texture.generateMipmaps = false;
  6940. renderer.setRenderTarget( renderTarget, 0 );
  6941. renderer.render( scene, cameraPX );
  6942. renderer.setRenderTarget( renderTarget, 1 );
  6943. renderer.render( scene, cameraNX );
  6944. renderer.setRenderTarget( renderTarget, 2 );
  6945. renderer.render( scene, cameraPY );
  6946. renderer.setRenderTarget( renderTarget, 3 );
  6947. renderer.render( scene, cameraNY );
  6948. renderer.setRenderTarget( renderTarget, 4 );
  6949. renderer.render( scene, cameraPZ );
  6950. renderTarget.texture.generateMipmaps = generateMipmaps;
  6951. renderer.setRenderTarget( renderTarget, 5 );
  6952. renderer.render( scene, cameraNZ );
  6953. renderer.setRenderTarget( currentRenderTarget );
  6954. renderer.xr.enabled = currentXrEnabled;
  6955. }
  6956. }
  6957. class CubeTexture extends Texture {
  6958. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  6959. images = images !== undefined ? images : [];
  6960. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  6961. format = format !== undefined ? format : RGBFormat;
  6962. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  6963. // Why CubeTexture._needsFlipEnvMap is necessary:
  6964. //
  6965. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  6966. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  6967. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  6968. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  6969. // and the flag _needsFlipEnvMap controls this conversion. The flip is not required (and thus _needsFlipEnvMap is set to false)
  6970. // when using WebGLCubeRenderTarget.texture as a cube texture.
  6971. this._needsFlipEnvMap = true;
  6972. this.flipY = false;
  6973. }
  6974. get images() {
  6975. return this.image;
  6976. }
  6977. set images( value ) {
  6978. this.image = value;
  6979. }
  6980. }
  6981. CubeTexture.prototype.isCubeTexture = true;
  6982. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  6983. constructor( size, options, dummy ) {
  6984. if ( Number.isInteger( options ) ) {
  6985. console.warn( 'THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )' );
  6986. options = dummy;
  6987. }
  6988. super( size, size, options );
  6989. options = options || {};
  6990. this.texture = new CubeTexture( undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  6991. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  6992. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  6993. this.texture._needsFlipEnvMap = false;
  6994. }
  6995. fromEquirectangularTexture( renderer, texture ) {
  6996. this.texture.type = texture.type;
  6997. this.texture.format = RGBAFormat; // see #18859
  6998. this.texture.encoding = texture.encoding;
  6999. this.texture.generateMipmaps = texture.generateMipmaps;
  7000. this.texture.minFilter = texture.minFilter;
  7001. this.texture.magFilter = texture.magFilter;
  7002. const shader = {
  7003. uniforms: {
  7004. tEquirect: { value: null },
  7005. },
  7006. vertexShader: /* glsl */`
  7007. varying vec3 vWorldDirection;
  7008. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7009. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7010. }
  7011. void main() {
  7012. vWorldDirection = transformDirection( position, modelMatrix );
  7013. #include <begin_vertex>
  7014. #include <project_vertex>
  7015. }
  7016. `,
  7017. fragmentShader: /* glsl */`
  7018. uniform sampler2D tEquirect;
  7019. varying vec3 vWorldDirection;
  7020. #include <common>
  7021. void main() {
  7022. vec3 direction = normalize( vWorldDirection );
  7023. vec2 sampleUV = equirectUv( direction );
  7024. gl_FragColor = texture2D( tEquirect, sampleUV );
  7025. }
  7026. `
  7027. };
  7028. const geometry = new BoxGeometry( 5, 5, 5 );
  7029. const material = new ShaderMaterial( {
  7030. name: 'CubemapFromEquirect',
  7031. uniforms: cloneUniforms( shader.uniforms ),
  7032. vertexShader: shader.vertexShader,
  7033. fragmentShader: shader.fragmentShader,
  7034. side: BackSide,
  7035. blending: NoBlending
  7036. } );
  7037. material.uniforms.tEquirect.value = texture;
  7038. const mesh = new Mesh( geometry, material );
  7039. const currentMinFilter = texture.minFilter;
  7040. // Avoid blurred poles
  7041. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7042. const camera = new CubeCamera( 1, 10, this );
  7043. camera.update( renderer, mesh );
  7044. texture.minFilter = currentMinFilter;
  7045. mesh.geometry.dispose();
  7046. mesh.material.dispose();
  7047. return this;
  7048. }
  7049. clear( renderer, color, depth, stencil ) {
  7050. const currentRenderTarget = renderer.getRenderTarget();
  7051. for ( let i = 0; i < 6; i ++ ) {
  7052. renderer.setRenderTarget( this, i );
  7053. renderer.clear( color, depth, stencil );
  7054. }
  7055. renderer.setRenderTarget( currentRenderTarget );
  7056. }
  7057. }
  7058. WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
  7059. const _vector1 = /*@__PURE__*/ new Vector3();
  7060. const _vector2 = /*@__PURE__*/ new Vector3();
  7061. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  7062. class Plane {
  7063. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  7064. // normal is assumed to be normalized
  7065. this.normal = normal;
  7066. this.constant = constant;
  7067. }
  7068. set( normal, constant ) {
  7069. this.normal.copy( normal );
  7070. this.constant = constant;
  7071. return this;
  7072. }
  7073. setComponents( x, y, z, w ) {
  7074. this.normal.set( x, y, z );
  7075. this.constant = w;
  7076. return this;
  7077. }
  7078. setFromNormalAndCoplanarPoint( normal, point ) {
  7079. this.normal.copy( normal );
  7080. this.constant = - point.dot( this.normal );
  7081. return this;
  7082. }
  7083. setFromCoplanarPoints( a, b, c ) {
  7084. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  7085. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7086. this.setFromNormalAndCoplanarPoint( normal, a );
  7087. return this;
  7088. }
  7089. copy( plane ) {
  7090. this.normal.copy( plane.normal );
  7091. this.constant = plane.constant;
  7092. return this;
  7093. }
  7094. normalize() {
  7095. // Note: will lead to a divide by zero if the plane is invalid.
  7096. const inverseNormalLength = 1.0 / this.normal.length();
  7097. this.normal.multiplyScalar( inverseNormalLength );
  7098. this.constant *= inverseNormalLength;
  7099. return this;
  7100. }
  7101. negate() {
  7102. this.constant *= - 1;
  7103. this.normal.negate();
  7104. return this;
  7105. }
  7106. distanceToPoint( point ) {
  7107. return this.normal.dot( point ) + this.constant;
  7108. }
  7109. distanceToSphere( sphere ) {
  7110. return this.distanceToPoint( sphere.center ) - sphere.radius;
  7111. }
  7112. projectPoint( point, target ) {
  7113. return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point );
  7114. }
  7115. intersectLine( line, target ) {
  7116. const direction = line.delta( _vector1 );
  7117. const denominator = this.normal.dot( direction );
  7118. if ( denominator === 0 ) {
  7119. // line is coplanar, return origin
  7120. if ( this.distanceToPoint( line.start ) === 0 ) {
  7121. return target.copy( line.start );
  7122. }
  7123. // Unsure if this is the correct method to handle this case.
  7124. return null;
  7125. }
  7126. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  7127. if ( t < 0 || t > 1 ) {
  7128. return null;
  7129. }
  7130. return target.copy( direction ).multiplyScalar( t ).add( line.start );
  7131. }
  7132. intersectsLine( line ) {
  7133. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7134. const startSign = this.distanceToPoint( line.start );
  7135. const endSign = this.distanceToPoint( line.end );
  7136. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  7137. }
  7138. intersectsBox( box ) {
  7139. return box.intersectsPlane( this );
  7140. }
  7141. intersectsSphere( sphere ) {
  7142. return sphere.intersectsPlane( this );
  7143. }
  7144. coplanarPoint( target ) {
  7145. return target.copy( this.normal ).multiplyScalar( - this.constant );
  7146. }
  7147. applyMatrix4( matrix, optionalNormalMatrix ) {
  7148. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  7149. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  7150. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  7151. this.constant = - referencePoint.dot( normal );
  7152. return this;
  7153. }
  7154. translate( offset ) {
  7155. this.constant -= offset.dot( this.normal );
  7156. return this;
  7157. }
  7158. equals( plane ) {
  7159. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  7160. }
  7161. clone() {
  7162. return new this.constructor().copy( this );
  7163. }
  7164. }
  7165. Plane.prototype.isPlane = true;
  7166. const _sphere$2 = /*@__PURE__*/ new Sphere();
  7167. const _vector$7 = /*@__PURE__*/ new Vector3();
  7168. class Frustum {
  7169. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  7170. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  7171. }
  7172. set( p0, p1, p2, p3, p4, p5 ) {
  7173. const planes = this.planes;
  7174. planes[ 0 ].copy( p0 );
  7175. planes[ 1 ].copy( p1 );
  7176. planes[ 2 ].copy( p2 );
  7177. planes[ 3 ].copy( p3 );
  7178. planes[ 4 ].copy( p4 );
  7179. planes[ 5 ].copy( p5 );
  7180. return this;
  7181. }
  7182. copy( frustum ) {
  7183. const planes = this.planes;
  7184. for ( let i = 0; i < 6; i ++ ) {
  7185. planes[ i ].copy( frustum.planes[ i ] );
  7186. }
  7187. return this;
  7188. }
  7189. setFromProjectionMatrix( m ) {
  7190. const planes = this.planes;
  7191. const me = m.elements;
  7192. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  7193. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  7194. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  7195. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  7196. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  7197. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  7198. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  7199. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  7200. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  7201. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  7202. return this;
  7203. }
  7204. intersectsObject( object ) {
  7205. const geometry = object.geometry;
  7206. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7207. _sphere$2.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  7208. return this.intersectsSphere( _sphere$2 );
  7209. }
  7210. intersectsSprite( sprite ) {
  7211. _sphere$2.center.set( 0, 0, 0 );
  7212. _sphere$2.radius = 0.7071067811865476;
  7213. _sphere$2.applyMatrix4( sprite.matrixWorld );
  7214. return this.intersectsSphere( _sphere$2 );
  7215. }
  7216. intersectsSphere( sphere ) {
  7217. const planes = this.planes;
  7218. const center = sphere.center;
  7219. const negRadius = - sphere.radius;
  7220. for ( let i = 0; i < 6; i ++ ) {
  7221. const distance = planes[ i ].distanceToPoint( center );
  7222. if ( distance < negRadius ) {
  7223. return false;
  7224. }
  7225. }
  7226. return true;
  7227. }
  7228. intersectsBox( box ) {
  7229. const planes = this.planes;
  7230. for ( let i = 0; i < 6; i ++ ) {
  7231. const plane = planes[ i ];
  7232. // corner at max distance
  7233. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7234. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7235. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7236. if ( plane.distanceToPoint( _vector$7 ) < 0 ) {
  7237. return false;
  7238. }
  7239. }
  7240. return true;
  7241. }
  7242. containsPoint( point ) {
  7243. const planes = this.planes;
  7244. for ( let i = 0; i < 6; i ++ ) {
  7245. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  7246. return false;
  7247. }
  7248. }
  7249. return true;
  7250. }
  7251. clone() {
  7252. return new this.constructor().copy( this );
  7253. }
  7254. }
  7255. function WebGLAnimation() {
  7256. let context = null;
  7257. let isAnimating = false;
  7258. let animationLoop = null;
  7259. let requestId = null;
  7260. function onAnimationFrame( time, frame ) {
  7261. animationLoop( time, frame );
  7262. requestId = context.requestAnimationFrame( onAnimationFrame );
  7263. }
  7264. return {
  7265. start: function () {
  7266. if ( isAnimating === true ) return;
  7267. if ( animationLoop === null ) return;
  7268. requestId = context.requestAnimationFrame( onAnimationFrame );
  7269. isAnimating = true;
  7270. },
  7271. stop: function () {
  7272. context.cancelAnimationFrame( requestId );
  7273. isAnimating = false;
  7274. },
  7275. setAnimationLoop: function ( callback ) {
  7276. animationLoop = callback;
  7277. },
  7278. setContext: function ( value ) {
  7279. context = value;
  7280. }
  7281. };
  7282. }
  7283. function WebGLAttributes( gl, capabilities ) {
  7284. const isWebGL2 = capabilities.isWebGL2;
  7285. const buffers = new WeakMap();
  7286. function createBuffer( attribute, bufferType ) {
  7287. const array = attribute.array;
  7288. const usage = attribute.usage;
  7289. const buffer = gl.createBuffer();
  7290. gl.bindBuffer( bufferType, buffer );
  7291. gl.bufferData( bufferType, array, usage );
  7292. attribute.onUploadCallback();
  7293. let type = 5126;
  7294. if ( array instanceof Float32Array ) {
  7295. type = 5126;
  7296. } else if ( array instanceof Float64Array ) {
  7297. console.warn( 'THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.' );
  7298. } else if ( array instanceof Uint16Array ) {
  7299. if ( attribute.isFloat16BufferAttribute ) {
  7300. if ( isWebGL2 ) {
  7301. type = 5131;
  7302. } else {
  7303. console.warn( 'THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.' );
  7304. }
  7305. } else {
  7306. type = 5123;
  7307. }
  7308. } else if ( array instanceof Int16Array ) {
  7309. type = 5122;
  7310. } else if ( array instanceof Uint32Array ) {
  7311. type = 5125;
  7312. } else if ( array instanceof Int32Array ) {
  7313. type = 5124;
  7314. } else if ( array instanceof Int8Array ) {
  7315. type = 5120;
  7316. } else if ( array instanceof Uint8Array ) {
  7317. type = 5121;
  7318. } else if ( array instanceof Uint8ClampedArray ) {
  7319. type = 5121;
  7320. }
  7321. return {
  7322. buffer: buffer,
  7323. type: type,
  7324. bytesPerElement: array.BYTES_PER_ELEMENT,
  7325. version: attribute.version
  7326. };
  7327. }
  7328. function updateBuffer( buffer, attribute, bufferType ) {
  7329. const array = attribute.array;
  7330. const updateRange = attribute.updateRange;
  7331. gl.bindBuffer( bufferType, buffer );
  7332. if ( updateRange.count === - 1 ) {
  7333. // Not using update ranges
  7334. gl.bufferSubData( bufferType, 0, array );
  7335. } else {
  7336. if ( isWebGL2 ) {
  7337. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7338. array, updateRange.offset, updateRange.count );
  7339. } else {
  7340. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7341. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  7342. }
  7343. updateRange.count = - 1; // reset range
  7344. }
  7345. }
  7346. //
  7347. function get( attribute ) {
  7348. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7349. return buffers.get( attribute );
  7350. }
  7351. function remove( attribute ) {
  7352. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7353. const data = buffers.get( attribute );
  7354. if ( data ) {
  7355. gl.deleteBuffer( data.buffer );
  7356. buffers.delete( attribute );
  7357. }
  7358. }
  7359. function update( attribute, bufferType ) {
  7360. if ( attribute.isGLBufferAttribute ) {
  7361. const cached = buffers.get( attribute );
  7362. if ( ! cached || cached.version < attribute.version ) {
  7363. buffers.set( attribute, {
  7364. buffer: attribute.buffer,
  7365. type: attribute.type,
  7366. bytesPerElement: attribute.elementSize,
  7367. version: attribute.version
  7368. } );
  7369. }
  7370. return;
  7371. }
  7372. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7373. const data = buffers.get( attribute );
  7374. if ( data === undefined ) {
  7375. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  7376. } else if ( data.version < attribute.version ) {
  7377. updateBuffer( data.buffer, attribute, bufferType );
  7378. data.version = attribute.version;
  7379. }
  7380. }
  7381. return {
  7382. get: get,
  7383. remove: remove,
  7384. update: update
  7385. };
  7386. }
  7387. class PlaneGeometry extends BufferGeometry {
  7388. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  7389. super();
  7390. this.type = 'PlaneGeometry';
  7391. this.parameters = {
  7392. width: width,
  7393. height: height,
  7394. widthSegments: widthSegments,
  7395. heightSegments: heightSegments
  7396. };
  7397. const width_half = width / 2;
  7398. const height_half = height / 2;
  7399. const gridX = Math.floor( widthSegments );
  7400. const gridY = Math.floor( heightSegments );
  7401. const gridX1 = gridX + 1;
  7402. const gridY1 = gridY + 1;
  7403. const segment_width = width / gridX;
  7404. const segment_height = height / gridY;
  7405. //
  7406. const indices = [];
  7407. const vertices = [];
  7408. const normals = [];
  7409. const uvs = [];
  7410. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7411. const y = iy * segment_height - height_half;
  7412. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7413. const x = ix * segment_width - width_half;
  7414. vertices.push( x, - y, 0 );
  7415. normals.push( 0, 0, 1 );
  7416. uvs.push( ix / gridX );
  7417. uvs.push( 1 - ( iy / gridY ) );
  7418. }
  7419. }
  7420. for ( let iy = 0; iy < gridY; iy ++ ) {
  7421. for ( let ix = 0; ix < gridX; ix ++ ) {
  7422. const a = ix + gridX1 * iy;
  7423. const b = ix + gridX1 * ( iy + 1 );
  7424. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  7425. const d = ( ix + 1 ) + gridX1 * iy;
  7426. indices.push( a, b, d );
  7427. indices.push( b, c, d );
  7428. }
  7429. }
  7430. this.setIndex( indices );
  7431. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7432. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7433. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7434. }
  7435. static fromJSON( data ) {
  7436. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  7437. }
  7438. }
  7439. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  7440. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7441. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";
  7442. 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";
  7443. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7444. var begin_vertex = "vec3 transformed = vec3( position );";
  7445. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  7446. var bsdfs = "vec2 integrateSpecularBRDF( const in float dotNV, const in float roughness ) {\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\treturn vec2( -1.04, 1.04 ) * a004 + r.zw;\n}\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n#else\n\tif( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t}\n\treturn 1.0;\n#endif\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotVH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nvec3 F_Schlick_RoughnessDependent( const in vec3 F0, const in float dotNV, const in float roughness ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotNV - 6.98316 ) * dotNV );\n\tvec3 Fr = max( vec3( 1.0 - roughness ), F0 ) - F0;\n\treturn Fr * fresnel + F0;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + viewDir );\n\tfloat dotNL = saturate( dot( normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nvec3 BRDF_Specular_GGX_Environment( const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\treturn specularColor * brdf.x + brdf.y;\n}\nvoid BRDF_Specular_Multiscattering_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tvec3 F = F_Schlick_RoughnessDependent( specularColor, dotNV, roughness );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\tvec3 FssEss = F * brdf.x + brdf.y;\n\tfloat Ess = brdf.x + brdf.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie(float roughness, float NoH) {\n\tfloat invAlpha = 1.0 / roughness;\n\tfloat cos2h = NoH * NoH;\n\tfloat sin2h = max(1.0 - cos2h, 0.0078125);\treturn (2.0 + invAlpha) * pow(sin2h, invAlpha * 0.5) / (2.0 * PI);\n}\nfloat V_Neubelt(float NoV, float NoL) {\n\treturn saturate(1.0 / (4.0 * (NoL + NoV - NoL * NoV)));\n}\nvec3 BRDF_Specular_Sheen( const in float roughness, const in vec3 L, const in GeometricContext geometry, vec3 specularColor ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 H = normalize( V + L );\n\tfloat dotNH = saturate( dot( N, H ) );\n\treturn specularColor * D_Charlie( roughness, dotNH ) * V_Neubelt( dot(N, V), dot(N, L) );\n}\n#endif";
  7447. 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";
  7448. 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";
  7449. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  7450. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  7451. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  7452. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7453. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7454. 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";
  7455. 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";
  7456. 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}";
  7457. 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";
  7458. 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";
  7459. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  7460. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  7461. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  7462. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  7463. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  7464. 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}";
  7465. 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";
  7466. 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";
  7467. 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";
  7468. 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";
  7469. 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";
  7470. var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = - mvPosition.z;\n#endif";
  7471. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";
  7472. 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";
  7473. 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";
  7474. 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}";
  7475. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\treflectedLight.indirectDiffuse += PI * lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n#endif";
  7476. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7477. 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";
  7478. 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";
  7479. 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";
  7480. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  7481. 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)";
  7482. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  7483. 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)";
  7484. 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";
  7485. 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}";
  7486. 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";
  7487. 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";
  7488. 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";
  7489. 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";
  7490. 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";
  7491. 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";
  7492. 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";
  7493. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  7494. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  7495. 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";
  7496. 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";
  7497. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  7498. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  7499. 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";
  7500. 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";
  7501. 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";
  7502. 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;";
  7503. 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";
  7504. 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";
  7505. var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  7506. 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";
  7507. 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";
  7508. 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}";
  7509. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  7510. 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;";
  7511. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  7512. 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";
  7513. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  7514. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  7515. 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";
  7516. 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";
  7517. 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";
  7518. 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}";
  7519. 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";
  7520. 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";
  7521. 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";
  7522. 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";
  7523. 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";
  7524. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  7525. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  7526. 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; }";
  7527. var transmission_fragment = "#ifdef USE_TRANSMISSION\n\tfloat transmissionFactor = transmission;\n\tfloat thicknessFactor = thickness;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\ttransmissionFactor *= texture2D( transmissionMap, vUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSNMAP\n\t\tthicknessFactor *= texture2D( thicknessMap, vUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition.xyz / vWorldPosition.w;\n\tvec3 v = normalize( cameraPosition - pos );\n\tfloat ior = ( 1.0 + 0.4 * reflectivity ) / ( 1.0 - 0.4 * reflectivity );\n\tvec3 transmission = transmissionFactor * getIBLVolumeRefraction(\n\t\tnormal, v, roughnessFactor, material.diffuseColor, totalSpecular,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, ior, thicknessFactor,\n\t\tattenuationColor, attenuationDistance );\n\ttotalDiffuse = mix( totalDiffuse, transmission, transmissionFactor );\n#endif";
  7528. var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec4 vWorldPosition;\n\tvec3 getVolumeTransmissionRay(vec3 n, vec3 v, float thickness, float ior, mat4 modelMatrix) {\n\t\tvec3 refractionVector = refract(-v, normalize(n), 1.0 / ior);\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length(vec3(modelMatrix[0].xyz));\n\t\tmodelScale.y = length(vec3(modelMatrix[1].xyz));\n\t\tmodelScale.z = length(vec3(modelMatrix[2].xyz));\n\t\treturn normalize(refractionVector) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness(float roughness, float ior) {\n\t\treturn roughness * clamp(ior * 2.0 - 2.0, 0.0, 1.0);\n\t}\n\tvec3 getTransmissionSample(vec2 fragCoord, float roughness, float ior) {\n\t\tfloat framebufferLod = log2(transmissionSamplerSize.x) * applyIorToRoughness(roughness, ior);\n\t\treturn texture2DLodEXT(transmissionSamplerMap, fragCoord.xy, framebufferLod).rgb;\n\t}\n\tvec3 applyVolumeAttenuation(vec3 radiance, float transmissionDistance, vec3 attenuationColor, float attenuationDistance) {\n\t\tif (attenuationDistance == 0.0) {\n\t\t\treturn radiance;\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log(attenuationColor) / attenuationDistance;\n\t\t\tvec3 transmittance = exp(-attenuationCoefficient * transmissionDistance);\t\t\treturn transmittance * radiance;\n\t\t}\n\t}\n\tvec3 getIBLVolumeRefraction(vec3 n, vec3 v, float perceptualRoughness, vec3 baseColor, vec3 specularColor,\n\t\tvec3 position, mat4 modelMatrix, mat4 viewMatrix, mat4 projMatrix, float ior, float thickness,\n\t\tvec3 attenuationColor, float attenuationDistance) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay(n, v, thickness, ior, modelMatrix);\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4(refractedRayExit, 1.0);\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec3 transmittedLight = getTransmissionSample(refractionCoords, perceptualRoughness, ior);\n\t\tvec3 attenuatedColor = applyVolumeAttenuation(transmittedLight, length(transmissionRay), attenuationColor, attenuationDistance);\n\t\treturn (1.0 - specularColor) * attenuatedColor * baseColor;\n\t}\n#endif";
  7529. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  7530. 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";
  7531. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  7532. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  7533. 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";
  7534. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  7535. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION )\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif";
  7536. 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}";
  7537. 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}";
  7538. 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}";
  7539. 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}";
  7540. 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}";
  7541. 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}";
  7542. 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}";
  7543. 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}";
  7544. 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}";
  7545. 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}";
  7546. 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}";
  7547. 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}";
  7548. 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}";
  7549. 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}";
  7550. 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}";
  7551. 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}";
  7552. 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}";
  7553. 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}";
  7554. 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}";
  7555. 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}";
  7556. 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}";
  7557. 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}";
  7558. var meshphysical_frag = "#define STANDARD\n#ifdef PHYSICAL\n\t#define REFLECTIVITY\n\t#define CLEARCOAT\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform vec3 attenuationColor;\n\tuniform float attenuationDistance;\n#endif\n#ifdef REFLECTIVITY\n\tuniform float reflectivity;\n#endif\n#ifdef CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheen;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <bsdfs>\n#include <transmission_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <lights_physical_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include <transmission_fragment>\n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7559. var meshphysical_vert = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#ifdef USE_TRANSMISSION\n\tvarying vec4 vWorldPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition;\n#endif\n}";
  7560. 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}";
  7561. 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}";
  7562. 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}";
  7563. 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}";
  7564. 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}";
  7565. 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}";
  7566. 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}";
  7567. 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}";
  7568. const ShaderChunk = {
  7569. alphamap_fragment: alphamap_fragment,
  7570. alphamap_pars_fragment: alphamap_pars_fragment,
  7571. alphatest_fragment: alphatest_fragment,
  7572. aomap_fragment: aomap_fragment,
  7573. aomap_pars_fragment: aomap_pars_fragment,
  7574. begin_vertex: begin_vertex,
  7575. beginnormal_vertex: beginnormal_vertex,
  7576. bsdfs: bsdfs,
  7577. bumpmap_pars_fragment: bumpmap_pars_fragment,
  7578. clipping_planes_fragment: clipping_planes_fragment,
  7579. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  7580. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  7581. clipping_planes_vertex: clipping_planes_vertex,
  7582. color_fragment: color_fragment,
  7583. color_pars_fragment: color_pars_fragment,
  7584. color_pars_vertex: color_pars_vertex,
  7585. color_vertex: color_vertex,
  7586. common: common,
  7587. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  7588. defaultnormal_vertex: defaultnormal_vertex,
  7589. displacementmap_pars_vertex: displacementmap_pars_vertex,
  7590. displacementmap_vertex: displacementmap_vertex,
  7591. emissivemap_fragment: emissivemap_fragment,
  7592. emissivemap_pars_fragment: emissivemap_pars_fragment,
  7593. encodings_fragment: encodings_fragment,
  7594. encodings_pars_fragment: encodings_pars_fragment,
  7595. envmap_fragment: envmap_fragment,
  7596. envmap_common_pars_fragment: envmap_common_pars_fragment,
  7597. envmap_pars_fragment: envmap_pars_fragment,
  7598. envmap_pars_vertex: envmap_pars_vertex,
  7599. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  7600. envmap_vertex: envmap_vertex,
  7601. fog_vertex: fog_vertex,
  7602. fog_pars_vertex: fog_pars_vertex,
  7603. fog_fragment: fog_fragment,
  7604. fog_pars_fragment: fog_pars_fragment,
  7605. gradientmap_pars_fragment: gradientmap_pars_fragment,
  7606. lightmap_fragment: lightmap_fragment,
  7607. lightmap_pars_fragment: lightmap_pars_fragment,
  7608. lights_lambert_vertex: lights_lambert_vertex,
  7609. lights_pars_begin: lights_pars_begin,
  7610. lights_toon_fragment: lights_toon_fragment,
  7611. lights_toon_pars_fragment: lights_toon_pars_fragment,
  7612. lights_phong_fragment: lights_phong_fragment,
  7613. lights_phong_pars_fragment: lights_phong_pars_fragment,
  7614. lights_physical_fragment: lights_physical_fragment,
  7615. lights_physical_pars_fragment: lights_physical_pars_fragment,
  7616. lights_fragment_begin: lights_fragment_begin,
  7617. lights_fragment_maps: lights_fragment_maps,
  7618. lights_fragment_end: lights_fragment_end,
  7619. logdepthbuf_fragment: logdepthbuf_fragment,
  7620. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  7621. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  7622. logdepthbuf_vertex: logdepthbuf_vertex,
  7623. map_fragment: map_fragment,
  7624. map_pars_fragment: map_pars_fragment,
  7625. map_particle_fragment: map_particle_fragment,
  7626. map_particle_pars_fragment: map_particle_pars_fragment,
  7627. metalnessmap_fragment: metalnessmap_fragment,
  7628. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  7629. morphnormal_vertex: morphnormal_vertex,
  7630. morphtarget_pars_vertex: morphtarget_pars_vertex,
  7631. morphtarget_vertex: morphtarget_vertex,
  7632. normal_fragment_begin: normal_fragment_begin,
  7633. normal_fragment_maps: normal_fragment_maps,
  7634. normalmap_pars_fragment: normalmap_pars_fragment,
  7635. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  7636. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  7637. clearcoat_pars_fragment: clearcoat_pars_fragment,
  7638. packing: packing,
  7639. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  7640. project_vertex: project_vertex,
  7641. dithering_fragment: dithering_fragment,
  7642. dithering_pars_fragment: dithering_pars_fragment,
  7643. roughnessmap_fragment: roughnessmap_fragment,
  7644. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  7645. shadowmap_pars_fragment: shadowmap_pars_fragment,
  7646. shadowmap_pars_vertex: shadowmap_pars_vertex,
  7647. shadowmap_vertex: shadowmap_vertex,
  7648. shadowmask_pars_fragment: shadowmask_pars_fragment,
  7649. skinbase_vertex: skinbase_vertex,
  7650. skinning_pars_vertex: skinning_pars_vertex,
  7651. skinning_vertex: skinning_vertex,
  7652. skinnormal_vertex: skinnormal_vertex,
  7653. specularmap_fragment: specularmap_fragment,
  7654. specularmap_pars_fragment: specularmap_pars_fragment,
  7655. tonemapping_fragment: tonemapping_fragment,
  7656. tonemapping_pars_fragment: tonemapping_pars_fragment,
  7657. transmission_fragment: transmission_fragment,
  7658. transmission_pars_fragment: transmission_pars_fragment,
  7659. uv_pars_fragment: uv_pars_fragment,
  7660. uv_pars_vertex: uv_pars_vertex,
  7661. uv_vertex: uv_vertex,
  7662. uv2_pars_fragment: uv2_pars_fragment,
  7663. uv2_pars_vertex: uv2_pars_vertex,
  7664. uv2_vertex: uv2_vertex,
  7665. worldpos_vertex: worldpos_vertex,
  7666. background_frag: background_frag,
  7667. background_vert: background_vert,
  7668. cube_frag: cube_frag,
  7669. cube_vert: cube_vert,
  7670. depth_frag: depth_frag,
  7671. depth_vert: depth_vert,
  7672. distanceRGBA_frag: distanceRGBA_frag,
  7673. distanceRGBA_vert: distanceRGBA_vert,
  7674. equirect_frag: equirect_frag,
  7675. equirect_vert: equirect_vert,
  7676. linedashed_frag: linedashed_frag,
  7677. linedashed_vert: linedashed_vert,
  7678. meshbasic_frag: meshbasic_frag,
  7679. meshbasic_vert: meshbasic_vert,
  7680. meshlambert_frag: meshlambert_frag,
  7681. meshlambert_vert: meshlambert_vert,
  7682. meshmatcap_frag: meshmatcap_frag,
  7683. meshmatcap_vert: meshmatcap_vert,
  7684. meshtoon_frag: meshtoon_frag,
  7685. meshtoon_vert: meshtoon_vert,
  7686. meshphong_frag: meshphong_frag,
  7687. meshphong_vert: meshphong_vert,
  7688. meshphysical_frag: meshphysical_frag,
  7689. meshphysical_vert: meshphysical_vert,
  7690. normal_frag: normal_frag,
  7691. normal_vert: normal_vert,
  7692. points_frag: points_frag,
  7693. points_vert: points_vert,
  7694. shadow_frag: shadow_frag,
  7695. shadow_vert: shadow_vert,
  7696. sprite_frag: sprite_frag,
  7697. sprite_vert: sprite_vert
  7698. };
  7699. /**
  7700. * Uniforms library for shared webgl shaders
  7701. */
  7702. const UniformsLib = {
  7703. common: {
  7704. diffuse: { value: new Color( 0xffffff ) },
  7705. opacity: { value: 1.0 },
  7706. map: { value: null },
  7707. uvTransform: { value: new Matrix3() },
  7708. uv2Transform: { value: new Matrix3() },
  7709. alphaMap: { value: null },
  7710. },
  7711. specularmap: {
  7712. specularMap: { value: null },
  7713. },
  7714. envmap: {
  7715. envMap: { value: null },
  7716. flipEnvMap: { value: - 1 },
  7717. reflectivity: { value: 1.0 },
  7718. refractionRatio: { value: 0.98 },
  7719. maxMipLevel: { value: 0 }
  7720. },
  7721. aomap: {
  7722. aoMap: { value: null },
  7723. aoMapIntensity: { value: 1 }
  7724. },
  7725. lightmap: {
  7726. lightMap: { value: null },
  7727. lightMapIntensity: { value: 1 }
  7728. },
  7729. emissivemap: {
  7730. emissiveMap: { value: null }
  7731. },
  7732. bumpmap: {
  7733. bumpMap: { value: null },
  7734. bumpScale: { value: 1 }
  7735. },
  7736. normalmap: {
  7737. normalMap: { value: null },
  7738. normalScale: { value: new Vector2( 1, 1 ) }
  7739. },
  7740. displacementmap: {
  7741. displacementMap: { value: null },
  7742. displacementScale: { value: 1 },
  7743. displacementBias: { value: 0 }
  7744. },
  7745. roughnessmap: {
  7746. roughnessMap: { value: null }
  7747. },
  7748. metalnessmap: {
  7749. metalnessMap: { value: null }
  7750. },
  7751. gradientmap: {
  7752. gradientMap: { value: null }
  7753. },
  7754. fog: {
  7755. fogDensity: { value: 0.00025 },
  7756. fogNear: { value: 1 },
  7757. fogFar: { value: 2000 },
  7758. fogColor: { value: new Color( 0xffffff ) }
  7759. },
  7760. lights: {
  7761. ambientLightColor: { value: [] },
  7762. lightProbe: { value: [] },
  7763. directionalLights: { value: [], properties: {
  7764. direction: {},
  7765. color: {}
  7766. } },
  7767. directionalLightShadows: { value: [], properties: {
  7768. shadowBias: {},
  7769. shadowNormalBias: {},
  7770. shadowRadius: {},
  7771. shadowMapSize: {}
  7772. } },
  7773. directionalShadowMap: { value: [] },
  7774. directionalShadowMatrix: { value: [] },
  7775. spotLights: { value: [], properties: {
  7776. color: {},
  7777. position: {},
  7778. direction: {},
  7779. distance: {},
  7780. coneCos: {},
  7781. penumbraCos: {},
  7782. decay: {}
  7783. } },
  7784. spotLightShadows: { value: [], properties: {
  7785. shadowBias: {},
  7786. shadowNormalBias: {},
  7787. shadowRadius: {},
  7788. shadowMapSize: {}
  7789. } },
  7790. spotShadowMap: { value: [] },
  7791. spotShadowMatrix: { value: [] },
  7792. pointLights: { value: [], properties: {
  7793. color: {},
  7794. position: {},
  7795. decay: {},
  7796. distance: {}
  7797. } },
  7798. pointLightShadows: { value: [], properties: {
  7799. shadowBias: {},
  7800. shadowNormalBias: {},
  7801. shadowRadius: {},
  7802. shadowMapSize: {},
  7803. shadowCameraNear: {},
  7804. shadowCameraFar: {}
  7805. } },
  7806. pointShadowMap: { value: [] },
  7807. pointShadowMatrix: { value: [] },
  7808. hemisphereLights: { value: [], properties: {
  7809. direction: {},
  7810. skyColor: {},
  7811. groundColor: {}
  7812. } },
  7813. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  7814. rectAreaLights: { value: [], properties: {
  7815. color: {},
  7816. position: {},
  7817. width: {},
  7818. height: {}
  7819. } },
  7820. ltc_1: { value: null },
  7821. ltc_2: { value: null }
  7822. },
  7823. points: {
  7824. diffuse: { value: new Color( 0xffffff ) },
  7825. opacity: { value: 1.0 },
  7826. size: { value: 1.0 },
  7827. scale: { value: 1.0 },
  7828. map: { value: null },
  7829. alphaMap: { value: null },
  7830. uvTransform: { value: new Matrix3() }
  7831. },
  7832. sprite: {
  7833. diffuse: { value: new Color( 0xffffff ) },
  7834. opacity: { value: 1.0 },
  7835. center: { value: new Vector2( 0.5, 0.5 ) },
  7836. rotation: { value: 0.0 },
  7837. map: { value: null },
  7838. alphaMap: { value: null },
  7839. uvTransform: { value: new Matrix3() }
  7840. }
  7841. };
  7842. const ShaderLib = {
  7843. basic: {
  7844. uniforms: mergeUniforms( [
  7845. UniformsLib.common,
  7846. UniformsLib.specularmap,
  7847. UniformsLib.envmap,
  7848. UniformsLib.aomap,
  7849. UniformsLib.lightmap,
  7850. UniformsLib.fog
  7851. ] ),
  7852. vertexShader: ShaderChunk.meshbasic_vert,
  7853. fragmentShader: ShaderChunk.meshbasic_frag
  7854. },
  7855. lambert: {
  7856. uniforms: mergeUniforms( [
  7857. UniformsLib.common,
  7858. UniformsLib.specularmap,
  7859. UniformsLib.envmap,
  7860. UniformsLib.aomap,
  7861. UniformsLib.lightmap,
  7862. UniformsLib.emissivemap,
  7863. UniformsLib.fog,
  7864. UniformsLib.lights,
  7865. {
  7866. emissive: { value: new Color( 0x000000 ) }
  7867. }
  7868. ] ),
  7869. vertexShader: ShaderChunk.meshlambert_vert,
  7870. fragmentShader: ShaderChunk.meshlambert_frag
  7871. },
  7872. phong: {
  7873. uniforms: mergeUniforms( [
  7874. UniformsLib.common,
  7875. UniformsLib.specularmap,
  7876. UniformsLib.envmap,
  7877. UniformsLib.aomap,
  7878. UniformsLib.lightmap,
  7879. UniformsLib.emissivemap,
  7880. UniformsLib.bumpmap,
  7881. UniformsLib.normalmap,
  7882. UniformsLib.displacementmap,
  7883. UniformsLib.fog,
  7884. UniformsLib.lights,
  7885. {
  7886. emissive: { value: new Color( 0x000000 ) },
  7887. specular: { value: new Color( 0x111111 ) },
  7888. shininess: { value: 30 }
  7889. }
  7890. ] ),
  7891. vertexShader: ShaderChunk.meshphong_vert,
  7892. fragmentShader: ShaderChunk.meshphong_frag
  7893. },
  7894. standard: {
  7895. uniforms: mergeUniforms( [
  7896. UniformsLib.common,
  7897. UniformsLib.envmap,
  7898. UniformsLib.aomap,
  7899. UniformsLib.lightmap,
  7900. UniformsLib.emissivemap,
  7901. UniformsLib.bumpmap,
  7902. UniformsLib.normalmap,
  7903. UniformsLib.displacementmap,
  7904. UniformsLib.roughnessmap,
  7905. UniformsLib.metalnessmap,
  7906. UniformsLib.fog,
  7907. UniformsLib.lights,
  7908. {
  7909. emissive: { value: new Color( 0x000000 ) },
  7910. roughness: { value: 1.0 },
  7911. metalness: { value: 0.0 },
  7912. envMapIntensity: { value: 1 } // temporary
  7913. }
  7914. ] ),
  7915. vertexShader: ShaderChunk.meshphysical_vert,
  7916. fragmentShader: ShaderChunk.meshphysical_frag
  7917. },
  7918. toon: {
  7919. uniforms: mergeUniforms( [
  7920. UniformsLib.common,
  7921. UniformsLib.aomap,
  7922. UniformsLib.lightmap,
  7923. UniformsLib.emissivemap,
  7924. UniformsLib.bumpmap,
  7925. UniformsLib.normalmap,
  7926. UniformsLib.displacementmap,
  7927. UniformsLib.gradientmap,
  7928. UniformsLib.fog,
  7929. UniformsLib.lights,
  7930. {
  7931. emissive: { value: new Color( 0x000000 ) }
  7932. }
  7933. ] ),
  7934. vertexShader: ShaderChunk.meshtoon_vert,
  7935. fragmentShader: ShaderChunk.meshtoon_frag
  7936. },
  7937. matcap: {
  7938. uniforms: mergeUniforms( [
  7939. UniformsLib.common,
  7940. UniformsLib.bumpmap,
  7941. UniformsLib.normalmap,
  7942. UniformsLib.displacementmap,
  7943. UniformsLib.fog,
  7944. {
  7945. matcap: { value: null }
  7946. }
  7947. ] ),
  7948. vertexShader: ShaderChunk.meshmatcap_vert,
  7949. fragmentShader: ShaderChunk.meshmatcap_frag
  7950. },
  7951. points: {
  7952. uniforms: mergeUniforms( [
  7953. UniformsLib.points,
  7954. UniformsLib.fog
  7955. ] ),
  7956. vertexShader: ShaderChunk.points_vert,
  7957. fragmentShader: ShaderChunk.points_frag
  7958. },
  7959. dashed: {
  7960. uniforms: mergeUniforms( [
  7961. UniformsLib.common,
  7962. UniformsLib.fog,
  7963. {
  7964. scale: { value: 1 },
  7965. dashSize: { value: 1 },
  7966. totalSize: { value: 2 }
  7967. }
  7968. ] ),
  7969. vertexShader: ShaderChunk.linedashed_vert,
  7970. fragmentShader: ShaderChunk.linedashed_frag
  7971. },
  7972. depth: {
  7973. uniforms: mergeUniforms( [
  7974. UniformsLib.common,
  7975. UniformsLib.displacementmap
  7976. ] ),
  7977. vertexShader: ShaderChunk.depth_vert,
  7978. fragmentShader: ShaderChunk.depth_frag
  7979. },
  7980. normal: {
  7981. uniforms: mergeUniforms( [
  7982. UniformsLib.common,
  7983. UniformsLib.bumpmap,
  7984. UniformsLib.normalmap,
  7985. UniformsLib.displacementmap,
  7986. {
  7987. opacity: { value: 1.0 }
  7988. }
  7989. ] ),
  7990. vertexShader: ShaderChunk.normal_vert,
  7991. fragmentShader: ShaderChunk.normal_frag
  7992. },
  7993. sprite: {
  7994. uniforms: mergeUniforms( [
  7995. UniformsLib.sprite,
  7996. UniformsLib.fog
  7997. ] ),
  7998. vertexShader: ShaderChunk.sprite_vert,
  7999. fragmentShader: ShaderChunk.sprite_frag
  8000. },
  8001. background: {
  8002. uniforms: {
  8003. uvTransform: { value: new Matrix3() },
  8004. t2D: { value: null },
  8005. },
  8006. vertexShader: ShaderChunk.background_vert,
  8007. fragmentShader: ShaderChunk.background_frag
  8008. },
  8009. /* -------------------------------------------------------------------------
  8010. // Cube map shader
  8011. ------------------------------------------------------------------------- */
  8012. cube: {
  8013. uniforms: mergeUniforms( [
  8014. UniformsLib.envmap,
  8015. {
  8016. opacity: { value: 1.0 }
  8017. }
  8018. ] ),
  8019. vertexShader: ShaderChunk.cube_vert,
  8020. fragmentShader: ShaderChunk.cube_frag
  8021. },
  8022. equirect: {
  8023. uniforms: {
  8024. tEquirect: { value: null },
  8025. },
  8026. vertexShader: ShaderChunk.equirect_vert,
  8027. fragmentShader: ShaderChunk.equirect_frag
  8028. },
  8029. distanceRGBA: {
  8030. uniforms: mergeUniforms( [
  8031. UniformsLib.common,
  8032. UniformsLib.displacementmap,
  8033. {
  8034. referencePosition: { value: new Vector3() },
  8035. nearDistance: { value: 1 },
  8036. farDistance: { value: 1000 }
  8037. }
  8038. ] ),
  8039. vertexShader: ShaderChunk.distanceRGBA_vert,
  8040. fragmentShader: ShaderChunk.distanceRGBA_frag
  8041. },
  8042. shadow: {
  8043. uniforms: mergeUniforms( [
  8044. UniformsLib.lights,
  8045. UniformsLib.fog,
  8046. {
  8047. color: { value: new Color( 0x00000 ) },
  8048. opacity: { value: 1.0 }
  8049. },
  8050. ] ),
  8051. vertexShader: ShaderChunk.shadow_vert,
  8052. fragmentShader: ShaderChunk.shadow_frag
  8053. }
  8054. };
  8055. ShaderLib.physical = {
  8056. uniforms: mergeUniforms( [
  8057. ShaderLib.standard.uniforms,
  8058. {
  8059. clearcoat: { value: 0 },
  8060. clearcoatMap: { value: null },
  8061. clearcoatRoughness: { value: 0 },
  8062. clearcoatRoughnessMap: { value: null },
  8063. clearcoatNormalScale: { value: new Vector2( 1, 1 ) },
  8064. clearcoatNormalMap: { value: null },
  8065. sheen: { value: new Color( 0x000000 ) },
  8066. transmission: { value: 0 },
  8067. transmissionMap: { value: null },
  8068. transmissionSamplerSize: { value: new Vector2() },
  8069. transmissionSamplerMap: { value: null },
  8070. thickness: { value: 0 },
  8071. thicknessMap: { value: null },
  8072. attenuationDistance: { value: 0 },
  8073. attenuationColor: { value: new Color( 0x000000 ) }
  8074. }
  8075. ] ),
  8076. vertexShader: ShaderChunk.meshphysical_vert,
  8077. fragmentShader: ShaderChunk.meshphysical_frag
  8078. };
  8079. function WebGLBackground( renderer, cubemaps, state, objects, premultipliedAlpha ) {
  8080. const clearColor = new Color( 0x000000 );
  8081. let clearAlpha = 0;
  8082. let planeMesh;
  8083. let boxMesh;
  8084. let currentBackground = null;
  8085. let currentBackgroundVersion = 0;
  8086. let currentTonemapping = null;
  8087. function render( renderList, scene ) {
  8088. let forceClear = false;
  8089. let background = scene.isScene === true ? scene.background : null;
  8090. if ( background && background.isTexture ) {
  8091. background = cubemaps.get( background );
  8092. }
  8093. // Ignore background in AR
  8094. // TODO: Reconsider this.
  8095. const xr = renderer.xr;
  8096. const session = xr.getSession && xr.getSession();
  8097. if ( session && session.environmentBlendMode === 'additive' ) {
  8098. background = null;
  8099. }
  8100. if ( background === null ) {
  8101. setClear( clearColor, clearAlpha );
  8102. } else if ( background && background.isColor ) {
  8103. setClear( background, 1 );
  8104. forceClear = true;
  8105. }
  8106. if ( renderer.autoClear || forceClear ) {
  8107. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  8108. }
  8109. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  8110. if ( boxMesh === undefined ) {
  8111. boxMesh = new Mesh(
  8112. new BoxGeometry( 1, 1, 1 ),
  8113. new ShaderMaterial( {
  8114. name: 'BackgroundCubeMaterial',
  8115. uniforms: cloneUniforms( ShaderLib.cube.uniforms ),
  8116. vertexShader: ShaderLib.cube.vertexShader,
  8117. fragmentShader: ShaderLib.cube.fragmentShader,
  8118. side: BackSide,
  8119. depthTest: false,
  8120. depthWrite: false,
  8121. fog: false
  8122. } )
  8123. );
  8124. boxMesh.geometry.deleteAttribute( 'normal' );
  8125. boxMesh.geometry.deleteAttribute( 'uv' );
  8126. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  8127. this.matrixWorld.copyPosition( camera.matrixWorld );
  8128. };
  8129. // enable code injection for non-built-in material
  8130. Object.defineProperty( boxMesh.material, 'envMap', {
  8131. get: function () {
  8132. return this.uniforms.envMap.value;
  8133. }
  8134. } );
  8135. objects.update( boxMesh );
  8136. }
  8137. boxMesh.material.uniforms.envMap.value = background;
  8138. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background._needsFlipEnvMap ) ? - 1 : 1;
  8139. if ( currentBackground !== background ||
  8140. currentBackgroundVersion !== background.version ||
  8141. currentTonemapping !== renderer.toneMapping ) {
  8142. boxMesh.material.needsUpdate = true;
  8143. currentBackground = background;
  8144. currentBackgroundVersion = background.version;
  8145. currentTonemapping = renderer.toneMapping;
  8146. }
  8147. // push to the pre-sorted opaque render list
  8148. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  8149. } else if ( background && background.isTexture ) {
  8150. if ( planeMesh === undefined ) {
  8151. planeMesh = new Mesh(
  8152. new PlaneGeometry( 2, 2 ),
  8153. new ShaderMaterial( {
  8154. name: 'BackgroundMaterial',
  8155. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  8156. vertexShader: ShaderLib.background.vertexShader,
  8157. fragmentShader: ShaderLib.background.fragmentShader,
  8158. side: FrontSide,
  8159. depthTest: false,
  8160. depthWrite: false,
  8161. fog: false
  8162. } )
  8163. );
  8164. planeMesh.geometry.deleteAttribute( 'normal' );
  8165. // enable code injection for non-built-in material
  8166. Object.defineProperty( planeMesh.material, 'map', {
  8167. get: function () {
  8168. return this.uniforms.t2D.value;
  8169. }
  8170. } );
  8171. objects.update( planeMesh );
  8172. }
  8173. planeMesh.material.uniforms.t2D.value = background;
  8174. if ( background.matrixAutoUpdate === true ) {
  8175. background.updateMatrix();
  8176. }
  8177. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  8178. if ( currentBackground !== background ||
  8179. currentBackgroundVersion !== background.version ||
  8180. currentTonemapping !== renderer.toneMapping ) {
  8181. planeMesh.material.needsUpdate = true;
  8182. currentBackground = background;
  8183. currentBackgroundVersion = background.version;
  8184. currentTonemapping = renderer.toneMapping;
  8185. }
  8186. // push to the pre-sorted opaque render list
  8187. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  8188. }
  8189. }
  8190. function setClear( color, alpha ) {
  8191. state.buffers.color.setClear( color.r, color.g, color.b, alpha, premultipliedAlpha );
  8192. }
  8193. return {
  8194. getClearColor: function () {
  8195. return clearColor;
  8196. },
  8197. setClearColor: function ( color, alpha = 1 ) {
  8198. clearColor.set( color );
  8199. clearAlpha = alpha;
  8200. setClear( clearColor, clearAlpha );
  8201. },
  8202. getClearAlpha: function () {
  8203. return clearAlpha;
  8204. },
  8205. setClearAlpha: function ( alpha ) {
  8206. clearAlpha = alpha;
  8207. setClear( clearColor, clearAlpha );
  8208. },
  8209. render: render
  8210. };
  8211. }
  8212. function WebGLBindingStates( gl, extensions, attributes, capabilities ) {
  8213. const maxVertexAttributes = gl.getParameter( 34921 );
  8214. const extension = capabilities.isWebGL2 ? null : extensions.get( 'OES_vertex_array_object' );
  8215. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8216. const bindingStates = {};
  8217. const defaultState = createBindingState( null );
  8218. let currentState = defaultState;
  8219. function setup( object, material, program, geometry, index ) {
  8220. let updateBuffers = false;
  8221. if ( vaoAvailable ) {
  8222. const state = getBindingState( geometry, program, material );
  8223. if ( currentState !== state ) {
  8224. currentState = state;
  8225. bindVertexArrayObject( currentState.object );
  8226. }
  8227. updateBuffers = needsUpdate( geometry, index );
  8228. if ( updateBuffers ) saveCache( geometry, index );
  8229. } else {
  8230. const wireframe = ( material.wireframe === true );
  8231. if ( currentState.geometry !== geometry.id ||
  8232. currentState.program !== program.id ||
  8233. currentState.wireframe !== wireframe ) {
  8234. currentState.geometry = geometry.id;
  8235. currentState.program = program.id;
  8236. currentState.wireframe = wireframe;
  8237. updateBuffers = true;
  8238. }
  8239. }
  8240. if ( object.isInstancedMesh === true ) {
  8241. updateBuffers = true;
  8242. }
  8243. if ( index !== null ) {
  8244. attributes.update( index, 34963 );
  8245. }
  8246. if ( updateBuffers ) {
  8247. setupVertexAttributes( object, material, program, geometry );
  8248. if ( index !== null ) {
  8249. gl.bindBuffer( 34963, attributes.get( index ).buffer );
  8250. }
  8251. }
  8252. }
  8253. function createVertexArrayObject() {
  8254. if ( capabilities.isWebGL2 ) return gl.createVertexArray();
  8255. return extension.createVertexArrayOES();
  8256. }
  8257. function bindVertexArrayObject( vao ) {
  8258. if ( capabilities.isWebGL2 ) return gl.bindVertexArray( vao );
  8259. return extension.bindVertexArrayOES( vao );
  8260. }
  8261. function deleteVertexArrayObject( vao ) {
  8262. if ( capabilities.isWebGL2 ) return gl.deleteVertexArray( vao );
  8263. return extension.deleteVertexArrayOES( vao );
  8264. }
  8265. function getBindingState( geometry, program, material ) {
  8266. const wireframe = ( material.wireframe === true );
  8267. let programMap = bindingStates[ geometry.id ];
  8268. if ( programMap === undefined ) {
  8269. programMap = {};
  8270. bindingStates[ geometry.id ] = programMap;
  8271. }
  8272. let stateMap = programMap[ program.id ];
  8273. if ( stateMap === undefined ) {
  8274. stateMap = {};
  8275. programMap[ program.id ] = stateMap;
  8276. }
  8277. let state = stateMap[ wireframe ];
  8278. if ( state === undefined ) {
  8279. state = createBindingState( createVertexArrayObject() );
  8280. stateMap[ wireframe ] = state;
  8281. }
  8282. return state;
  8283. }
  8284. function createBindingState( vao ) {
  8285. const newAttributes = [];
  8286. const enabledAttributes = [];
  8287. const attributeDivisors = [];
  8288. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  8289. newAttributes[ i ] = 0;
  8290. enabledAttributes[ i ] = 0;
  8291. attributeDivisors[ i ] = 0;
  8292. }
  8293. return {
  8294. // for backward compatibility on non-VAO support browser
  8295. geometry: null,
  8296. program: null,
  8297. wireframe: false,
  8298. newAttributes: newAttributes,
  8299. enabledAttributes: enabledAttributes,
  8300. attributeDivisors: attributeDivisors,
  8301. object: vao,
  8302. attributes: {},
  8303. index: null
  8304. };
  8305. }
  8306. function needsUpdate( geometry, index ) {
  8307. const cachedAttributes = currentState.attributes;
  8308. const geometryAttributes = geometry.attributes;
  8309. let attributesNum = 0;
  8310. for ( const key in geometryAttributes ) {
  8311. const cachedAttribute = cachedAttributes[ key ];
  8312. const geometryAttribute = geometryAttributes[ key ];
  8313. if ( cachedAttribute === undefined ) return true;
  8314. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  8315. if ( cachedAttribute.data !== geometryAttribute.data ) return true;
  8316. attributesNum ++;
  8317. }
  8318. if ( currentState.attributesNum !== attributesNum ) return true;
  8319. if ( currentState.index !== index ) return true;
  8320. return false;
  8321. }
  8322. function saveCache( geometry, index ) {
  8323. const cache = {};
  8324. const attributes = geometry.attributes;
  8325. let attributesNum = 0;
  8326. for ( const key in attributes ) {
  8327. const attribute = attributes[ key ];
  8328. const data = {};
  8329. data.attribute = attribute;
  8330. if ( attribute.data ) {
  8331. data.data = attribute.data;
  8332. }
  8333. cache[ key ] = data;
  8334. attributesNum ++;
  8335. }
  8336. currentState.attributes = cache;
  8337. currentState.attributesNum = attributesNum;
  8338. currentState.index = index;
  8339. }
  8340. function initAttributes() {
  8341. const newAttributes = currentState.newAttributes;
  8342. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  8343. newAttributes[ i ] = 0;
  8344. }
  8345. }
  8346. function enableAttribute( attribute ) {
  8347. enableAttributeAndDivisor( attribute, 0 );
  8348. }
  8349. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  8350. const newAttributes = currentState.newAttributes;
  8351. const enabledAttributes = currentState.enabledAttributes;
  8352. const attributeDivisors = currentState.attributeDivisors;
  8353. newAttributes[ attribute ] = 1;
  8354. if ( enabledAttributes[ attribute ] === 0 ) {
  8355. gl.enableVertexAttribArray( attribute );
  8356. enabledAttributes[ attribute ] = 1;
  8357. }
  8358. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  8359. const extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );
  8360. extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
  8361. attributeDivisors[ attribute ] = meshPerAttribute;
  8362. }
  8363. }
  8364. function disableUnusedAttributes() {
  8365. const newAttributes = currentState.newAttributes;
  8366. const enabledAttributes = currentState.enabledAttributes;
  8367. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  8368. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  8369. gl.disableVertexAttribArray( i );
  8370. enabledAttributes[ i ] = 0;
  8371. }
  8372. }
  8373. }
  8374. function vertexAttribPointer( index, size, type, normalized, stride, offset ) {
  8375. if ( capabilities.isWebGL2 === true && ( type === 5124 || type === 5125 ) ) {
  8376. gl.vertexAttribIPointer( index, size, type, stride, offset );
  8377. } else {
  8378. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  8379. }
  8380. }
  8381. function setupVertexAttributes( object, material, program, geometry ) {
  8382. if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {
  8383. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return;
  8384. }
  8385. initAttributes();
  8386. const geometryAttributes = geometry.attributes;
  8387. const programAttributes = program.getAttributes();
  8388. const materialDefaultAttributeValues = material.defaultAttributeValues;
  8389. for ( const name in programAttributes ) {
  8390. const programAttribute = programAttributes[ name ];
  8391. if ( programAttribute >= 0 ) {
  8392. const geometryAttribute = geometryAttributes[ name ];
  8393. if ( geometryAttribute !== undefined ) {
  8394. const normalized = geometryAttribute.normalized;
  8395. const size = geometryAttribute.itemSize;
  8396. const attribute = attributes.get( geometryAttribute );
  8397. // TODO Attribute may not be available on context restore
  8398. if ( attribute === undefined ) continue;
  8399. const buffer = attribute.buffer;
  8400. const type = attribute.type;
  8401. const bytesPerElement = attribute.bytesPerElement;
  8402. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  8403. const data = geometryAttribute.data;
  8404. const stride = data.stride;
  8405. const offset = geometryAttribute.offset;
  8406. if ( data && data.isInstancedInterleavedBuffer ) {
  8407. enableAttributeAndDivisor( programAttribute, data.meshPerAttribute );
  8408. if ( geometry._maxInstanceCount === undefined ) {
  8409. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  8410. }
  8411. } else {
  8412. enableAttribute( programAttribute );
  8413. }
  8414. gl.bindBuffer( 34962, buffer );
  8415. vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement );
  8416. } else {
  8417. if ( geometryAttribute.isInstancedBufferAttribute ) {
  8418. enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute );
  8419. if ( geometry._maxInstanceCount === undefined ) {
  8420. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  8421. }
  8422. } else {
  8423. enableAttribute( programAttribute );
  8424. }
  8425. gl.bindBuffer( 34962, buffer );
  8426. vertexAttribPointer( programAttribute, size, type, normalized, 0, 0 );
  8427. }
  8428. } else if ( name === 'instanceMatrix' ) {
  8429. const attribute = attributes.get( object.instanceMatrix );
  8430. // TODO Attribute may not be available on context restore
  8431. if ( attribute === undefined ) continue;
  8432. const buffer = attribute.buffer;
  8433. const type = attribute.type;
  8434. enableAttributeAndDivisor( programAttribute + 0, 1 );
  8435. enableAttributeAndDivisor( programAttribute + 1, 1 );
  8436. enableAttributeAndDivisor( programAttribute + 2, 1 );
  8437. enableAttributeAndDivisor( programAttribute + 3, 1 );
  8438. gl.bindBuffer( 34962, buffer );
  8439. gl.vertexAttribPointer( programAttribute + 0, 4, type, false, 64, 0 );
  8440. gl.vertexAttribPointer( programAttribute + 1, 4, type, false, 64, 16 );
  8441. gl.vertexAttribPointer( programAttribute + 2, 4, type, false, 64, 32 );
  8442. gl.vertexAttribPointer( programAttribute + 3, 4, type, false, 64, 48 );
  8443. } else if ( name === 'instanceColor' ) {
  8444. const attribute = attributes.get( object.instanceColor );
  8445. // TODO Attribute may not be available on context restore
  8446. if ( attribute === undefined ) continue;
  8447. const buffer = attribute.buffer;
  8448. const type = attribute.type;
  8449. enableAttributeAndDivisor( programAttribute, 1 );
  8450. gl.bindBuffer( 34962, buffer );
  8451. gl.vertexAttribPointer( programAttribute, 3, type, false, 12, 0 );
  8452. } else if ( materialDefaultAttributeValues !== undefined ) {
  8453. const value = materialDefaultAttributeValues[ name ];
  8454. if ( value !== undefined ) {
  8455. switch ( value.length ) {
  8456. case 2:
  8457. gl.vertexAttrib2fv( programAttribute, value );
  8458. break;
  8459. case 3:
  8460. gl.vertexAttrib3fv( programAttribute, value );
  8461. break;
  8462. case 4:
  8463. gl.vertexAttrib4fv( programAttribute, value );
  8464. break;
  8465. default:
  8466. gl.vertexAttrib1fv( programAttribute, value );
  8467. }
  8468. }
  8469. }
  8470. }
  8471. }
  8472. disableUnusedAttributes();
  8473. }
  8474. function dispose() {
  8475. reset();
  8476. for ( const geometryId in bindingStates ) {
  8477. const programMap = bindingStates[ geometryId ];
  8478. for ( const programId in programMap ) {
  8479. const stateMap = programMap[ programId ];
  8480. for ( const wireframe in stateMap ) {
  8481. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8482. delete stateMap[ wireframe ];
  8483. }
  8484. delete programMap[ programId ];
  8485. }
  8486. delete bindingStates[ geometryId ];
  8487. }
  8488. }
  8489. function releaseStatesOfGeometry( geometry ) {
  8490. if ( bindingStates[ geometry.id ] === undefined ) return;
  8491. const programMap = bindingStates[ geometry.id ];
  8492. for ( const programId in programMap ) {
  8493. const stateMap = programMap[ programId ];
  8494. for ( const wireframe in stateMap ) {
  8495. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8496. delete stateMap[ wireframe ];
  8497. }
  8498. delete programMap[ programId ];
  8499. }
  8500. delete bindingStates[ geometry.id ];
  8501. }
  8502. function releaseStatesOfProgram( program ) {
  8503. for ( const geometryId in bindingStates ) {
  8504. const programMap = bindingStates[ geometryId ];
  8505. if ( programMap[ program.id ] === undefined ) continue;
  8506. const stateMap = programMap[ program.id ];
  8507. for ( const wireframe in stateMap ) {
  8508. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8509. delete stateMap[ wireframe ];
  8510. }
  8511. delete programMap[ program.id ];
  8512. }
  8513. }
  8514. function reset() {
  8515. resetDefaultState();
  8516. if ( currentState === defaultState ) return;
  8517. currentState = defaultState;
  8518. bindVertexArrayObject( currentState.object );
  8519. }
  8520. // for backward-compatilibity
  8521. function resetDefaultState() {
  8522. defaultState.geometry = null;
  8523. defaultState.program = null;
  8524. defaultState.wireframe = false;
  8525. }
  8526. return {
  8527. setup: setup,
  8528. reset: reset,
  8529. resetDefaultState: resetDefaultState,
  8530. dispose: dispose,
  8531. releaseStatesOfGeometry: releaseStatesOfGeometry,
  8532. releaseStatesOfProgram: releaseStatesOfProgram,
  8533. initAttributes: initAttributes,
  8534. enableAttribute: enableAttribute,
  8535. disableUnusedAttributes: disableUnusedAttributes
  8536. };
  8537. }
  8538. function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
  8539. const isWebGL2 = capabilities.isWebGL2;
  8540. let mode;
  8541. function setMode( value ) {
  8542. mode = value;
  8543. }
  8544. function render( start, count ) {
  8545. gl.drawArrays( mode, start, count );
  8546. info.update( count, mode, 1 );
  8547. }
  8548. function renderInstances( start, count, primcount ) {
  8549. if ( primcount === 0 ) return;
  8550. let extension, methodName;
  8551. if ( isWebGL2 ) {
  8552. extension = gl;
  8553. methodName = 'drawArraysInstanced';
  8554. } else {
  8555. extension = extensions.get( 'ANGLE_instanced_arrays' );
  8556. methodName = 'drawArraysInstancedANGLE';
  8557. if ( extension === null ) {
  8558. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  8559. return;
  8560. }
  8561. }
  8562. extension[ methodName ]( mode, start, count, primcount );
  8563. info.update( count, mode, primcount );
  8564. }
  8565. //
  8566. this.setMode = setMode;
  8567. this.render = render;
  8568. this.renderInstances = renderInstances;
  8569. }
  8570. function WebGLCapabilities( gl, extensions, parameters ) {
  8571. let maxAnisotropy;
  8572. function getMaxAnisotropy() {
  8573. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  8574. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  8575. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  8576. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  8577. } else {
  8578. maxAnisotropy = 0;
  8579. }
  8580. return maxAnisotropy;
  8581. }
  8582. function getMaxPrecision( precision ) {
  8583. if ( precision === 'highp' ) {
  8584. if ( gl.getShaderPrecisionFormat( 35633, 36338 ).precision > 0 &&
  8585. gl.getShaderPrecisionFormat( 35632, 36338 ).precision > 0 ) {
  8586. return 'highp';
  8587. }
  8588. precision = 'mediump';
  8589. }
  8590. if ( precision === 'mediump' ) {
  8591. if ( gl.getShaderPrecisionFormat( 35633, 36337 ).precision > 0 &&
  8592. gl.getShaderPrecisionFormat( 35632, 36337 ).precision > 0 ) {
  8593. return 'mediump';
  8594. }
  8595. }
  8596. return 'lowp';
  8597. }
  8598. /* eslint-disable no-undef */
  8599. const isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext ) ||
  8600. ( typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext );
  8601. /* eslint-enable no-undef */
  8602. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  8603. const maxPrecision = getMaxPrecision( precision );
  8604. if ( maxPrecision !== precision ) {
  8605. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  8606. precision = maxPrecision;
  8607. }
  8608. const drawBuffers = isWebGL2 || extensions.has( 'WEBGL_draw_buffers' );
  8609. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  8610. const maxTextures = gl.getParameter( 34930 );
  8611. const maxVertexTextures = gl.getParameter( 35660 );
  8612. const maxTextureSize = gl.getParameter( 3379 );
  8613. const maxCubemapSize = gl.getParameter( 34076 );
  8614. const maxAttributes = gl.getParameter( 34921 );
  8615. const maxVertexUniforms = gl.getParameter( 36347 );
  8616. const maxVaryings = gl.getParameter( 36348 );
  8617. const maxFragmentUniforms = gl.getParameter( 36349 );
  8618. const vertexTextures = maxVertexTextures > 0;
  8619. const floatFragmentTextures = isWebGL2 || extensions.has( 'OES_texture_float' );
  8620. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  8621. const maxSamples = isWebGL2 ? gl.getParameter( 36183 ) : 0;
  8622. return {
  8623. isWebGL2: isWebGL2,
  8624. drawBuffers: drawBuffers,
  8625. getMaxAnisotropy: getMaxAnisotropy,
  8626. getMaxPrecision: getMaxPrecision,
  8627. precision: precision,
  8628. logarithmicDepthBuffer: logarithmicDepthBuffer,
  8629. maxTextures: maxTextures,
  8630. maxVertexTextures: maxVertexTextures,
  8631. maxTextureSize: maxTextureSize,
  8632. maxCubemapSize: maxCubemapSize,
  8633. maxAttributes: maxAttributes,
  8634. maxVertexUniforms: maxVertexUniforms,
  8635. maxVaryings: maxVaryings,
  8636. maxFragmentUniforms: maxFragmentUniforms,
  8637. vertexTextures: vertexTextures,
  8638. floatFragmentTextures: floatFragmentTextures,
  8639. floatVertexTextures: floatVertexTextures,
  8640. maxSamples: maxSamples
  8641. };
  8642. }
  8643. function WebGLClipping( properties ) {
  8644. const scope = this;
  8645. let globalState = null,
  8646. numGlobalPlanes = 0,
  8647. localClippingEnabled = false,
  8648. renderingShadows = false;
  8649. const plane = new Plane(),
  8650. viewNormalMatrix = new Matrix3(),
  8651. uniform = { value: null, needsUpdate: false };
  8652. this.uniform = uniform;
  8653. this.numPlanes = 0;
  8654. this.numIntersection = 0;
  8655. this.init = function ( planes, enableLocalClipping, camera ) {
  8656. const enabled =
  8657. planes.length !== 0 ||
  8658. enableLocalClipping ||
  8659. // enable state of previous frame - the clipping code has to
  8660. // run another frame in order to reset the state:
  8661. numGlobalPlanes !== 0 ||
  8662. localClippingEnabled;
  8663. localClippingEnabled = enableLocalClipping;
  8664. globalState = projectPlanes( planes, camera, 0 );
  8665. numGlobalPlanes = planes.length;
  8666. return enabled;
  8667. };
  8668. this.beginShadows = function () {
  8669. renderingShadows = true;
  8670. projectPlanes( null );
  8671. };
  8672. this.endShadows = function () {
  8673. renderingShadows = false;
  8674. resetGlobalState();
  8675. };
  8676. this.setState = function ( material, camera, useCache ) {
  8677. const planes = material.clippingPlanes,
  8678. clipIntersection = material.clipIntersection,
  8679. clipShadows = material.clipShadows;
  8680. const materialProperties = properties.get( material );
  8681. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  8682. // there's no local clipping
  8683. if ( renderingShadows ) {
  8684. // there's no global clipping
  8685. projectPlanes( null );
  8686. } else {
  8687. resetGlobalState();
  8688. }
  8689. } else {
  8690. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  8691. lGlobal = nGlobal * 4;
  8692. let dstArray = materialProperties.clippingState || null;
  8693. uniform.value = dstArray; // ensure unique state
  8694. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  8695. for ( let i = 0; i !== lGlobal; ++ i ) {
  8696. dstArray[ i ] = globalState[ i ];
  8697. }
  8698. materialProperties.clippingState = dstArray;
  8699. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  8700. this.numPlanes += nGlobal;
  8701. }
  8702. };
  8703. function resetGlobalState() {
  8704. if ( uniform.value !== globalState ) {
  8705. uniform.value = globalState;
  8706. uniform.needsUpdate = numGlobalPlanes > 0;
  8707. }
  8708. scope.numPlanes = numGlobalPlanes;
  8709. scope.numIntersection = 0;
  8710. }
  8711. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  8712. const nPlanes = planes !== null ? planes.length : 0;
  8713. let dstArray = null;
  8714. if ( nPlanes !== 0 ) {
  8715. dstArray = uniform.value;
  8716. if ( skipTransform !== true || dstArray === null ) {
  8717. const flatSize = dstOffset + nPlanes * 4,
  8718. viewMatrix = camera.matrixWorldInverse;
  8719. viewNormalMatrix.getNormalMatrix( viewMatrix );
  8720. if ( dstArray === null || dstArray.length < flatSize ) {
  8721. dstArray = new Float32Array( flatSize );
  8722. }
  8723. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  8724. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  8725. plane.normal.toArray( dstArray, i4 );
  8726. dstArray[ i4 + 3 ] = plane.constant;
  8727. }
  8728. }
  8729. uniform.value = dstArray;
  8730. uniform.needsUpdate = true;
  8731. }
  8732. scope.numPlanes = nPlanes;
  8733. scope.numIntersection = 0;
  8734. return dstArray;
  8735. }
  8736. }
  8737. function WebGLCubeMaps( renderer ) {
  8738. let cubemaps = new WeakMap();
  8739. function mapTextureMapping( texture, mapping ) {
  8740. if ( mapping === EquirectangularReflectionMapping ) {
  8741. texture.mapping = CubeReflectionMapping;
  8742. } else if ( mapping === EquirectangularRefractionMapping ) {
  8743. texture.mapping = CubeRefractionMapping;
  8744. }
  8745. return texture;
  8746. }
  8747. function get( texture ) {
  8748. if ( texture && texture.isTexture ) {
  8749. const mapping = texture.mapping;
  8750. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  8751. if ( cubemaps.has( texture ) ) {
  8752. const cubemap = cubemaps.get( texture ).texture;
  8753. return mapTextureMapping( cubemap, texture.mapping );
  8754. } else {
  8755. const image = texture.image;
  8756. if ( image && image.height > 0 ) {
  8757. const currentRenderTarget = renderer.getRenderTarget();
  8758. const renderTarget = new WebGLCubeRenderTarget( image.height / 2 );
  8759. renderTarget.fromEquirectangularTexture( renderer, texture );
  8760. cubemaps.set( texture, renderTarget );
  8761. renderer.setRenderTarget( currentRenderTarget );
  8762. texture.addEventListener( 'dispose', onTextureDispose );
  8763. return mapTextureMapping( renderTarget.texture, texture.mapping );
  8764. } else {
  8765. // image not yet ready. try the conversion next frame
  8766. return null;
  8767. }
  8768. }
  8769. }
  8770. }
  8771. return texture;
  8772. }
  8773. function onTextureDispose( event ) {
  8774. const texture = event.target;
  8775. texture.removeEventListener( 'dispose', onTextureDispose );
  8776. const cubemap = cubemaps.get( texture );
  8777. if ( cubemap !== undefined ) {
  8778. cubemaps.delete( texture );
  8779. cubemap.dispose();
  8780. }
  8781. }
  8782. function dispose() {
  8783. cubemaps = new WeakMap();
  8784. }
  8785. return {
  8786. get: get,
  8787. dispose: dispose
  8788. };
  8789. }
  8790. function WebGLExtensions( gl ) {
  8791. const extensions = {};
  8792. function getExtension( name ) {
  8793. if ( extensions[ name ] !== undefined ) {
  8794. return extensions[ name ];
  8795. }
  8796. let extension;
  8797. switch ( name ) {
  8798. case 'WEBGL_depth_texture':
  8799. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  8800. break;
  8801. case 'EXT_texture_filter_anisotropic':
  8802. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  8803. break;
  8804. case 'WEBGL_compressed_texture_s3tc':
  8805. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  8806. break;
  8807. case 'WEBGL_compressed_texture_pvrtc':
  8808. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  8809. break;
  8810. default:
  8811. extension = gl.getExtension( name );
  8812. }
  8813. extensions[ name ] = extension;
  8814. return extension;
  8815. }
  8816. return {
  8817. has: function ( name ) {
  8818. return getExtension( name ) !== null;
  8819. },
  8820. init: function ( capabilities ) {
  8821. if ( capabilities.isWebGL2 ) {
  8822. getExtension( 'EXT_color_buffer_float' );
  8823. } else {
  8824. getExtension( 'WEBGL_depth_texture' );
  8825. getExtension( 'OES_texture_float' );
  8826. getExtension( 'OES_texture_half_float' );
  8827. getExtension( 'OES_texture_half_float_linear' );
  8828. getExtension( 'OES_standard_derivatives' );
  8829. getExtension( 'OES_element_index_uint' );
  8830. getExtension( 'OES_vertex_array_object' );
  8831. getExtension( 'ANGLE_instanced_arrays' );
  8832. }
  8833. getExtension( 'OES_texture_float_linear' );
  8834. getExtension( 'EXT_color_buffer_half_float' );
  8835. },
  8836. get: function ( name ) {
  8837. const extension = getExtension( name );
  8838. if ( extension === null ) {
  8839. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  8840. }
  8841. return extension;
  8842. }
  8843. };
  8844. }
  8845. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  8846. const geometries = {};
  8847. const wireframeAttributes = new WeakMap();
  8848. function onGeometryDispose( event ) {
  8849. const geometry = event.target;
  8850. if ( geometry.index !== null ) {
  8851. attributes.remove( geometry.index );
  8852. }
  8853. for ( const name in geometry.attributes ) {
  8854. attributes.remove( geometry.attributes[ name ] );
  8855. }
  8856. geometry.removeEventListener( 'dispose', onGeometryDispose );
  8857. delete geometries[ geometry.id ];
  8858. const attribute = wireframeAttributes.get( geometry );
  8859. if ( attribute ) {
  8860. attributes.remove( attribute );
  8861. wireframeAttributes.delete( geometry );
  8862. }
  8863. bindingStates.releaseStatesOfGeometry( geometry );
  8864. if ( geometry.isInstancedBufferGeometry === true ) {
  8865. delete geometry._maxInstanceCount;
  8866. }
  8867. //
  8868. info.memory.geometries --;
  8869. }
  8870. function get( object, geometry ) {
  8871. if ( geometries[ geometry.id ] === true ) return geometry;
  8872. geometry.addEventListener( 'dispose', onGeometryDispose );
  8873. geometries[ geometry.id ] = true;
  8874. info.memory.geometries ++;
  8875. return geometry;
  8876. }
  8877. function update( geometry ) {
  8878. const geometryAttributes = geometry.attributes;
  8879. // Updating index buffer in VAO now. See WebGLBindingStates.
  8880. for ( const name in geometryAttributes ) {
  8881. attributes.update( geometryAttributes[ name ], 34962 );
  8882. }
  8883. // morph targets
  8884. const morphAttributes = geometry.morphAttributes;
  8885. for ( const name in morphAttributes ) {
  8886. const array = morphAttributes[ name ];
  8887. for ( let i = 0, l = array.length; i < l; i ++ ) {
  8888. attributes.update( array[ i ], 34962 );
  8889. }
  8890. }
  8891. }
  8892. function updateWireframeAttribute( geometry ) {
  8893. const indices = [];
  8894. const geometryIndex = geometry.index;
  8895. const geometryPosition = geometry.attributes.position;
  8896. let version = 0;
  8897. if ( geometryIndex !== null ) {
  8898. const array = geometryIndex.array;
  8899. version = geometryIndex.version;
  8900. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  8901. const a = array[ i + 0 ];
  8902. const b = array[ i + 1 ];
  8903. const c = array[ i + 2 ];
  8904. indices.push( a, b, b, c, c, a );
  8905. }
  8906. } else {
  8907. const array = geometryPosition.array;
  8908. version = geometryPosition.version;
  8909. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  8910. const a = i + 0;
  8911. const b = i + 1;
  8912. const c = i + 2;
  8913. indices.push( a, b, b, c, c, a );
  8914. }
  8915. }
  8916. const attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  8917. attribute.version = version;
  8918. // Updating index buffer in VAO now. See WebGLBindingStates
  8919. //
  8920. const previousAttribute = wireframeAttributes.get( geometry );
  8921. if ( previousAttribute ) attributes.remove( previousAttribute );
  8922. //
  8923. wireframeAttributes.set( geometry, attribute );
  8924. }
  8925. function getWireframeAttribute( geometry ) {
  8926. const currentAttribute = wireframeAttributes.get( geometry );
  8927. if ( currentAttribute ) {
  8928. const geometryIndex = geometry.index;
  8929. if ( geometryIndex !== null ) {
  8930. // if the attribute is obsolete, create a new one
  8931. if ( currentAttribute.version < geometryIndex.version ) {
  8932. updateWireframeAttribute( geometry );
  8933. }
  8934. }
  8935. } else {
  8936. updateWireframeAttribute( geometry );
  8937. }
  8938. return wireframeAttributes.get( geometry );
  8939. }
  8940. return {
  8941. get: get,
  8942. update: update,
  8943. getWireframeAttribute: getWireframeAttribute
  8944. };
  8945. }
  8946. function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {
  8947. const isWebGL2 = capabilities.isWebGL2;
  8948. let mode;
  8949. function setMode( value ) {
  8950. mode = value;
  8951. }
  8952. let type, bytesPerElement;
  8953. function setIndex( value ) {
  8954. type = value.type;
  8955. bytesPerElement = value.bytesPerElement;
  8956. }
  8957. function render( start, count ) {
  8958. gl.drawElements( mode, count, type, start * bytesPerElement );
  8959. info.update( count, mode, 1 );
  8960. }
  8961. function renderInstances( start, count, primcount ) {
  8962. if ( primcount === 0 ) return;
  8963. let extension, methodName;
  8964. if ( isWebGL2 ) {
  8965. extension = gl;
  8966. methodName = 'drawElementsInstanced';
  8967. } else {
  8968. extension = extensions.get( 'ANGLE_instanced_arrays' );
  8969. methodName = 'drawElementsInstancedANGLE';
  8970. if ( extension === null ) {
  8971. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  8972. return;
  8973. }
  8974. }
  8975. extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount );
  8976. info.update( count, mode, primcount );
  8977. }
  8978. //
  8979. this.setMode = setMode;
  8980. this.setIndex = setIndex;
  8981. this.render = render;
  8982. this.renderInstances = renderInstances;
  8983. }
  8984. function WebGLInfo( gl ) {
  8985. const memory = {
  8986. geometries: 0,
  8987. textures: 0
  8988. };
  8989. const render = {
  8990. frame: 0,
  8991. calls: 0,
  8992. triangles: 0,
  8993. points: 0,
  8994. lines: 0
  8995. };
  8996. function update( count, mode, instanceCount ) {
  8997. render.calls ++;
  8998. switch ( mode ) {
  8999. case 4:
  9000. render.triangles += instanceCount * ( count / 3 );
  9001. break;
  9002. case 1:
  9003. render.lines += instanceCount * ( count / 2 );
  9004. break;
  9005. case 3:
  9006. render.lines += instanceCount * ( count - 1 );
  9007. break;
  9008. case 2:
  9009. render.lines += instanceCount * count;
  9010. break;
  9011. case 0:
  9012. render.points += instanceCount * count;
  9013. break;
  9014. default:
  9015. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  9016. break;
  9017. }
  9018. }
  9019. function reset() {
  9020. render.frame ++;
  9021. render.calls = 0;
  9022. render.triangles = 0;
  9023. render.points = 0;
  9024. render.lines = 0;
  9025. }
  9026. return {
  9027. memory: memory,
  9028. render: render,
  9029. programs: null,
  9030. autoReset: true,
  9031. reset: reset,
  9032. update: update
  9033. };
  9034. }
  9035. function numericalSort( a, b ) {
  9036. return a[ 0 ] - b[ 0 ];
  9037. }
  9038. function absNumericalSort( a, b ) {
  9039. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  9040. }
  9041. function WebGLMorphtargets( gl ) {
  9042. const influencesList = {};
  9043. const morphInfluences = new Float32Array( 8 );
  9044. const workInfluences = [];
  9045. for ( let i = 0; i < 8; i ++ ) {
  9046. workInfluences[ i ] = [ i, 0 ];
  9047. }
  9048. function update( object, geometry, material, program ) {
  9049. const objectInfluences = object.morphTargetInfluences;
  9050. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  9051. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  9052. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  9053. let influences = influencesList[ geometry.id ];
  9054. if ( influences === undefined || influences.length !== length ) {
  9055. // initialise list
  9056. influences = [];
  9057. for ( let i = 0; i < length; i ++ ) {
  9058. influences[ i ] = [ i, 0 ];
  9059. }
  9060. influencesList[ geometry.id ] = influences;
  9061. }
  9062. // Collect influences
  9063. for ( let i = 0; i < length; i ++ ) {
  9064. const influence = influences[ i ];
  9065. influence[ 0 ] = i;
  9066. influence[ 1 ] = objectInfluences[ i ];
  9067. }
  9068. influences.sort( absNumericalSort );
  9069. for ( let i = 0; i < 8; i ++ ) {
  9070. if ( i < length && influences[ i ][ 1 ] ) {
  9071. workInfluences[ i ][ 0 ] = influences[ i ][ 0 ];
  9072. workInfluences[ i ][ 1 ] = influences[ i ][ 1 ];
  9073. } else {
  9074. workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER;
  9075. workInfluences[ i ][ 1 ] = 0;
  9076. }
  9077. }
  9078. workInfluences.sort( numericalSort );
  9079. const morphTargets = material.morphTargets && geometry.morphAttributes.position;
  9080. const morphNormals = material.morphNormals && geometry.morphAttributes.normal;
  9081. let morphInfluencesSum = 0;
  9082. for ( let i = 0; i < 8; i ++ ) {
  9083. const influence = workInfluences[ i ];
  9084. const index = influence[ 0 ];
  9085. const value = influence[ 1 ];
  9086. if ( index !== Number.MAX_SAFE_INTEGER && value ) {
  9087. if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) {
  9088. geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] );
  9089. }
  9090. if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) {
  9091. geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] );
  9092. }
  9093. morphInfluences[ i ] = value;
  9094. morphInfluencesSum += value;
  9095. } else {
  9096. if ( morphTargets && geometry.hasAttribute( 'morphTarget' + i ) === true ) {
  9097. geometry.deleteAttribute( 'morphTarget' + i );
  9098. }
  9099. if ( morphNormals && geometry.hasAttribute( 'morphNormal' + i ) === true ) {
  9100. geometry.deleteAttribute( 'morphNormal' + i );
  9101. }
  9102. morphInfluences[ i ] = 0;
  9103. }
  9104. }
  9105. // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  9106. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  9107. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  9108. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  9109. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  9110. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  9111. }
  9112. return {
  9113. update: update
  9114. };
  9115. }
  9116. function WebGLObjects( gl, geometries, attributes, info ) {
  9117. let updateMap = new WeakMap();
  9118. function update( object ) {
  9119. const frame = info.render.frame;
  9120. const geometry = object.geometry;
  9121. const buffergeometry = geometries.get( object, geometry );
  9122. // Update once per frame
  9123. if ( updateMap.get( buffergeometry ) !== frame ) {
  9124. geometries.update( buffergeometry );
  9125. updateMap.set( buffergeometry, frame );
  9126. }
  9127. if ( object.isInstancedMesh ) {
  9128. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  9129. object.addEventListener( 'dispose', onInstancedMeshDispose );
  9130. }
  9131. attributes.update( object.instanceMatrix, 34962 );
  9132. if ( object.instanceColor !== null ) {
  9133. attributes.update( object.instanceColor, 34962 );
  9134. }
  9135. }
  9136. return buffergeometry;
  9137. }
  9138. function dispose() {
  9139. updateMap = new WeakMap();
  9140. }
  9141. function onInstancedMeshDispose( event ) {
  9142. const instancedMesh = event.target;
  9143. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  9144. attributes.remove( instancedMesh.instanceMatrix );
  9145. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  9146. }
  9147. return {
  9148. update: update,
  9149. dispose: dispose
  9150. };
  9151. }
  9152. class DataTexture2DArray extends Texture {
  9153. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  9154. super( null );
  9155. this.image = { data, width, height, depth };
  9156. this.magFilter = NearestFilter;
  9157. this.minFilter = NearestFilter;
  9158. this.wrapR = ClampToEdgeWrapping;
  9159. this.generateMipmaps = false;
  9160. this.flipY = false;
  9161. this.unpackAlignment = 1;
  9162. this.needsUpdate = true;
  9163. }
  9164. }
  9165. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  9166. class DataTexture3D extends Texture {
  9167. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  9168. // We're going to add .setXXX() methods for setting properties later.
  9169. // Users can still set in DataTexture3D directly.
  9170. //
  9171. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  9172. // texture.anisotropy = 16;
  9173. //
  9174. // See #14839
  9175. super( null );
  9176. this.image = { data, width, height, depth };
  9177. this.magFilter = NearestFilter;
  9178. this.minFilter = NearestFilter;
  9179. this.wrapR = ClampToEdgeWrapping;
  9180. this.generateMipmaps = false;
  9181. this.flipY = false;
  9182. this.unpackAlignment = 1;
  9183. this.needsUpdate = true;
  9184. }
  9185. }
  9186. DataTexture3D.prototype.isDataTexture3D = true;
  9187. /**
  9188. * Uniforms of a program.
  9189. * Those form a tree structure with a special top-level container for the root,
  9190. * which you get by calling 'new WebGLUniforms( gl, program )'.
  9191. *
  9192. *
  9193. * Properties of inner nodes including the top-level container:
  9194. *
  9195. * .seq - array of nested uniforms
  9196. * .map - nested uniforms by name
  9197. *
  9198. *
  9199. * Methods of all nodes except the top-level container:
  9200. *
  9201. * .setValue( gl, value, [textures] )
  9202. *
  9203. * uploads a uniform value(s)
  9204. * the 'textures' parameter is needed for sampler uniforms
  9205. *
  9206. *
  9207. * Static methods of the top-level container (textures factorizations):
  9208. *
  9209. * .upload( gl, seq, values, textures )
  9210. *
  9211. * sets uniforms in 'seq' to 'values[id].value'
  9212. *
  9213. * .seqWithValue( seq, values ) : filteredSeq
  9214. *
  9215. * filters 'seq' entries with corresponding entry in values
  9216. *
  9217. *
  9218. * Methods of the top-level container (textures factorizations):
  9219. *
  9220. * .setValue( gl, name, value, textures )
  9221. *
  9222. * sets uniform with name 'name' to 'value'
  9223. *
  9224. * .setOptional( gl, obj, prop )
  9225. *
  9226. * like .set for an optional property of the object
  9227. *
  9228. */
  9229. const emptyTexture = new Texture();
  9230. const emptyTexture2dArray = new DataTexture2DArray();
  9231. const emptyTexture3d = new DataTexture3D();
  9232. const emptyCubeTexture = new CubeTexture();
  9233. // --- Utilities ---
  9234. // Array Caches (provide typed arrays for temporary by size)
  9235. const arrayCacheF32 = [];
  9236. const arrayCacheI32 = [];
  9237. // Float32Array caches used for uploading Matrix uniforms
  9238. const mat4array = new Float32Array( 16 );
  9239. const mat3array = new Float32Array( 9 );
  9240. const mat2array = new Float32Array( 4 );
  9241. // Flattening for arrays of vectors and matrices
  9242. function flatten( array, nBlocks, blockSize ) {
  9243. const firstElem = array[ 0 ];
  9244. if ( firstElem <= 0 || firstElem > 0 ) return array;
  9245. // unoptimized: ! isNaN( firstElem )
  9246. // see http://jacksondunstan.com/articles/983
  9247. const n = nBlocks * blockSize;
  9248. let r = arrayCacheF32[ n ];
  9249. if ( r === undefined ) {
  9250. r = new Float32Array( n );
  9251. arrayCacheF32[ n ] = r;
  9252. }
  9253. if ( nBlocks !== 0 ) {
  9254. firstElem.toArray( r, 0 );
  9255. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  9256. offset += blockSize;
  9257. array[ i ].toArray( r, offset );
  9258. }
  9259. }
  9260. return r;
  9261. }
  9262. function arraysEqual( a, b ) {
  9263. if ( a.length !== b.length ) return false;
  9264. for ( let i = 0, l = a.length; i < l; i ++ ) {
  9265. if ( a[ i ] !== b[ i ] ) return false;
  9266. }
  9267. return true;
  9268. }
  9269. function copyArray( a, b ) {
  9270. for ( let i = 0, l = b.length; i < l; i ++ ) {
  9271. a[ i ] = b[ i ];
  9272. }
  9273. }
  9274. // Texture unit allocation
  9275. function allocTexUnits( textures, n ) {
  9276. let r = arrayCacheI32[ n ];
  9277. if ( r === undefined ) {
  9278. r = new Int32Array( n );
  9279. arrayCacheI32[ n ] = r;
  9280. }
  9281. for ( let i = 0; i !== n; ++ i ) {
  9282. r[ i ] = textures.allocateTextureUnit();
  9283. }
  9284. return r;
  9285. }
  9286. // --- Setters ---
  9287. // Note: Defining these methods externally, because they come in a bunch
  9288. // and this way their names minify.
  9289. // Single scalar
  9290. function setValueV1f( gl, v ) {
  9291. const cache = this.cache;
  9292. if ( cache[ 0 ] === v ) return;
  9293. gl.uniform1f( this.addr, v );
  9294. cache[ 0 ] = v;
  9295. }
  9296. // Single float vector (from flat array or THREE.VectorN)
  9297. function setValueV2f( gl, v ) {
  9298. const cache = this.cache;
  9299. if ( v.x !== undefined ) {
  9300. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  9301. gl.uniform2f( this.addr, v.x, v.y );
  9302. cache[ 0 ] = v.x;
  9303. cache[ 1 ] = v.y;
  9304. }
  9305. } else {
  9306. if ( arraysEqual( cache, v ) ) return;
  9307. gl.uniform2fv( this.addr, v );
  9308. copyArray( cache, v );
  9309. }
  9310. }
  9311. function setValueV3f( gl, v ) {
  9312. const cache = this.cache;
  9313. if ( v.x !== undefined ) {
  9314. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  9315. gl.uniform3f( this.addr, v.x, v.y, v.z );
  9316. cache[ 0 ] = v.x;
  9317. cache[ 1 ] = v.y;
  9318. cache[ 2 ] = v.z;
  9319. }
  9320. } else if ( v.r !== undefined ) {
  9321. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  9322. gl.uniform3f( this.addr, v.r, v.g, v.b );
  9323. cache[ 0 ] = v.r;
  9324. cache[ 1 ] = v.g;
  9325. cache[ 2 ] = v.b;
  9326. }
  9327. } else {
  9328. if ( arraysEqual( cache, v ) ) return;
  9329. gl.uniform3fv( this.addr, v );
  9330. copyArray( cache, v );
  9331. }
  9332. }
  9333. function setValueV4f( gl, v ) {
  9334. const cache = this.cache;
  9335. if ( v.x !== undefined ) {
  9336. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  9337. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  9338. cache[ 0 ] = v.x;
  9339. cache[ 1 ] = v.y;
  9340. cache[ 2 ] = v.z;
  9341. cache[ 3 ] = v.w;
  9342. }
  9343. } else {
  9344. if ( arraysEqual( cache, v ) ) return;
  9345. gl.uniform4fv( this.addr, v );
  9346. copyArray( cache, v );
  9347. }
  9348. }
  9349. // Single matrix (from flat array or THREE.MatrixN)
  9350. function setValueM2( gl, v ) {
  9351. const cache = this.cache;
  9352. const elements = v.elements;
  9353. if ( elements === undefined ) {
  9354. if ( arraysEqual( cache, v ) ) return;
  9355. gl.uniformMatrix2fv( this.addr, false, v );
  9356. copyArray( cache, v );
  9357. } else {
  9358. if ( arraysEqual( cache, elements ) ) return;
  9359. mat2array.set( elements );
  9360. gl.uniformMatrix2fv( this.addr, false, mat2array );
  9361. copyArray( cache, elements );
  9362. }
  9363. }
  9364. function setValueM3( gl, v ) {
  9365. const cache = this.cache;
  9366. const elements = v.elements;
  9367. if ( elements === undefined ) {
  9368. if ( arraysEqual( cache, v ) ) return;
  9369. gl.uniformMatrix3fv( this.addr, false, v );
  9370. copyArray( cache, v );
  9371. } else {
  9372. if ( arraysEqual( cache, elements ) ) return;
  9373. mat3array.set( elements );
  9374. gl.uniformMatrix3fv( this.addr, false, mat3array );
  9375. copyArray( cache, elements );
  9376. }
  9377. }
  9378. function setValueM4( gl, v ) {
  9379. const cache = this.cache;
  9380. const elements = v.elements;
  9381. if ( elements === undefined ) {
  9382. if ( arraysEqual( cache, v ) ) return;
  9383. gl.uniformMatrix4fv( this.addr, false, v );
  9384. copyArray( cache, v );
  9385. } else {
  9386. if ( arraysEqual( cache, elements ) ) return;
  9387. mat4array.set( elements );
  9388. gl.uniformMatrix4fv( this.addr, false, mat4array );
  9389. copyArray( cache, elements );
  9390. }
  9391. }
  9392. // Single integer / boolean
  9393. function setValueV1i( gl, v ) {
  9394. const cache = this.cache;
  9395. if ( cache[ 0 ] === v ) return;
  9396. gl.uniform1i( this.addr, v );
  9397. cache[ 0 ] = v;
  9398. }
  9399. // Single integer / boolean vector (from flat array)
  9400. function setValueV2i( gl, v ) {
  9401. const cache = this.cache;
  9402. if ( arraysEqual( cache, v ) ) return;
  9403. gl.uniform2iv( this.addr, v );
  9404. copyArray( cache, v );
  9405. }
  9406. function setValueV3i( gl, v ) {
  9407. const cache = this.cache;
  9408. if ( arraysEqual( cache, v ) ) return;
  9409. gl.uniform3iv( this.addr, v );
  9410. copyArray( cache, v );
  9411. }
  9412. function setValueV4i( gl, v ) {
  9413. const cache = this.cache;
  9414. if ( arraysEqual( cache, v ) ) return;
  9415. gl.uniform4iv( this.addr, v );
  9416. copyArray( cache, v );
  9417. }
  9418. // Single unsigned integer
  9419. function setValueV1ui( gl, v ) {
  9420. const cache = this.cache;
  9421. if ( cache[ 0 ] === v ) return;
  9422. gl.uniform1ui( this.addr, v );
  9423. cache[ 0 ] = v;
  9424. }
  9425. // Single unsigned integer vector (from flat array)
  9426. function setValueV2ui( gl, v ) {
  9427. const cache = this.cache;
  9428. if ( arraysEqual( cache, v ) ) return;
  9429. gl.uniform2uiv( this.addr, v );
  9430. copyArray( cache, v );
  9431. }
  9432. function setValueV3ui( gl, v ) {
  9433. const cache = this.cache;
  9434. if ( arraysEqual( cache, v ) ) return;
  9435. gl.uniform3uiv( this.addr, v );
  9436. copyArray( cache, v );
  9437. }
  9438. function setValueV4ui( gl, v ) {
  9439. const cache = this.cache;
  9440. if ( arraysEqual( cache, v ) ) return;
  9441. gl.uniform4uiv( this.addr, v );
  9442. copyArray( cache, v );
  9443. }
  9444. // Single texture (2D / Cube)
  9445. function setValueT1( gl, v, textures ) {
  9446. const cache = this.cache;
  9447. const unit = textures.allocateTextureUnit();
  9448. if ( cache[ 0 ] !== unit ) {
  9449. gl.uniform1i( this.addr, unit );
  9450. cache[ 0 ] = unit;
  9451. }
  9452. textures.safeSetTexture2D( v || emptyTexture, unit );
  9453. }
  9454. function setValueT3D1( gl, v, textures ) {
  9455. const cache = this.cache;
  9456. const unit = textures.allocateTextureUnit();
  9457. if ( cache[ 0 ] !== unit ) {
  9458. gl.uniform1i( this.addr, unit );
  9459. cache[ 0 ] = unit;
  9460. }
  9461. textures.setTexture3D( v || emptyTexture3d, unit );
  9462. }
  9463. function setValueT6( gl, v, textures ) {
  9464. const cache = this.cache;
  9465. const unit = textures.allocateTextureUnit();
  9466. if ( cache[ 0 ] !== unit ) {
  9467. gl.uniform1i( this.addr, unit );
  9468. cache[ 0 ] = unit;
  9469. }
  9470. textures.safeSetTextureCube( v || emptyCubeTexture, unit );
  9471. }
  9472. function setValueT2DArray1( gl, v, textures ) {
  9473. const cache = this.cache;
  9474. const unit = textures.allocateTextureUnit();
  9475. if ( cache[ 0 ] !== unit ) {
  9476. gl.uniform1i( this.addr, unit );
  9477. cache[ 0 ] = unit;
  9478. }
  9479. textures.setTexture2DArray( v || emptyTexture2dArray, unit );
  9480. }
  9481. // Helper to pick the right setter for the singular case
  9482. function getSingularSetter( type ) {
  9483. switch ( type ) {
  9484. case 0x1406: return setValueV1f; // FLOAT
  9485. case 0x8b50: return setValueV2f; // _VEC2
  9486. case 0x8b51: return setValueV3f; // _VEC3
  9487. case 0x8b52: return setValueV4f; // _VEC4
  9488. case 0x8b5a: return setValueM2; // _MAT2
  9489. case 0x8b5b: return setValueM3; // _MAT3
  9490. case 0x8b5c: return setValueM4; // _MAT4
  9491. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  9492. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  9493. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  9494. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  9495. case 0x1405: return setValueV1ui; // UINT
  9496. case 0x8dc6: return setValueV2ui; // _VEC2
  9497. case 0x8dc7: return setValueV3ui; // _VEC3
  9498. case 0x8dc8: return setValueV4ui; // _VEC4
  9499. case 0x8b5e: // SAMPLER_2D
  9500. case 0x8d66: // SAMPLER_EXTERNAL_OES
  9501. case 0x8dca: // INT_SAMPLER_2D
  9502. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  9503. case 0x8b62: // SAMPLER_2D_SHADOW
  9504. return setValueT1;
  9505. case 0x8b5f: // SAMPLER_3D
  9506. case 0x8dcb: // INT_SAMPLER_3D
  9507. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  9508. return setValueT3D1;
  9509. case 0x8b60: // SAMPLER_CUBE
  9510. case 0x8dcc: // INT_SAMPLER_CUBE
  9511. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  9512. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  9513. return setValueT6;
  9514. case 0x8dc1: // SAMPLER_2D_ARRAY
  9515. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  9516. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  9517. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  9518. return setValueT2DArray1;
  9519. }
  9520. }
  9521. // Array of scalars
  9522. function setValueV1fArray( gl, v ) {
  9523. gl.uniform1fv( this.addr, v );
  9524. }
  9525. // Array of vectors (from flat array or array of THREE.VectorN)
  9526. function setValueV2fArray( gl, v ) {
  9527. const data = flatten( v, this.size, 2 );
  9528. gl.uniform2fv( this.addr, data );
  9529. }
  9530. function setValueV3fArray( gl, v ) {
  9531. const data = flatten( v, this.size, 3 );
  9532. gl.uniform3fv( this.addr, data );
  9533. }
  9534. function setValueV4fArray( gl, v ) {
  9535. const data = flatten( v, this.size, 4 );
  9536. gl.uniform4fv( this.addr, data );
  9537. }
  9538. // Array of matrices (from flat array or array of THREE.MatrixN)
  9539. function setValueM2Array( gl, v ) {
  9540. const data = flatten( v, this.size, 4 );
  9541. gl.uniformMatrix2fv( this.addr, false, data );
  9542. }
  9543. function setValueM3Array( gl, v ) {
  9544. const data = flatten( v, this.size, 9 );
  9545. gl.uniformMatrix3fv( this.addr, false, data );
  9546. }
  9547. function setValueM4Array( gl, v ) {
  9548. const data = flatten( v, this.size, 16 );
  9549. gl.uniformMatrix4fv( this.addr, false, data );
  9550. }
  9551. // Array of integer / boolean
  9552. function setValueV1iArray( gl, v ) {
  9553. gl.uniform1iv( this.addr, v );
  9554. }
  9555. // Array of integer / boolean vectors (from flat array)
  9556. function setValueV2iArray( gl, v ) {
  9557. gl.uniform2iv( this.addr, v );
  9558. }
  9559. function setValueV3iArray( gl, v ) {
  9560. gl.uniform3iv( this.addr, v );
  9561. }
  9562. function setValueV4iArray( gl, v ) {
  9563. gl.uniform4iv( this.addr, v );
  9564. }
  9565. // Array of unsigned integer
  9566. function setValueV1uiArray( gl, v ) {
  9567. gl.uniform1uiv( this.addr, v );
  9568. }
  9569. // Array of unsigned integer vectors (from flat array)
  9570. function setValueV2uiArray( gl, v ) {
  9571. gl.uniform2uiv( this.addr, v );
  9572. }
  9573. function setValueV3uiArray( gl, v ) {
  9574. gl.uniform3uiv( this.addr, v );
  9575. }
  9576. function setValueV4uiArray( gl, v ) {
  9577. gl.uniform4uiv( this.addr, v );
  9578. }
  9579. // Array of textures (2D / Cube)
  9580. function setValueT1Array( gl, v, textures ) {
  9581. const n = v.length;
  9582. const units = allocTexUnits( textures, n );
  9583. gl.uniform1iv( this.addr, units );
  9584. for ( let i = 0; i !== n; ++ i ) {
  9585. textures.safeSetTexture2D( v[ i ] || emptyTexture, units[ i ] );
  9586. }
  9587. }
  9588. function setValueT6Array( gl, v, textures ) {
  9589. const n = v.length;
  9590. const units = allocTexUnits( textures, n );
  9591. gl.uniform1iv( this.addr, units );
  9592. for ( let i = 0; i !== n; ++ i ) {
  9593. textures.safeSetTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  9594. }
  9595. }
  9596. // Helper to pick the right setter for a pure (bottom-level) array
  9597. function getPureArraySetter( type ) {
  9598. switch ( type ) {
  9599. case 0x1406: return setValueV1fArray; // FLOAT
  9600. case 0x8b50: return setValueV2fArray; // _VEC2
  9601. case 0x8b51: return setValueV3fArray; // _VEC3
  9602. case 0x8b52: return setValueV4fArray; // _VEC4
  9603. case 0x8b5a: return setValueM2Array; // _MAT2
  9604. case 0x8b5b: return setValueM3Array; // _MAT3
  9605. case 0x8b5c: return setValueM4Array; // _MAT4
  9606. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  9607. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  9608. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  9609. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  9610. case 0x1405: return setValueV1uiArray; // UINT
  9611. case 0x8dc6: return setValueV2uiArray; // _VEC2
  9612. case 0x8dc7: return setValueV3uiArray; // _VEC3
  9613. case 0x8dc8: return setValueV4uiArray; // _VEC4
  9614. case 0x8b5e: // SAMPLER_2D
  9615. case 0x8d66: // SAMPLER_EXTERNAL_OES
  9616. case 0x8dca: // INT_SAMPLER_2D
  9617. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  9618. case 0x8b62: // SAMPLER_2D_SHADOW
  9619. return setValueT1Array;
  9620. case 0x8b60: // SAMPLER_CUBE
  9621. case 0x8dcc: // INT_SAMPLER_CUBE
  9622. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  9623. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  9624. return setValueT6Array;
  9625. }
  9626. }
  9627. // --- Uniform Classes ---
  9628. function SingleUniform( id, activeInfo, addr ) {
  9629. this.id = id;
  9630. this.addr = addr;
  9631. this.cache = [];
  9632. this.setValue = getSingularSetter( activeInfo.type );
  9633. // this.path = activeInfo.name; // DEBUG
  9634. }
  9635. function PureArrayUniform( id, activeInfo, addr ) {
  9636. this.id = id;
  9637. this.addr = addr;
  9638. this.cache = [];
  9639. this.size = activeInfo.size;
  9640. this.setValue = getPureArraySetter( activeInfo.type );
  9641. // this.path = activeInfo.name; // DEBUG
  9642. }
  9643. PureArrayUniform.prototype.updateCache = function ( data ) {
  9644. const cache = this.cache;
  9645. if ( data instanceof Float32Array && cache.length !== data.length ) {
  9646. this.cache = new Float32Array( data.length );
  9647. }
  9648. copyArray( cache, data );
  9649. };
  9650. function StructuredUniform( id ) {
  9651. this.id = id;
  9652. this.seq = [];
  9653. this.map = {};
  9654. }
  9655. StructuredUniform.prototype.setValue = function ( gl, value, textures ) {
  9656. const seq = this.seq;
  9657. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  9658. const u = seq[ i ];
  9659. u.setValue( gl, value[ u.id ], textures );
  9660. }
  9661. };
  9662. // --- Top-level ---
  9663. // Parser - builds up the property tree from the path strings
  9664. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  9665. // extracts
  9666. // - the identifier (member name or array index)
  9667. // - followed by an optional right bracket (found when array index)
  9668. // - followed by an optional left bracket or dot (type of subscript)
  9669. //
  9670. // Note: These portions can be read in a non-overlapping fashion and
  9671. // allow straightforward parsing of the hierarchy that WebGL encodes
  9672. // in the uniform names.
  9673. function addUniform( container, uniformObject ) {
  9674. container.seq.push( uniformObject );
  9675. container.map[ uniformObject.id ] = uniformObject;
  9676. }
  9677. function parseUniform( activeInfo, addr, container ) {
  9678. const path = activeInfo.name,
  9679. pathLength = path.length;
  9680. // reset RegExp object, because of the early exit of a previous run
  9681. RePathPart.lastIndex = 0;
  9682. while ( true ) {
  9683. const match = RePathPart.exec( path ),
  9684. matchEnd = RePathPart.lastIndex;
  9685. let id = match[ 1 ];
  9686. const idIsIndex = match[ 2 ] === ']',
  9687. subscript = match[ 3 ];
  9688. if ( idIsIndex ) id = id | 0; // convert to integer
  9689. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  9690. // bare name or "pure" bottom-level array "[0]" suffix
  9691. addUniform( container, subscript === undefined ?
  9692. new SingleUniform( id, activeInfo, addr ) :
  9693. new PureArrayUniform( id, activeInfo, addr ) );
  9694. break;
  9695. } else {
  9696. // step into inner node / create it in case it doesn't exist
  9697. const map = container.map;
  9698. let next = map[ id ];
  9699. if ( next === undefined ) {
  9700. next = new StructuredUniform( id );
  9701. addUniform( container, next );
  9702. }
  9703. container = next;
  9704. }
  9705. }
  9706. }
  9707. // Root Container
  9708. function WebGLUniforms( gl, program ) {
  9709. this.seq = [];
  9710. this.map = {};
  9711. const n = gl.getProgramParameter( program, 35718 );
  9712. for ( let i = 0; i < n; ++ i ) {
  9713. const info = gl.getActiveUniform( program, i ),
  9714. addr = gl.getUniformLocation( program, info.name );
  9715. parseUniform( info, addr, this );
  9716. }
  9717. }
  9718. WebGLUniforms.prototype.setValue = function ( gl, name, value, textures ) {
  9719. const u = this.map[ name ];
  9720. if ( u !== undefined ) u.setValue( gl, value, textures );
  9721. };
  9722. WebGLUniforms.prototype.setOptional = function ( gl, object, name ) {
  9723. const v = object[ name ];
  9724. if ( v !== undefined ) this.setValue( gl, name, v );
  9725. };
  9726. // Static interface
  9727. WebGLUniforms.upload = function ( gl, seq, values, textures ) {
  9728. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  9729. const u = seq[ i ],
  9730. v = values[ u.id ];
  9731. if ( v.needsUpdate !== false ) {
  9732. // note: always updating when .needsUpdate is undefined
  9733. u.setValue( gl, v.value, textures );
  9734. }
  9735. }
  9736. };
  9737. WebGLUniforms.seqWithValue = function ( seq, values ) {
  9738. const r = [];
  9739. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  9740. const u = seq[ i ];
  9741. if ( u.id in values ) r.push( u );
  9742. }
  9743. return r;
  9744. };
  9745. function WebGLShader( gl, type, string ) {
  9746. const shader = gl.createShader( type );
  9747. gl.shaderSource( shader, string );
  9748. gl.compileShader( shader );
  9749. return shader;
  9750. }
  9751. let programIdCount = 0;
  9752. function addLineNumbers( string ) {
  9753. const lines = string.split( '\n' );
  9754. for ( let i = 0; i < lines.length; i ++ ) {
  9755. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  9756. }
  9757. return lines.join( '\n' );
  9758. }
  9759. function getEncodingComponents( encoding ) {
  9760. switch ( encoding ) {
  9761. case LinearEncoding:
  9762. return [ 'Linear', '( value )' ];
  9763. case sRGBEncoding:
  9764. return [ 'sRGB', '( value )' ];
  9765. case RGBEEncoding:
  9766. return [ 'RGBE', '( value )' ];
  9767. case RGBM7Encoding:
  9768. return [ 'RGBM', '( value, 7.0 )' ];
  9769. case RGBM16Encoding:
  9770. return [ 'RGBM', '( value, 16.0 )' ];
  9771. case RGBDEncoding:
  9772. return [ 'RGBD', '( value, 256.0 )' ];
  9773. case GammaEncoding:
  9774. return [ 'Gamma', '( value, float( GAMMA_FACTOR ) )' ];
  9775. case LogLuvEncoding:
  9776. return [ 'LogLuv', '( value )' ];
  9777. default:
  9778. console.warn( 'THREE.WebGLProgram: Unsupported encoding:', encoding );
  9779. return [ 'Linear', '( value )' ];
  9780. }
  9781. }
  9782. function getShaderErrors( gl, shader, type ) {
  9783. const status = gl.getShaderParameter( shader, 35713 );
  9784. const log = gl.getShaderInfoLog( shader ).trim();
  9785. if ( status && log === '' ) return '';
  9786. // --enable-privileged-webgl-extension
  9787. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  9788. const source = gl.getShaderSource( shader );
  9789. return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers( source );
  9790. }
  9791. function getTexelDecodingFunction( functionName, encoding ) {
  9792. const components = getEncodingComponents( encoding );
  9793. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[ 0 ] + 'ToLinear' + components[ 1 ] + '; }';
  9794. }
  9795. function getTexelEncodingFunction( functionName, encoding ) {
  9796. const components = getEncodingComponents( encoding );
  9797. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';
  9798. }
  9799. function getToneMappingFunction( functionName, toneMapping ) {
  9800. let toneMappingName;
  9801. switch ( toneMapping ) {
  9802. case LinearToneMapping:
  9803. toneMappingName = 'Linear';
  9804. break;
  9805. case ReinhardToneMapping:
  9806. toneMappingName = 'Reinhard';
  9807. break;
  9808. case CineonToneMapping:
  9809. toneMappingName = 'OptimizedCineon';
  9810. break;
  9811. case ACESFilmicToneMapping:
  9812. toneMappingName = 'ACESFilmic';
  9813. break;
  9814. case CustomToneMapping:
  9815. toneMappingName = 'Custom';
  9816. break;
  9817. default:
  9818. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  9819. toneMappingName = 'Linear';
  9820. }
  9821. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  9822. }
  9823. function generateExtensions( parameters ) {
  9824. const chunks = [
  9825. ( parameters.extensionDerivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  9826. ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '',
  9827. ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '',
  9828. ( parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission > 0.0 ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  9829. ];
  9830. return chunks.filter( filterEmptyLine ).join( '\n' );
  9831. }
  9832. function generateDefines( defines ) {
  9833. const chunks = [];
  9834. for ( const name in defines ) {
  9835. const value = defines[ name ];
  9836. if ( value === false ) continue;
  9837. chunks.push( '#define ' + name + ' ' + value );
  9838. }
  9839. return chunks.join( '\n' );
  9840. }
  9841. function fetchAttributeLocations( gl, program ) {
  9842. const attributes = {};
  9843. const n = gl.getProgramParameter( program, 35721 );
  9844. for ( let i = 0; i < n; i ++ ) {
  9845. const info = gl.getActiveAttrib( program, i );
  9846. const name = info.name;
  9847. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  9848. attributes[ name ] = gl.getAttribLocation( program, name );
  9849. }
  9850. return attributes;
  9851. }
  9852. function filterEmptyLine( string ) {
  9853. return string !== '';
  9854. }
  9855. function replaceLightNums( string, parameters ) {
  9856. return string
  9857. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  9858. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  9859. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  9860. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  9861. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  9862. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  9863. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  9864. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  9865. }
  9866. function replaceClippingPlaneNums( string, parameters ) {
  9867. return string
  9868. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  9869. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  9870. }
  9871. // Resolve Includes
  9872. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  9873. function resolveIncludes( string ) {
  9874. return string.replace( includePattern, includeReplacer );
  9875. }
  9876. function includeReplacer( match, include ) {
  9877. const string = ShaderChunk[ include ];
  9878. if ( string === undefined ) {
  9879. throw new Error( 'Can not resolve #include <' + include + '>' );
  9880. }
  9881. return resolveIncludes( string );
  9882. }
  9883. // Unroll Loops
  9884. const deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  9885. 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;
  9886. function unrollLoops( string ) {
  9887. return string
  9888. .replace( unrollLoopPattern, loopReplacer )
  9889. .replace( deprecatedUnrollLoopPattern, deprecatedLoopReplacer );
  9890. }
  9891. function deprecatedLoopReplacer( match, start, end, snippet ) {
  9892. console.warn( 'WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.' );
  9893. return loopReplacer( match, start, end, snippet );
  9894. }
  9895. function loopReplacer( match, start, end, snippet ) {
  9896. let string = '';
  9897. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  9898. string += snippet
  9899. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  9900. .replace( /UNROLLED_LOOP_INDEX/g, i );
  9901. }
  9902. return string;
  9903. }
  9904. //
  9905. function generatePrecision( parameters ) {
  9906. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  9907. if ( parameters.precision === 'highp' ) {
  9908. precisionstring += '\n#define HIGH_PRECISION';
  9909. } else if ( parameters.precision === 'mediump' ) {
  9910. precisionstring += '\n#define MEDIUM_PRECISION';
  9911. } else if ( parameters.precision === 'lowp' ) {
  9912. precisionstring += '\n#define LOW_PRECISION';
  9913. }
  9914. return precisionstring;
  9915. }
  9916. function generateShadowMapTypeDefine( parameters ) {
  9917. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  9918. if ( parameters.shadowMapType === PCFShadowMap ) {
  9919. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  9920. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  9921. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  9922. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  9923. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  9924. }
  9925. return shadowMapTypeDefine;
  9926. }
  9927. function generateEnvMapTypeDefine( parameters ) {
  9928. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  9929. if ( parameters.envMap ) {
  9930. switch ( parameters.envMapMode ) {
  9931. case CubeReflectionMapping:
  9932. case CubeRefractionMapping:
  9933. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  9934. break;
  9935. case CubeUVReflectionMapping:
  9936. case CubeUVRefractionMapping:
  9937. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  9938. break;
  9939. }
  9940. }
  9941. return envMapTypeDefine;
  9942. }
  9943. function generateEnvMapModeDefine( parameters ) {
  9944. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  9945. if ( parameters.envMap ) {
  9946. switch ( parameters.envMapMode ) {
  9947. case CubeRefractionMapping:
  9948. case CubeUVRefractionMapping:
  9949. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  9950. break;
  9951. }
  9952. }
  9953. return envMapModeDefine;
  9954. }
  9955. function generateEnvMapBlendingDefine( parameters ) {
  9956. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  9957. if ( parameters.envMap ) {
  9958. switch ( parameters.combine ) {
  9959. case MultiplyOperation:
  9960. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  9961. break;
  9962. case MixOperation:
  9963. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  9964. break;
  9965. case AddOperation:
  9966. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  9967. break;
  9968. }
  9969. }
  9970. return envMapBlendingDefine;
  9971. }
  9972. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  9973. const gl = renderer.getContext();
  9974. const defines = parameters.defines;
  9975. let vertexShader = parameters.vertexShader;
  9976. let fragmentShader = parameters.fragmentShader;
  9977. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  9978. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  9979. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  9980. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  9981. const gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  9982. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters );
  9983. const customDefines = generateDefines( defines );
  9984. const program = gl.createProgram();
  9985. let prefixVertex, prefixFragment;
  9986. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  9987. if ( parameters.isRawShaderMaterial ) {
  9988. prefixVertex = [
  9989. customDefines
  9990. ].filter( filterEmptyLine ).join( '\n' );
  9991. if ( prefixVertex.length > 0 ) {
  9992. prefixVertex += '\n';
  9993. }
  9994. prefixFragment = [
  9995. customExtensions,
  9996. customDefines
  9997. ].filter( filterEmptyLine ).join( '\n' );
  9998. if ( prefixFragment.length > 0 ) {
  9999. prefixFragment += '\n';
  10000. }
  10001. } else {
  10002. prefixVertex = [
  10003. generatePrecision( parameters ),
  10004. '#define SHADER_NAME ' + parameters.shaderName,
  10005. customDefines,
  10006. parameters.instancing ? '#define USE_INSTANCING' : '',
  10007. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  10008. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  10009. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  10010. '#define MAX_BONES ' + parameters.maxBones,
  10011. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  10012. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  10013. parameters.map ? '#define USE_MAP' : '',
  10014. parameters.envMap ? '#define USE_ENVMAP' : '',
  10015. parameters.envMap ? '#define ' + envMapModeDefine : '',
  10016. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  10017. parameters.aoMap ? '#define USE_AOMAP' : '',
  10018. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  10019. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  10020. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  10021. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  10022. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  10023. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  10024. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  10025. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  10026. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  10027. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  10028. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  10029. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  10030. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  10031. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  10032. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  10033. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  10034. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  10035. parameters.vertexColors ? '#define USE_COLOR' : '',
  10036. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  10037. parameters.vertexUvs ? '#define USE_UV' : '',
  10038. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  10039. parameters.flatShading ? '#define FLAT_SHADED' : '',
  10040. parameters.skinning ? '#define USE_SKINNING' : '',
  10041. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  10042. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  10043. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  10044. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  10045. parameters.flipSided ? '#define FLIP_SIDED' : '',
  10046. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  10047. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  10048. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  10049. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  10050. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  10051. 'uniform mat4 modelMatrix;',
  10052. 'uniform mat4 modelViewMatrix;',
  10053. 'uniform mat4 projectionMatrix;',
  10054. 'uniform mat4 viewMatrix;',
  10055. 'uniform mat3 normalMatrix;',
  10056. 'uniform vec3 cameraPosition;',
  10057. 'uniform bool isOrthographic;',
  10058. '#ifdef USE_INSTANCING',
  10059. ' attribute mat4 instanceMatrix;',
  10060. '#endif',
  10061. '#ifdef USE_INSTANCING_COLOR',
  10062. ' attribute vec3 instanceColor;',
  10063. '#endif',
  10064. 'attribute vec3 position;',
  10065. 'attribute vec3 normal;',
  10066. 'attribute vec2 uv;',
  10067. '#ifdef USE_TANGENT',
  10068. ' attribute vec4 tangent;',
  10069. '#endif',
  10070. '#if defined( USE_COLOR_ALPHA )',
  10071. ' attribute vec4 color;',
  10072. '#elif defined( USE_COLOR )',
  10073. ' attribute vec3 color;',
  10074. '#endif',
  10075. '#ifdef USE_MORPHTARGETS',
  10076. ' attribute vec3 morphTarget0;',
  10077. ' attribute vec3 morphTarget1;',
  10078. ' attribute vec3 morphTarget2;',
  10079. ' attribute vec3 morphTarget3;',
  10080. ' #ifdef USE_MORPHNORMALS',
  10081. ' attribute vec3 morphNormal0;',
  10082. ' attribute vec3 morphNormal1;',
  10083. ' attribute vec3 morphNormal2;',
  10084. ' attribute vec3 morphNormal3;',
  10085. ' #else',
  10086. ' attribute vec3 morphTarget4;',
  10087. ' attribute vec3 morphTarget5;',
  10088. ' attribute vec3 morphTarget6;',
  10089. ' attribute vec3 morphTarget7;',
  10090. ' #endif',
  10091. '#endif',
  10092. '#ifdef USE_SKINNING',
  10093. ' attribute vec4 skinIndex;',
  10094. ' attribute vec4 skinWeight;',
  10095. '#endif',
  10096. '\n'
  10097. ].filter( filterEmptyLine ).join( '\n' );
  10098. prefixFragment = [
  10099. customExtensions,
  10100. generatePrecision( parameters ),
  10101. '#define SHADER_NAME ' + parameters.shaderName,
  10102. customDefines,
  10103. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + ( parameters.alphaTest % 1 ? '' : '.0' ) : '', // add '.0' if integer
  10104. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  10105. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  10106. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  10107. parameters.map ? '#define USE_MAP' : '',
  10108. parameters.matcap ? '#define USE_MATCAP' : '',
  10109. parameters.envMap ? '#define USE_ENVMAP' : '',
  10110. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  10111. parameters.envMap ? '#define ' + envMapModeDefine : '',
  10112. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  10113. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  10114. parameters.aoMap ? '#define USE_AOMAP' : '',
  10115. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  10116. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  10117. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  10118. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  10119. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  10120. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  10121. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  10122. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  10123. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  10124. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  10125. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  10126. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  10127. parameters.sheen ? '#define USE_SHEEN' : '',
  10128. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  10129. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  10130. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  10131. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  10132. parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '',
  10133. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  10134. parameters.vertexUvs ? '#define USE_UV' : '',
  10135. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  10136. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  10137. parameters.flatShading ? '#define FLAT_SHADED' : '',
  10138. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  10139. parameters.flipSided ? '#define FLIP_SIDED' : '',
  10140. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  10141. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  10142. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  10143. parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '',
  10144. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  10145. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  10146. ( ( parameters.extensionShaderTextureLOD || parameters.envMap ) && parameters.rendererExtensionShaderTextureLod ) ? '#define TEXTURE_LOD_EXT' : '',
  10147. 'uniform mat4 viewMatrix;',
  10148. 'uniform vec3 cameraPosition;',
  10149. 'uniform bool isOrthographic;',
  10150. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  10151. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  10152. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  10153. parameters.dithering ? '#define DITHERING' : '',
  10154. ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  10155. parameters.map ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  10156. parameters.matcap ? getTexelDecodingFunction( 'matcapTexelToLinear', parameters.matcapEncoding ) : '',
  10157. parameters.envMap ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  10158. parameters.emissiveMap ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  10159. parameters.lightMap ? getTexelDecodingFunction( 'lightMapTexelToLinear', parameters.lightMapEncoding ) : '',
  10160. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ),
  10161. parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  10162. '\n'
  10163. ].filter( filterEmptyLine ).join( '\n' );
  10164. }
  10165. vertexShader = resolveIncludes( vertexShader );
  10166. vertexShader = replaceLightNums( vertexShader, parameters );
  10167. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  10168. fragmentShader = resolveIncludes( fragmentShader );
  10169. fragmentShader = replaceLightNums( fragmentShader, parameters );
  10170. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  10171. vertexShader = unrollLoops( vertexShader );
  10172. fragmentShader = unrollLoops( fragmentShader );
  10173. if ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) {
  10174. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  10175. versionString = '#version 300 es\n';
  10176. prefixVertex = [
  10177. '#define attribute in',
  10178. '#define varying out',
  10179. '#define texture2D texture'
  10180. ].join( '\n' ) + '\n' + prefixVertex;
  10181. prefixFragment = [
  10182. '#define varying in',
  10183. ( parameters.glslVersion === GLSL3 ) ? '' : 'out highp vec4 pc_fragColor;',
  10184. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  10185. '#define gl_FragDepthEXT gl_FragDepth',
  10186. '#define texture2D texture',
  10187. '#define textureCube texture',
  10188. '#define texture2DProj textureProj',
  10189. '#define texture2DLodEXT textureLod',
  10190. '#define texture2DProjLodEXT textureProjLod',
  10191. '#define textureCubeLodEXT textureLod',
  10192. '#define texture2DGradEXT textureGrad',
  10193. '#define texture2DProjGradEXT textureProjGrad',
  10194. '#define textureCubeGradEXT textureGrad'
  10195. ].join( '\n' ) + '\n' + prefixFragment;
  10196. }
  10197. const vertexGlsl = versionString + prefixVertex + vertexShader;
  10198. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  10199. // console.log( '*VERTEX*', vertexGlsl );
  10200. // console.log( '*FRAGMENT*', fragmentGlsl );
  10201. const glVertexShader = WebGLShader( gl, 35633, vertexGlsl );
  10202. const glFragmentShader = WebGLShader( gl, 35632, fragmentGlsl );
  10203. gl.attachShader( program, glVertexShader );
  10204. gl.attachShader( program, glFragmentShader );
  10205. // Force a particular attribute to index 0.
  10206. if ( parameters.index0AttributeName !== undefined ) {
  10207. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  10208. } else if ( parameters.morphTargets === true ) {
  10209. // programs with morphTargets displace position out of attribute 0
  10210. gl.bindAttribLocation( program, 0, 'position' );
  10211. }
  10212. gl.linkProgram( program );
  10213. // check for link errors
  10214. if ( renderer.debug.checkShaderErrors ) {
  10215. const programLog = gl.getProgramInfoLog( program ).trim();
  10216. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  10217. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  10218. let runnable = true;
  10219. let haveDiagnostics = true;
  10220. if ( gl.getProgramParameter( program, 35714 ) === false ) {
  10221. runnable = false;
  10222. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  10223. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  10224. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter( program, 35715 ), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors );
  10225. } else if ( programLog !== '' ) {
  10226. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  10227. } else if ( vertexLog === '' || fragmentLog === '' ) {
  10228. haveDiagnostics = false;
  10229. }
  10230. if ( haveDiagnostics ) {
  10231. this.diagnostics = {
  10232. runnable: runnable,
  10233. programLog: programLog,
  10234. vertexShader: {
  10235. log: vertexLog,
  10236. prefix: prefixVertex
  10237. },
  10238. fragmentShader: {
  10239. log: fragmentLog,
  10240. prefix: prefixFragment
  10241. }
  10242. };
  10243. }
  10244. }
  10245. // Clean up
  10246. // Crashes in iOS9 and iOS10. #18402
  10247. // gl.detachShader( program, glVertexShader );
  10248. // gl.detachShader( program, glFragmentShader );
  10249. gl.deleteShader( glVertexShader );
  10250. gl.deleteShader( glFragmentShader );
  10251. // set up caching for uniform locations
  10252. let cachedUniforms;
  10253. this.getUniforms = function () {
  10254. if ( cachedUniforms === undefined ) {
  10255. cachedUniforms = new WebGLUniforms( gl, program );
  10256. }
  10257. return cachedUniforms;
  10258. };
  10259. // set up caching for attribute locations
  10260. let cachedAttributes;
  10261. this.getAttributes = function () {
  10262. if ( cachedAttributes === undefined ) {
  10263. cachedAttributes = fetchAttributeLocations( gl, program );
  10264. }
  10265. return cachedAttributes;
  10266. };
  10267. // free resource
  10268. this.destroy = function () {
  10269. bindingStates.releaseStatesOfProgram( this );
  10270. gl.deleteProgram( program );
  10271. this.program = undefined;
  10272. };
  10273. //
  10274. this.name = parameters.shaderName;
  10275. this.id = programIdCount ++;
  10276. this.cacheKey = cacheKey;
  10277. this.usedTimes = 1;
  10278. this.program = program;
  10279. this.vertexShader = glVertexShader;
  10280. this.fragmentShader = glFragmentShader;
  10281. return this;
  10282. }
  10283. function WebGLPrograms( renderer, cubemaps, extensions, capabilities, bindingStates, clipping ) {
  10284. const programs = [];
  10285. const isWebGL2 = capabilities.isWebGL2;
  10286. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  10287. const floatVertexTextures = capabilities.floatVertexTextures;
  10288. const maxVertexUniforms = capabilities.maxVertexUniforms;
  10289. const vertexTextures = capabilities.vertexTextures;
  10290. let precision = capabilities.precision;
  10291. const shaderIDs = {
  10292. MeshDepthMaterial: 'depth',
  10293. MeshDistanceMaterial: 'distanceRGBA',
  10294. MeshNormalMaterial: 'normal',
  10295. MeshBasicMaterial: 'basic',
  10296. MeshLambertMaterial: 'lambert',
  10297. MeshPhongMaterial: 'phong',
  10298. MeshToonMaterial: 'toon',
  10299. MeshStandardMaterial: 'physical',
  10300. MeshPhysicalMaterial: 'physical',
  10301. MeshMatcapMaterial: 'matcap',
  10302. LineBasicMaterial: 'basic',
  10303. LineDashedMaterial: 'dashed',
  10304. PointsMaterial: 'points',
  10305. ShadowMaterial: 'shadow',
  10306. SpriteMaterial: 'sprite'
  10307. };
  10308. const parameterNames = [
  10309. 'precision', 'isWebGL2', 'supportsVertexTextures', 'outputEncoding', 'instancing', 'instancingColor',
  10310. 'map', 'mapEncoding', 'matcap', 'matcapEncoding', 'envMap', 'envMapMode', 'envMapEncoding', 'envMapCubeUV',
  10311. 'lightMap', 'lightMapEncoding', 'aoMap', 'emissiveMap', 'emissiveMapEncoding', 'bumpMap', 'normalMap', 'objectSpaceNormalMap', 'tangentSpaceNormalMap', 'clearcoatMap', 'clearcoatRoughnessMap', 'clearcoatNormalMap', 'displacementMap', 'specularMap',
  10312. 'roughnessMap', 'metalnessMap', 'gradientMap',
  10313. 'alphaMap', 'combine', 'vertexColors', 'vertexAlphas', 'vertexTangents', 'vertexUvs', 'uvsVertexOnly', 'fog', 'useFog', 'fogExp2',
  10314. 'flatShading', 'sizeAttenuation', 'logarithmicDepthBuffer', 'skinning',
  10315. 'maxBones', 'useVertexTexture', 'morphTargets', 'morphNormals', 'premultipliedAlpha',
  10316. 'numDirLights', 'numPointLights', 'numSpotLights', 'numHemiLights', 'numRectAreaLights',
  10317. 'numDirLightShadows', 'numPointLightShadows', 'numSpotLightShadows',
  10318. 'shadowMapEnabled', 'shadowMapType', 'toneMapping', 'physicallyCorrectLights',
  10319. 'alphaTest', 'doubleSided', 'flipSided', 'numClippingPlanes', 'numClipIntersection', 'depthPacking', 'dithering',
  10320. 'sheen', 'transmission', 'transmissionMap', 'thicknessMap'
  10321. ];
  10322. function getMaxBones( object ) {
  10323. const skeleton = object.skeleton;
  10324. const bones = skeleton.bones;
  10325. if ( floatVertexTextures ) {
  10326. return 1024;
  10327. } else {
  10328. // default for when object is not specified
  10329. // ( for example when prebuilding shader to be used with multiple objects )
  10330. //
  10331. // - leave some extra space for other uniforms
  10332. // - limit here is ANGLE's 254 max uniform vectors
  10333. // (up to 54 should be safe)
  10334. const nVertexUniforms = maxVertexUniforms;
  10335. const nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  10336. const maxBones = Math.min( nVertexMatrices, bones.length );
  10337. if ( maxBones < bones.length ) {
  10338. console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' );
  10339. return 0;
  10340. }
  10341. return maxBones;
  10342. }
  10343. }
  10344. function getTextureEncodingFromMap( map ) {
  10345. let encoding;
  10346. if ( map && map.isTexture ) {
  10347. encoding = map.encoding;
  10348. } else if ( map && map.isWebGLRenderTarget ) {
  10349. console.warn( 'THREE.WebGLPrograms.getTextureEncodingFromMap: don\'t use render targets as textures. Use their .texture property instead.' );
  10350. encoding = map.texture.encoding;
  10351. } else {
  10352. encoding = LinearEncoding;
  10353. }
  10354. return encoding;
  10355. }
  10356. function getParameters( material, lights, shadows, scene, object ) {
  10357. const fog = scene.fog;
  10358. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  10359. const envMap = cubemaps.get( material.envMap || environment );
  10360. const shaderID = shaderIDs[ material.type ];
  10361. // heuristics to create shader parameters according to lights in the scene
  10362. // (not to blow over maxLights budget)
  10363. const maxBones = object.isSkinnedMesh ? getMaxBones( object ) : 0;
  10364. if ( material.precision !== null ) {
  10365. precision = capabilities.getMaxPrecision( material.precision );
  10366. if ( precision !== material.precision ) {
  10367. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  10368. }
  10369. }
  10370. let vertexShader, fragmentShader;
  10371. if ( shaderID ) {
  10372. const shader = ShaderLib[ shaderID ];
  10373. vertexShader = shader.vertexShader;
  10374. fragmentShader = shader.fragmentShader;
  10375. } else {
  10376. vertexShader = material.vertexShader;
  10377. fragmentShader = material.fragmentShader;
  10378. }
  10379. const currentRenderTarget = renderer.getRenderTarget();
  10380. const parameters = {
  10381. isWebGL2: isWebGL2,
  10382. shaderID: shaderID,
  10383. shaderName: material.type,
  10384. vertexShader: vertexShader,
  10385. fragmentShader: fragmentShader,
  10386. defines: material.defines,
  10387. isRawShaderMaterial: material.isRawShaderMaterial === true,
  10388. glslVersion: material.glslVersion,
  10389. precision: precision,
  10390. instancing: object.isInstancedMesh === true,
  10391. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  10392. supportsVertexTextures: vertexTextures,
  10393. outputEncoding: ( currentRenderTarget !== null ) ? getTextureEncodingFromMap( currentRenderTarget.texture ) : renderer.outputEncoding,
  10394. map: !! material.map,
  10395. mapEncoding: getTextureEncodingFromMap( material.map ),
  10396. matcap: !! material.matcap,
  10397. matcapEncoding: getTextureEncodingFromMap( material.matcap ),
  10398. envMap: !! envMap,
  10399. envMapMode: envMap && envMap.mapping,
  10400. envMapEncoding: getTextureEncodingFromMap( envMap ),
  10401. envMapCubeUV: ( !! envMap ) && ( ( envMap.mapping === CubeUVReflectionMapping ) || ( envMap.mapping === CubeUVRefractionMapping ) ),
  10402. lightMap: !! material.lightMap,
  10403. lightMapEncoding: getTextureEncodingFromMap( material.lightMap ),
  10404. aoMap: !! material.aoMap,
  10405. emissiveMap: !! material.emissiveMap,
  10406. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap ),
  10407. bumpMap: !! material.bumpMap,
  10408. normalMap: !! material.normalMap,
  10409. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  10410. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  10411. clearcoatMap: !! material.clearcoatMap,
  10412. clearcoatRoughnessMap: !! material.clearcoatRoughnessMap,
  10413. clearcoatNormalMap: !! material.clearcoatNormalMap,
  10414. displacementMap: !! material.displacementMap,
  10415. roughnessMap: !! material.roughnessMap,
  10416. metalnessMap: !! material.metalnessMap,
  10417. specularMap: !! material.specularMap,
  10418. alphaMap: !! material.alphaMap,
  10419. gradientMap: !! material.gradientMap,
  10420. sheen: !! material.sheen,
  10421. transmission: !! material.transmission,
  10422. transmissionMap: !! material.transmissionMap,
  10423. thicknessMap: !! material.thicknessMap,
  10424. combine: material.combine,
  10425. vertexTangents: ( material.normalMap && material.vertexTangents ),
  10426. vertexColors: material.vertexColors,
  10427. vertexAlphas: material.vertexColors === true && object.geometry && object.geometry.attributes.color && object.geometry.attributes.color.itemSize === 4,
  10428. vertexUvs: !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatMap || !! material.clearcoatRoughnessMap || !! material.clearcoatNormalMap || !! material.displacementMap || !! material.transmissionMap || !! material.thicknessMap,
  10429. uvsVertexOnly: ! ( !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap || !! material.transmission || !! material.transmissionMap || !! material.thicknessMap ) && !! material.displacementMap,
  10430. fog: !! fog,
  10431. useFog: material.fog,
  10432. fogExp2: ( fog && fog.isFogExp2 ),
  10433. flatShading: !! material.flatShading,
  10434. sizeAttenuation: material.sizeAttenuation,
  10435. logarithmicDepthBuffer: logarithmicDepthBuffer,
  10436. skinning: object.isSkinnedMesh === true && maxBones > 0,
  10437. maxBones: maxBones,
  10438. useVertexTexture: floatVertexTextures,
  10439. morphTargets: material.morphTargets,
  10440. morphNormals: material.morphNormals,
  10441. numDirLights: lights.directional.length,
  10442. numPointLights: lights.point.length,
  10443. numSpotLights: lights.spot.length,
  10444. numRectAreaLights: lights.rectArea.length,
  10445. numHemiLights: lights.hemi.length,
  10446. numDirLightShadows: lights.directionalShadowMap.length,
  10447. numPointLightShadows: lights.pointShadowMap.length,
  10448. numSpotLightShadows: lights.spotShadowMap.length,
  10449. numClippingPlanes: clipping.numPlanes,
  10450. numClipIntersection: clipping.numIntersection,
  10451. dithering: material.dithering,
  10452. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  10453. shadowMapType: renderer.shadowMap.type,
  10454. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  10455. physicallyCorrectLights: renderer.physicallyCorrectLights,
  10456. premultipliedAlpha: material.premultipliedAlpha,
  10457. alphaTest: material.alphaTest,
  10458. doubleSided: material.side === DoubleSide,
  10459. flipSided: material.side === BackSide,
  10460. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false,
  10461. index0AttributeName: material.index0AttributeName,
  10462. extensionDerivatives: material.extensions && material.extensions.derivatives,
  10463. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  10464. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  10465. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  10466. rendererExtensionFragDepth: isWebGL2 || extensions.has( 'EXT_frag_depth' ),
  10467. rendererExtensionDrawBuffers: isWebGL2 || extensions.has( 'WEBGL_draw_buffers' ),
  10468. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has( 'EXT_shader_texture_lod' ),
  10469. customProgramCacheKey: material.customProgramCacheKey()
  10470. };
  10471. return parameters;
  10472. }
  10473. function getProgramCacheKey( parameters ) {
  10474. const array = [];
  10475. if ( parameters.shaderID ) {
  10476. array.push( parameters.shaderID );
  10477. } else {
  10478. array.push( parameters.fragmentShader );
  10479. array.push( parameters.vertexShader );
  10480. }
  10481. if ( parameters.defines !== undefined ) {
  10482. for ( const name in parameters.defines ) {
  10483. array.push( name );
  10484. array.push( parameters.defines[ name ] );
  10485. }
  10486. }
  10487. if ( parameters.isRawShaderMaterial === false ) {
  10488. for ( let i = 0; i < parameterNames.length; i ++ ) {
  10489. array.push( parameters[ parameterNames[ i ] ] );
  10490. }
  10491. array.push( renderer.outputEncoding );
  10492. array.push( renderer.gammaFactor );
  10493. }
  10494. array.push( parameters.customProgramCacheKey );
  10495. return array.join();
  10496. }
  10497. function getUniforms( material ) {
  10498. const shaderID = shaderIDs[ material.type ];
  10499. let uniforms;
  10500. if ( shaderID ) {
  10501. const shader = ShaderLib[ shaderID ];
  10502. uniforms = UniformsUtils.clone( shader.uniforms );
  10503. } else {
  10504. uniforms = material.uniforms;
  10505. }
  10506. return uniforms;
  10507. }
  10508. function acquireProgram( parameters, cacheKey ) {
  10509. let program;
  10510. // Check if code has been already compiled
  10511. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  10512. const preexistingProgram = programs[ p ];
  10513. if ( preexistingProgram.cacheKey === cacheKey ) {
  10514. program = preexistingProgram;
  10515. ++ program.usedTimes;
  10516. break;
  10517. }
  10518. }
  10519. if ( program === undefined ) {
  10520. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  10521. programs.push( program );
  10522. }
  10523. return program;
  10524. }
  10525. function releaseProgram( program ) {
  10526. if ( -- program.usedTimes === 0 ) {
  10527. // Remove from unordered set
  10528. const i = programs.indexOf( program );
  10529. programs[ i ] = programs[ programs.length - 1 ];
  10530. programs.pop();
  10531. // Free WebGL resources
  10532. program.destroy();
  10533. }
  10534. }
  10535. return {
  10536. getParameters: getParameters,
  10537. getProgramCacheKey: getProgramCacheKey,
  10538. getUniforms: getUniforms,
  10539. acquireProgram: acquireProgram,
  10540. releaseProgram: releaseProgram,
  10541. // Exposed for resource monitoring & error feedback via renderer.info:
  10542. programs: programs
  10543. };
  10544. }
  10545. function WebGLProperties() {
  10546. let properties = new WeakMap();
  10547. function get( object ) {
  10548. let map = properties.get( object );
  10549. if ( map === undefined ) {
  10550. map = {};
  10551. properties.set( object, map );
  10552. }
  10553. return map;
  10554. }
  10555. function remove( object ) {
  10556. properties.delete( object );
  10557. }
  10558. function update( object, key, value ) {
  10559. properties.get( object )[ key ] = value;
  10560. }
  10561. function dispose() {
  10562. properties = new WeakMap();
  10563. }
  10564. return {
  10565. get: get,
  10566. remove: remove,
  10567. update: update,
  10568. dispose: dispose
  10569. };
  10570. }
  10571. function painterSortStable( a, b ) {
  10572. if ( a.groupOrder !== b.groupOrder ) {
  10573. return a.groupOrder - b.groupOrder;
  10574. } else if ( a.renderOrder !== b.renderOrder ) {
  10575. return a.renderOrder - b.renderOrder;
  10576. } else if ( a.program !== b.program ) {
  10577. return a.program.id - b.program.id;
  10578. } else if ( a.material.id !== b.material.id ) {
  10579. return a.material.id - b.material.id;
  10580. } else if ( a.z !== b.z ) {
  10581. return a.z - b.z;
  10582. } else {
  10583. return a.id - b.id;
  10584. }
  10585. }
  10586. function reversePainterSortStable( a, b ) {
  10587. if ( a.groupOrder !== b.groupOrder ) {
  10588. return a.groupOrder - b.groupOrder;
  10589. } else if ( a.renderOrder !== b.renderOrder ) {
  10590. return a.renderOrder - b.renderOrder;
  10591. } else if ( a.z !== b.z ) {
  10592. return b.z - a.z;
  10593. } else {
  10594. return a.id - b.id;
  10595. }
  10596. }
  10597. function WebGLRenderList( properties ) {
  10598. const renderItems = [];
  10599. let renderItemsIndex = 0;
  10600. const opaque = [];
  10601. const transmissive = [];
  10602. const transparent = [];
  10603. const defaultProgram = { id: - 1 };
  10604. function init() {
  10605. renderItemsIndex = 0;
  10606. opaque.length = 0;
  10607. transmissive.length = 0;
  10608. transparent.length = 0;
  10609. }
  10610. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  10611. let renderItem = renderItems[ renderItemsIndex ];
  10612. const materialProperties = properties.get( material );
  10613. if ( renderItem === undefined ) {
  10614. renderItem = {
  10615. id: object.id,
  10616. object: object,
  10617. geometry: geometry,
  10618. material: material,
  10619. program: materialProperties.program || defaultProgram,
  10620. groupOrder: groupOrder,
  10621. renderOrder: object.renderOrder,
  10622. z: z,
  10623. group: group
  10624. };
  10625. renderItems[ renderItemsIndex ] = renderItem;
  10626. } else {
  10627. renderItem.id = object.id;
  10628. renderItem.object = object;
  10629. renderItem.geometry = geometry;
  10630. renderItem.material = material;
  10631. renderItem.program = materialProperties.program || defaultProgram;
  10632. renderItem.groupOrder = groupOrder;
  10633. renderItem.renderOrder = object.renderOrder;
  10634. renderItem.z = z;
  10635. renderItem.group = group;
  10636. }
  10637. renderItemsIndex ++;
  10638. return renderItem;
  10639. }
  10640. function push( object, geometry, material, groupOrder, z, group ) {
  10641. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  10642. if ( material.transmission > 0.0 ) {
  10643. transmissive.push( renderItem );
  10644. } else if ( material.transparent === true ) {
  10645. transparent.push( renderItem );
  10646. } else {
  10647. opaque.push( renderItem );
  10648. }
  10649. }
  10650. function unshift( object, geometry, material, groupOrder, z, group ) {
  10651. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  10652. if ( material.transmission > 0.0 ) {
  10653. transmissive.unshift( renderItem );
  10654. } else if ( material.transparent === true ) {
  10655. transparent.unshift( renderItem );
  10656. } else {
  10657. opaque.unshift( renderItem );
  10658. }
  10659. }
  10660. function sort( customOpaqueSort, customTransparentSort ) {
  10661. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  10662. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  10663. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  10664. }
  10665. function finish() {
  10666. // Clear references from inactive renderItems in the list
  10667. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  10668. const renderItem = renderItems[ i ];
  10669. if ( renderItem.id === null ) break;
  10670. renderItem.id = null;
  10671. renderItem.object = null;
  10672. renderItem.geometry = null;
  10673. renderItem.material = null;
  10674. renderItem.program = null;
  10675. renderItem.group = null;
  10676. }
  10677. }
  10678. return {
  10679. opaque: opaque,
  10680. transmissive: transmissive,
  10681. transparent: transparent,
  10682. init: init,
  10683. push: push,
  10684. unshift: unshift,
  10685. finish: finish,
  10686. sort: sort
  10687. };
  10688. }
  10689. function WebGLRenderLists( properties ) {
  10690. let lists = new WeakMap();
  10691. function get( scene, renderCallDepth ) {
  10692. let list;
  10693. if ( lists.has( scene ) === false ) {
  10694. list = new WebGLRenderList( properties );
  10695. lists.set( scene, [ list ] );
  10696. } else {
  10697. if ( renderCallDepth >= lists.get( scene ).length ) {
  10698. list = new WebGLRenderList( properties );
  10699. lists.get( scene ).push( list );
  10700. } else {
  10701. list = lists.get( scene )[ renderCallDepth ];
  10702. }
  10703. }
  10704. return list;
  10705. }
  10706. function dispose() {
  10707. lists = new WeakMap();
  10708. }
  10709. return {
  10710. get: get,
  10711. dispose: dispose
  10712. };
  10713. }
  10714. function UniformsCache() {
  10715. const lights = {};
  10716. return {
  10717. get: function ( light ) {
  10718. if ( lights[ light.id ] !== undefined ) {
  10719. return lights[ light.id ];
  10720. }
  10721. let uniforms;
  10722. switch ( light.type ) {
  10723. case 'DirectionalLight':
  10724. uniforms = {
  10725. direction: new Vector3(),
  10726. color: new Color()
  10727. };
  10728. break;
  10729. case 'SpotLight':
  10730. uniforms = {
  10731. position: new Vector3(),
  10732. direction: new Vector3(),
  10733. color: new Color(),
  10734. distance: 0,
  10735. coneCos: 0,
  10736. penumbraCos: 0,
  10737. decay: 0
  10738. };
  10739. break;
  10740. case 'PointLight':
  10741. uniforms = {
  10742. position: new Vector3(),
  10743. color: new Color(),
  10744. distance: 0,
  10745. decay: 0
  10746. };
  10747. break;
  10748. case 'HemisphereLight':
  10749. uniforms = {
  10750. direction: new Vector3(),
  10751. skyColor: new Color(),
  10752. groundColor: new Color()
  10753. };
  10754. break;
  10755. case 'RectAreaLight':
  10756. uniforms = {
  10757. color: new Color(),
  10758. position: new Vector3(),
  10759. halfWidth: new Vector3(),
  10760. halfHeight: new Vector3()
  10761. };
  10762. break;
  10763. }
  10764. lights[ light.id ] = uniforms;
  10765. return uniforms;
  10766. }
  10767. };
  10768. }
  10769. function ShadowUniformsCache() {
  10770. const lights = {};
  10771. return {
  10772. get: function ( light ) {
  10773. if ( lights[ light.id ] !== undefined ) {
  10774. return lights[ light.id ];
  10775. }
  10776. let uniforms;
  10777. switch ( light.type ) {
  10778. case 'DirectionalLight':
  10779. uniforms = {
  10780. shadowBias: 0,
  10781. shadowNormalBias: 0,
  10782. shadowRadius: 1,
  10783. shadowMapSize: new Vector2()
  10784. };
  10785. break;
  10786. case 'SpotLight':
  10787. uniforms = {
  10788. shadowBias: 0,
  10789. shadowNormalBias: 0,
  10790. shadowRadius: 1,
  10791. shadowMapSize: new Vector2()
  10792. };
  10793. break;
  10794. case 'PointLight':
  10795. uniforms = {
  10796. shadowBias: 0,
  10797. shadowNormalBias: 0,
  10798. shadowRadius: 1,
  10799. shadowMapSize: new Vector2(),
  10800. shadowCameraNear: 1,
  10801. shadowCameraFar: 1000
  10802. };
  10803. break;
  10804. // TODO (abelnation): set RectAreaLight shadow uniforms
  10805. }
  10806. lights[ light.id ] = uniforms;
  10807. return uniforms;
  10808. }
  10809. };
  10810. }
  10811. let nextVersion = 0;
  10812. function shadowCastingLightsFirst( lightA, lightB ) {
  10813. return ( lightB.castShadow ? 1 : 0 ) - ( lightA.castShadow ? 1 : 0 );
  10814. }
  10815. function WebGLLights( extensions, capabilities ) {
  10816. const cache = new UniformsCache();
  10817. const shadowCache = ShadowUniformsCache();
  10818. const state = {
  10819. version: 0,
  10820. hash: {
  10821. directionalLength: - 1,
  10822. pointLength: - 1,
  10823. spotLength: - 1,
  10824. rectAreaLength: - 1,
  10825. hemiLength: - 1,
  10826. numDirectionalShadows: - 1,
  10827. numPointShadows: - 1,
  10828. numSpotShadows: - 1
  10829. },
  10830. ambient: [ 0, 0, 0 ],
  10831. probe: [],
  10832. directional: [],
  10833. directionalShadow: [],
  10834. directionalShadowMap: [],
  10835. directionalShadowMatrix: [],
  10836. spot: [],
  10837. spotShadow: [],
  10838. spotShadowMap: [],
  10839. spotShadowMatrix: [],
  10840. rectArea: [],
  10841. rectAreaLTC1: null,
  10842. rectAreaLTC2: null,
  10843. point: [],
  10844. pointShadow: [],
  10845. pointShadowMap: [],
  10846. pointShadowMatrix: [],
  10847. hemi: []
  10848. };
  10849. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  10850. const vector3 = new Vector3();
  10851. const matrix4 = new Matrix4();
  10852. const matrix42 = new Matrix4();
  10853. function setup( lights ) {
  10854. let r = 0, g = 0, b = 0;
  10855. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  10856. let directionalLength = 0;
  10857. let pointLength = 0;
  10858. let spotLength = 0;
  10859. let rectAreaLength = 0;
  10860. let hemiLength = 0;
  10861. let numDirectionalShadows = 0;
  10862. let numPointShadows = 0;
  10863. let numSpotShadows = 0;
  10864. lights.sort( shadowCastingLightsFirst );
  10865. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  10866. const light = lights[ i ];
  10867. const color = light.color;
  10868. const intensity = light.intensity;
  10869. const distance = light.distance;
  10870. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  10871. if ( light.isAmbientLight ) {
  10872. r += color.r * intensity;
  10873. g += color.g * intensity;
  10874. b += color.b * intensity;
  10875. } else if ( light.isLightProbe ) {
  10876. for ( let j = 0; j < 9; j ++ ) {
  10877. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  10878. }
  10879. } else if ( light.isDirectionalLight ) {
  10880. const uniforms = cache.get( light );
  10881. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  10882. if ( light.castShadow ) {
  10883. const shadow = light.shadow;
  10884. const shadowUniforms = shadowCache.get( light );
  10885. shadowUniforms.shadowBias = shadow.bias;
  10886. shadowUniforms.shadowNormalBias = shadow.normalBias;
  10887. shadowUniforms.shadowRadius = shadow.radius;
  10888. shadowUniforms.shadowMapSize = shadow.mapSize;
  10889. state.directionalShadow[ directionalLength ] = shadowUniforms;
  10890. state.directionalShadowMap[ directionalLength ] = shadowMap;
  10891. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  10892. numDirectionalShadows ++;
  10893. }
  10894. state.directional[ directionalLength ] = uniforms;
  10895. directionalLength ++;
  10896. } else if ( light.isSpotLight ) {
  10897. const uniforms = cache.get( light );
  10898. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  10899. uniforms.color.copy( color ).multiplyScalar( intensity );
  10900. uniforms.distance = distance;
  10901. uniforms.coneCos = Math.cos( light.angle );
  10902. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  10903. uniforms.decay = light.decay;
  10904. if ( light.castShadow ) {
  10905. const shadow = light.shadow;
  10906. const shadowUniforms = shadowCache.get( light );
  10907. shadowUniforms.shadowBias = shadow.bias;
  10908. shadowUniforms.shadowNormalBias = shadow.normalBias;
  10909. shadowUniforms.shadowRadius = shadow.radius;
  10910. shadowUniforms.shadowMapSize = shadow.mapSize;
  10911. state.spotShadow[ spotLength ] = shadowUniforms;
  10912. state.spotShadowMap[ spotLength ] = shadowMap;
  10913. state.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  10914. numSpotShadows ++;
  10915. }
  10916. state.spot[ spotLength ] = uniforms;
  10917. spotLength ++;
  10918. } else if ( light.isRectAreaLight ) {
  10919. const uniforms = cache.get( light );
  10920. // (a) intensity is the total visible light emitted
  10921. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  10922. // (b) intensity is the brightness of the light
  10923. uniforms.color.copy( color ).multiplyScalar( intensity );
  10924. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  10925. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  10926. state.rectArea[ rectAreaLength ] = uniforms;
  10927. rectAreaLength ++;
  10928. } else if ( light.isPointLight ) {
  10929. const uniforms = cache.get( light );
  10930. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  10931. uniforms.distance = light.distance;
  10932. uniforms.decay = light.decay;
  10933. if ( light.castShadow ) {
  10934. const shadow = light.shadow;
  10935. const shadowUniforms = shadowCache.get( light );
  10936. shadowUniforms.shadowBias = shadow.bias;
  10937. shadowUniforms.shadowNormalBias = shadow.normalBias;
  10938. shadowUniforms.shadowRadius = shadow.radius;
  10939. shadowUniforms.shadowMapSize = shadow.mapSize;
  10940. shadowUniforms.shadowCameraNear = shadow.camera.near;
  10941. shadowUniforms.shadowCameraFar = shadow.camera.far;
  10942. state.pointShadow[ pointLength ] = shadowUniforms;
  10943. state.pointShadowMap[ pointLength ] = shadowMap;
  10944. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  10945. numPointShadows ++;
  10946. }
  10947. state.point[ pointLength ] = uniforms;
  10948. pointLength ++;
  10949. } else if ( light.isHemisphereLight ) {
  10950. const uniforms = cache.get( light );
  10951. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  10952. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  10953. state.hemi[ hemiLength ] = uniforms;
  10954. hemiLength ++;
  10955. }
  10956. }
  10957. if ( rectAreaLength > 0 ) {
  10958. if ( capabilities.isWebGL2 ) {
  10959. // WebGL 2
  10960. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  10961. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  10962. } else {
  10963. // WebGL 1
  10964. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  10965. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  10966. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  10967. } else if ( extensions.has( 'OES_texture_half_float_linear' ) === true ) {
  10968. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  10969. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  10970. } else {
  10971. console.error( 'THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.' );
  10972. }
  10973. }
  10974. }
  10975. state.ambient[ 0 ] = r;
  10976. state.ambient[ 1 ] = g;
  10977. state.ambient[ 2 ] = b;
  10978. const hash = state.hash;
  10979. if ( hash.directionalLength !== directionalLength ||
  10980. hash.pointLength !== pointLength ||
  10981. hash.spotLength !== spotLength ||
  10982. hash.rectAreaLength !== rectAreaLength ||
  10983. hash.hemiLength !== hemiLength ||
  10984. hash.numDirectionalShadows !== numDirectionalShadows ||
  10985. hash.numPointShadows !== numPointShadows ||
  10986. hash.numSpotShadows !== numSpotShadows ) {
  10987. state.directional.length = directionalLength;
  10988. state.spot.length = spotLength;
  10989. state.rectArea.length = rectAreaLength;
  10990. state.point.length = pointLength;
  10991. state.hemi.length = hemiLength;
  10992. state.directionalShadow.length = numDirectionalShadows;
  10993. state.directionalShadowMap.length = numDirectionalShadows;
  10994. state.pointShadow.length = numPointShadows;
  10995. state.pointShadowMap.length = numPointShadows;
  10996. state.spotShadow.length = numSpotShadows;
  10997. state.spotShadowMap.length = numSpotShadows;
  10998. state.directionalShadowMatrix.length = numDirectionalShadows;
  10999. state.pointShadowMatrix.length = numPointShadows;
  11000. state.spotShadowMatrix.length = numSpotShadows;
  11001. hash.directionalLength = directionalLength;
  11002. hash.pointLength = pointLength;
  11003. hash.spotLength = spotLength;
  11004. hash.rectAreaLength = rectAreaLength;
  11005. hash.hemiLength = hemiLength;
  11006. hash.numDirectionalShadows = numDirectionalShadows;
  11007. hash.numPointShadows = numPointShadows;
  11008. hash.numSpotShadows = numSpotShadows;
  11009. state.version = nextVersion ++;
  11010. }
  11011. }
  11012. function setupView( lights, camera ) {
  11013. let directionalLength = 0;
  11014. let pointLength = 0;
  11015. let spotLength = 0;
  11016. let rectAreaLength = 0;
  11017. let hemiLength = 0;
  11018. const viewMatrix = camera.matrixWorldInverse;
  11019. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  11020. const light = lights[ i ];
  11021. if ( light.isDirectionalLight ) {
  11022. const uniforms = state.directional[ directionalLength ];
  11023. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  11024. vector3.setFromMatrixPosition( light.target.matrixWorld );
  11025. uniforms.direction.sub( vector3 );
  11026. uniforms.direction.transformDirection( viewMatrix );
  11027. directionalLength ++;
  11028. } else if ( light.isSpotLight ) {
  11029. const uniforms = state.spot[ spotLength ];
  11030. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  11031. uniforms.position.applyMatrix4( viewMatrix );
  11032. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  11033. vector3.setFromMatrixPosition( light.target.matrixWorld );
  11034. uniforms.direction.sub( vector3 );
  11035. uniforms.direction.transformDirection( viewMatrix );
  11036. spotLength ++;
  11037. } else if ( light.isRectAreaLight ) {
  11038. const uniforms = state.rectArea[ rectAreaLength ];
  11039. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  11040. uniforms.position.applyMatrix4( viewMatrix );
  11041. // extract local rotation of light to derive width/height half vectors
  11042. matrix42.identity();
  11043. matrix4.copy( light.matrixWorld );
  11044. matrix4.premultiply( viewMatrix );
  11045. matrix42.extractRotation( matrix4 );
  11046. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  11047. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  11048. uniforms.halfWidth.applyMatrix4( matrix42 );
  11049. uniforms.halfHeight.applyMatrix4( matrix42 );
  11050. rectAreaLength ++;
  11051. } else if ( light.isPointLight ) {
  11052. const uniforms = state.point[ pointLength ];
  11053. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  11054. uniforms.position.applyMatrix4( viewMatrix );
  11055. pointLength ++;
  11056. } else if ( light.isHemisphereLight ) {
  11057. const uniforms = state.hemi[ hemiLength ];
  11058. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  11059. uniforms.direction.transformDirection( viewMatrix );
  11060. uniforms.direction.normalize();
  11061. hemiLength ++;
  11062. }
  11063. }
  11064. }
  11065. return {
  11066. setup: setup,
  11067. setupView: setupView,
  11068. state: state
  11069. };
  11070. }
  11071. function WebGLRenderState( extensions, capabilities ) {
  11072. const lights = new WebGLLights( extensions, capabilities );
  11073. const lightsArray = [];
  11074. const shadowsArray = [];
  11075. function init() {
  11076. lightsArray.length = 0;
  11077. shadowsArray.length = 0;
  11078. }
  11079. function pushLight( light ) {
  11080. lightsArray.push( light );
  11081. }
  11082. function pushShadow( shadowLight ) {
  11083. shadowsArray.push( shadowLight );
  11084. }
  11085. function setupLights() {
  11086. lights.setup( lightsArray );
  11087. }
  11088. function setupLightsView( camera ) {
  11089. lights.setupView( lightsArray, camera );
  11090. }
  11091. const state = {
  11092. lightsArray: lightsArray,
  11093. shadowsArray: shadowsArray,
  11094. lights: lights
  11095. };
  11096. return {
  11097. init: init,
  11098. state: state,
  11099. setupLights: setupLights,
  11100. setupLightsView: setupLightsView,
  11101. pushLight: pushLight,
  11102. pushShadow: pushShadow
  11103. };
  11104. }
  11105. function WebGLRenderStates( extensions, capabilities ) {
  11106. let renderStates = new WeakMap();
  11107. function get( scene, renderCallDepth = 0 ) {
  11108. let renderState;
  11109. if ( renderStates.has( scene ) === false ) {
  11110. renderState = new WebGLRenderState( extensions, capabilities );
  11111. renderStates.set( scene, [ renderState ] );
  11112. } else {
  11113. if ( renderCallDepth >= renderStates.get( scene ).length ) {
  11114. renderState = new WebGLRenderState( extensions, capabilities );
  11115. renderStates.get( scene ).push( renderState );
  11116. } else {
  11117. renderState = renderStates.get( scene )[ renderCallDepth ];
  11118. }
  11119. }
  11120. return renderState;
  11121. }
  11122. function dispose() {
  11123. renderStates = new WeakMap();
  11124. }
  11125. return {
  11126. get: get,
  11127. dispose: dispose
  11128. };
  11129. }
  11130. /**
  11131. * parameters = {
  11132. *
  11133. * opacity: <float>,
  11134. *
  11135. * map: new THREE.Texture( <Image> ),
  11136. *
  11137. * alphaMap: new THREE.Texture( <Image> ),
  11138. *
  11139. * displacementMap: new THREE.Texture( <Image> ),
  11140. * displacementScale: <float>,
  11141. * displacementBias: <float>,
  11142. *
  11143. * wireframe: <boolean>,
  11144. * wireframeLinewidth: <float>
  11145. * }
  11146. */
  11147. class MeshDepthMaterial extends Material {
  11148. constructor( parameters ) {
  11149. super();
  11150. this.type = 'MeshDepthMaterial';
  11151. this.depthPacking = BasicDepthPacking;
  11152. this.morphTargets = false;
  11153. this.map = null;
  11154. this.alphaMap = null;
  11155. this.displacementMap = null;
  11156. this.displacementScale = 1;
  11157. this.displacementBias = 0;
  11158. this.wireframe = false;
  11159. this.wireframeLinewidth = 1;
  11160. this.fog = false;
  11161. this.setValues( parameters );
  11162. }
  11163. copy( source ) {
  11164. super.copy( source );
  11165. this.depthPacking = source.depthPacking;
  11166. this.morphTargets = source.morphTargets;
  11167. this.map = source.map;
  11168. this.alphaMap = source.alphaMap;
  11169. this.displacementMap = source.displacementMap;
  11170. this.displacementScale = source.displacementScale;
  11171. this.displacementBias = source.displacementBias;
  11172. this.wireframe = source.wireframe;
  11173. this.wireframeLinewidth = source.wireframeLinewidth;
  11174. return this;
  11175. }
  11176. }
  11177. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  11178. /**
  11179. * parameters = {
  11180. *
  11181. * referencePosition: <float>,
  11182. * nearDistance: <float>,
  11183. * farDistance: <float>,
  11184. *
  11185. * morphTargets: <bool>,
  11186. *
  11187. * map: new THREE.Texture( <Image> ),
  11188. *
  11189. * alphaMap: new THREE.Texture( <Image> ),
  11190. *
  11191. * displacementMap: new THREE.Texture( <Image> ),
  11192. * displacementScale: <float>,
  11193. * displacementBias: <float>
  11194. *
  11195. * }
  11196. */
  11197. class MeshDistanceMaterial extends Material {
  11198. constructor( parameters ) {
  11199. super();
  11200. this.type = 'MeshDistanceMaterial';
  11201. this.referencePosition = new Vector3();
  11202. this.nearDistance = 1;
  11203. this.farDistance = 1000;
  11204. this.morphTargets = false;
  11205. this.map = null;
  11206. this.alphaMap = null;
  11207. this.displacementMap = null;
  11208. this.displacementScale = 1;
  11209. this.displacementBias = 0;
  11210. this.fog = false;
  11211. this.setValues( parameters );
  11212. }
  11213. copy( source ) {
  11214. super.copy( source );
  11215. this.referencePosition.copy( source.referencePosition );
  11216. this.nearDistance = source.nearDistance;
  11217. this.farDistance = source.farDistance;
  11218. this.morphTargets = source.morphTargets;
  11219. this.map = source.map;
  11220. this.alphaMap = source.alphaMap;
  11221. this.displacementMap = source.displacementMap;
  11222. this.displacementScale = source.displacementScale;
  11223. this.displacementBias = source.displacementBias;
  11224. return this;
  11225. }
  11226. }
  11227. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  11228. 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}";
  11229. var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  11230. function WebGLShadowMap( _renderer, _objects, _capabilities ) {
  11231. let _frustum = new Frustum();
  11232. const _shadowMapSize = new Vector2(),
  11233. _viewportSize = new Vector2(),
  11234. _viewport = new Vector4(),
  11235. _depthMaterials = [],
  11236. _distanceMaterials = [],
  11237. _materialCache = {},
  11238. _maxTextureSize = _capabilities.maxTextureSize;
  11239. const shadowSide = { 0: BackSide, 1: FrontSide, 2: DoubleSide };
  11240. const shadowMaterialVertical = new ShaderMaterial( {
  11241. defines: {
  11242. SAMPLE_RATE: 2.0 / 8.0,
  11243. HALF_SAMPLE_RATE: 1.0 / 8.0
  11244. },
  11245. uniforms: {
  11246. shadow_pass: { value: null },
  11247. resolution: { value: new Vector2() },
  11248. radius: { value: 4.0 }
  11249. },
  11250. vertexShader: vsm_vert,
  11251. fragmentShader: vsm_frag
  11252. } );
  11253. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  11254. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  11255. const fullScreenTri = new BufferGeometry();
  11256. fullScreenTri.setAttribute(
  11257. 'position',
  11258. new BufferAttribute(
  11259. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  11260. 3
  11261. )
  11262. );
  11263. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  11264. const scope = this;
  11265. this.enabled = false;
  11266. this.autoUpdate = true;
  11267. this.needsUpdate = false;
  11268. this.type = PCFShadowMap;
  11269. this.render = function ( lights, scene, camera ) {
  11270. if ( scope.enabled === false ) return;
  11271. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  11272. if ( lights.length === 0 ) return;
  11273. const currentRenderTarget = _renderer.getRenderTarget();
  11274. const activeCubeFace = _renderer.getActiveCubeFace();
  11275. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  11276. const _state = _renderer.state;
  11277. // Set GL state for depth map.
  11278. _state.setBlending( NoBlending );
  11279. _state.buffers.color.setClear( 1, 1, 1, 1 );
  11280. _state.buffers.depth.setTest( true );
  11281. _state.setScissorTest( false );
  11282. // render depth map
  11283. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  11284. const light = lights[ i ];
  11285. const shadow = light.shadow;
  11286. if ( shadow === undefined ) {
  11287. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  11288. continue;
  11289. }
  11290. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  11291. _shadowMapSize.copy( shadow.mapSize );
  11292. const shadowFrameExtents = shadow.getFrameExtents();
  11293. _shadowMapSize.multiply( shadowFrameExtents );
  11294. _viewportSize.copy( shadow.mapSize );
  11295. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  11296. if ( _shadowMapSize.x > _maxTextureSize ) {
  11297. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  11298. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  11299. shadow.mapSize.x = _viewportSize.x;
  11300. }
  11301. if ( _shadowMapSize.y > _maxTextureSize ) {
  11302. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  11303. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  11304. shadow.mapSize.y = _viewportSize.y;
  11305. }
  11306. }
  11307. if ( shadow.map === null && ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {
  11308. const pars = { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat };
  11309. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  11310. shadow.map.texture.name = light.name + '.shadowMap';
  11311. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  11312. shadow.camera.updateProjectionMatrix();
  11313. }
  11314. if ( shadow.map === null ) {
  11315. const pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  11316. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  11317. shadow.map.texture.name = light.name + '.shadowMap';
  11318. shadow.camera.updateProjectionMatrix();
  11319. }
  11320. _renderer.setRenderTarget( shadow.map );
  11321. _renderer.clear();
  11322. const viewportCount = shadow.getViewportCount();
  11323. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  11324. const viewport = shadow.getViewport( vp );
  11325. _viewport.set(
  11326. _viewportSize.x * viewport.x,
  11327. _viewportSize.y * viewport.y,
  11328. _viewportSize.x * viewport.z,
  11329. _viewportSize.y * viewport.w
  11330. );
  11331. _state.viewport( _viewport );
  11332. shadow.updateMatrices( light, vp );
  11333. _frustum = shadow.getFrustum();
  11334. renderObject( scene, camera, shadow.camera, light, this.type );
  11335. }
  11336. // do blur pass for VSM
  11337. if ( ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {
  11338. VSMPass( shadow, camera );
  11339. }
  11340. shadow.needsUpdate = false;
  11341. }
  11342. scope.needsUpdate = false;
  11343. _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  11344. };
  11345. function VSMPass( shadow, camera ) {
  11346. const geometry = _objects.update( fullScreenMesh );
  11347. // vertical pass
  11348. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  11349. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  11350. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  11351. _renderer.setRenderTarget( shadow.mapPass );
  11352. _renderer.clear();
  11353. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  11354. // horizontal pass
  11355. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  11356. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  11357. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  11358. _renderer.setRenderTarget( shadow.map );
  11359. _renderer.clear();
  11360. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  11361. }
  11362. function getDepthMaterialVariant( useMorphing ) {
  11363. const index = useMorphing << 0;
  11364. let material = _depthMaterials[ index ];
  11365. if ( material === undefined ) {
  11366. material = new MeshDepthMaterial( {
  11367. depthPacking: RGBADepthPacking,
  11368. morphTargets: useMorphing
  11369. } );
  11370. _depthMaterials[ index ] = material;
  11371. }
  11372. return material;
  11373. }
  11374. function getDistanceMaterialVariant( useMorphing ) {
  11375. const index = useMorphing << 0;
  11376. let material = _distanceMaterials[ index ];
  11377. if ( material === undefined ) {
  11378. material = new MeshDistanceMaterial( {
  11379. morphTargets: useMorphing
  11380. } );
  11381. _distanceMaterials[ index ] = material;
  11382. }
  11383. return material;
  11384. }
  11385. function getDepthMaterial( object, geometry, material, light, shadowCameraNear, shadowCameraFar, type ) {
  11386. let result = null;
  11387. let getMaterialVariant = getDepthMaterialVariant;
  11388. let customMaterial = object.customDepthMaterial;
  11389. if ( light.isPointLight === true ) {
  11390. getMaterialVariant = getDistanceMaterialVariant;
  11391. customMaterial = object.customDistanceMaterial;
  11392. }
  11393. if ( customMaterial === undefined ) {
  11394. let useMorphing = false;
  11395. if ( material.morphTargets === true ) {
  11396. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  11397. }
  11398. result = getMaterialVariant( useMorphing );
  11399. } else {
  11400. result = customMaterial;
  11401. }
  11402. if ( _renderer.localClippingEnabled &&
  11403. material.clipShadows === true &&
  11404. material.clippingPlanes.length !== 0 ) {
  11405. // in this case we need a unique material instance reflecting the
  11406. // appropriate state
  11407. const keyA = result.uuid, keyB = material.uuid;
  11408. let materialsForVariant = _materialCache[ keyA ];
  11409. if ( materialsForVariant === undefined ) {
  11410. materialsForVariant = {};
  11411. _materialCache[ keyA ] = materialsForVariant;
  11412. }
  11413. let cachedMaterial = materialsForVariant[ keyB ];
  11414. if ( cachedMaterial === undefined ) {
  11415. cachedMaterial = result.clone();
  11416. materialsForVariant[ keyB ] = cachedMaterial;
  11417. }
  11418. result = cachedMaterial;
  11419. }
  11420. result.visible = material.visible;
  11421. result.wireframe = material.wireframe;
  11422. if ( type === VSMShadowMap ) {
  11423. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  11424. } else {
  11425. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  11426. }
  11427. result.clipShadows = material.clipShadows;
  11428. result.clippingPlanes = material.clippingPlanes;
  11429. result.clipIntersection = material.clipIntersection;
  11430. result.wireframeLinewidth = material.wireframeLinewidth;
  11431. result.linewidth = material.linewidth;
  11432. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  11433. result.referencePosition.setFromMatrixPosition( light.matrixWorld );
  11434. result.nearDistance = shadowCameraNear;
  11435. result.farDistance = shadowCameraFar;
  11436. }
  11437. return result;
  11438. }
  11439. function renderObject( object, camera, shadowCamera, light, type ) {
  11440. if ( object.visible === false ) return;
  11441. const visible = object.layers.test( camera.layers );
  11442. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  11443. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  11444. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  11445. const geometry = _objects.update( object );
  11446. const material = object.material;
  11447. if ( Array.isArray( material ) ) {
  11448. const groups = geometry.groups;
  11449. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  11450. const group = groups[ k ];
  11451. const groupMaterial = material[ group.materialIndex ];
  11452. if ( groupMaterial && groupMaterial.visible ) {
  11453. const depthMaterial = getDepthMaterial( object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type );
  11454. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  11455. }
  11456. }
  11457. } else if ( material.visible ) {
  11458. const depthMaterial = getDepthMaterial( object, geometry, material, light, shadowCamera.near, shadowCamera.far, type );
  11459. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  11460. }
  11461. }
  11462. }
  11463. const children = object.children;
  11464. for ( let i = 0, l = children.length; i < l; i ++ ) {
  11465. renderObject( children[ i ], camera, shadowCamera, light, type );
  11466. }
  11467. }
  11468. }
  11469. function WebGLState( gl, extensions, capabilities ) {
  11470. const isWebGL2 = capabilities.isWebGL2;
  11471. function ColorBuffer() {
  11472. let locked = false;
  11473. const color = new Vector4();
  11474. let currentColorMask = null;
  11475. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  11476. return {
  11477. setMask: function ( colorMask ) {
  11478. if ( currentColorMask !== colorMask && ! locked ) {
  11479. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  11480. currentColorMask = colorMask;
  11481. }
  11482. },
  11483. setLocked: function ( lock ) {
  11484. locked = lock;
  11485. },
  11486. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  11487. if ( premultipliedAlpha === true ) {
  11488. r *= a; g *= a; b *= a;
  11489. }
  11490. color.set( r, g, b, a );
  11491. if ( currentColorClear.equals( color ) === false ) {
  11492. gl.clearColor( r, g, b, a );
  11493. currentColorClear.copy( color );
  11494. }
  11495. },
  11496. reset: function () {
  11497. locked = false;
  11498. currentColorMask = null;
  11499. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  11500. }
  11501. };
  11502. }
  11503. function DepthBuffer() {
  11504. let locked = false;
  11505. let currentDepthMask = null;
  11506. let currentDepthFunc = null;
  11507. let currentDepthClear = null;
  11508. return {
  11509. setTest: function ( depthTest ) {
  11510. if ( depthTest ) {
  11511. enable( 2929 );
  11512. } else {
  11513. disable( 2929 );
  11514. }
  11515. },
  11516. setMask: function ( depthMask ) {
  11517. if ( currentDepthMask !== depthMask && ! locked ) {
  11518. gl.depthMask( depthMask );
  11519. currentDepthMask = depthMask;
  11520. }
  11521. },
  11522. setFunc: function ( depthFunc ) {
  11523. if ( currentDepthFunc !== depthFunc ) {
  11524. if ( depthFunc ) {
  11525. switch ( depthFunc ) {
  11526. case NeverDepth:
  11527. gl.depthFunc( 512 );
  11528. break;
  11529. case AlwaysDepth:
  11530. gl.depthFunc( 519 );
  11531. break;
  11532. case LessDepth:
  11533. gl.depthFunc( 513 );
  11534. break;
  11535. case LessEqualDepth:
  11536. gl.depthFunc( 515 );
  11537. break;
  11538. case EqualDepth:
  11539. gl.depthFunc( 514 );
  11540. break;
  11541. case GreaterEqualDepth:
  11542. gl.depthFunc( 518 );
  11543. break;
  11544. case GreaterDepth:
  11545. gl.depthFunc( 516 );
  11546. break;
  11547. case NotEqualDepth:
  11548. gl.depthFunc( 517 );
  11549. break;
  11550. default:
  11551. gl.depthFunc( 515 );
  11552. }
  11553. } else {
  11554. gl.depthFunc( 515 );
  11555. }
  11556. currentDepthFunc = depthFunc;
  11557. }
  11558. },
  11559. setLocked: function ( lock ) {
  11560. locked = lock;
  11561. },
  11562. setClear: function ( depth ) {
  11563. if ( currentDepthClear !== depth ) {
  11564. gl.clearDepth( depth );
  11565. currentDepthClear = depth;
  11566. }
  11567. },
  11568. reset: function () {
  11569. locked = false;
  11570. currentDepthMask = null;
  11571. currentDepthFunc = null;
  11572. currentDepthClear = null;
  11573. }
  11574. };
  11575. }
  11576. function StencilBuffer() {
  11577. let locked = false;
  11578. let currentStencilMask = null;
  11579. let currentStencilFunc = null;
  11580. let currentStencilRef = null;
  11581. let currentStencilFuncMask = null;
  11582. let currentStencilFail = null;
  11583. let currentStencilZFail = null;
  11584. let currentStencilZPass = null;
  11585. let currentStencilClear = null;
  11586. return {
  11587. setTest: function ( stencilTest ) {
  11588. if ( ! locked ) {
  11589. if ( stencilTest ) {
  11590. enable( 2960 );
  11591. } else {
  11592. disable( 2960 );
  11593. }
  11594. }
  11595. },
  11596. setMask: function ( stencilMask ) {
  11597. if ( currentStencilMask !== stencilMask && ! locked ) {
  11598. gl.stencilMask( stencilMask );
  11599. currentStencilMask = stencilMask;
  11600. }
  11601. },
  11602. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  11603. if ( currentStencilFunc !== stencilFunc ||
  11604. currentStencilRef !== stencilRef ||
  11605. currentStencilFuncMask !== stencilMask ) {
  11606. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  11607. currentStencilFunc = stencilFunc;
  11608. currentStencilRef = stencilRef;
  11609. currentStencilFuncMask = stencilMask;
  11610. }
  11611. },
  11612. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  11613. if ( currentStencilFail !== stencilFail ||
  11614. currentStencilZFail !== stencilZFail ||
  11615. currentStencilZPass !== stencilZPass ) {
  11616. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  11617. currentStencilFail = stencilFail;
  11618. currentStencilZFail = stencilZFail;
  11619. currentStencilZPass = stencilZPass;
  11620. }
  11621. },
  11622. setLocked: function ( lock ) {
  11623. locked = lock;
  11624. },
  11625. setClear: function ( stencil ) {
  11626. if ( currentStencilClear !== stencil ) {
  11627. gl.clearStencil( stencil );
  11628. currentStencilClear = stencil;
  11629. }
  11630. },
  11631. reset: function () {
  11632. locked = false;
  11633. currentStencilMask = null;
  11634. currentStencilFunc = null;
  11635. currentStencilRef = null;
  11636. currentStencilFuncMask = null;
  11637. currentStencilFail = null;
  11638. currentStencilZFail = null;
  11639. currentStencilZPass = null;
  11640. currentStencilClear = null;
  11641. }
  11642. };
  11643. }
  11644. //
  11645. const colorBuffer = new ColorBuffer();
  11646. const depthBuffer = new DepthBuffer();
  11647. const stencilBuffer = new StencilBuffer();
  11648. let enabledCapabilities = {};
  11649. let xrFramebuffer = null;
  11650. let currentBoundFramebuffers = {};
  11651. let currentProgram = null;
  11652. let currentBlendingEnabled = false;
  11653. let currentBlending = null;
  11654. let currentBlendEquation = null;
  11655. let currentBlendSrc = null;
  11656. let currentBlendDst = null;
  11657. let currentBlendEquationAlpha = null;
  11658. let currentBlendSrcAlpha = null;
  11659. let currentBlendDstAlpha = null;
  11660. let currentPremultipledAlpha = false;
  11661. let currentFlipSided = null;
  11662. let currentCullFace = null;
  11663. let currentLineWidth = null;
  11664. let currentPolygonOffsetFactor = null;
  11665. let currentPolygonOffsetUnits = null;
  11666. const maxTextures = gl.getParameter( 35661 );
  11667. let lineWidthAvailable = false;
  11668. let version = 0;
  11669. const glVersion = gl.getParameter( 7938 );
  11670. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  11671. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  11672. lineWidthAvailable = ( version >= 1.0 );
  11673. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  11674. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  11675. lineWidthAvailable = ( version >= 2.0 );
  11676. }
  11677. let currentTextureSlot = null;
  11678. let currentBoundTextures = {};
  11679. const scissorParam = gl.getParameter( 3088 );
  11680. const viewportParam = gl.getParameter( 2978 );
  11681. const currentScissor = new Vector4().fromArray( scissorParam );
  11682. const currentViewport = new Vector4().fromArray( viewportParam );
  11683. function createTexture( type, target, count ) {
  11684. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  11685. const texture = gl.createTexture();
  11686. gl.bindTexture( type, texture );
  11687. gl.texParameteri( type, 10241, 9728 );
  11688. gl.texParameteri( type, 10240, 9728 );
  11689. for ( let i = 0; i < count; i ++ ) {
  11690. gl.texImage2D( target + i, 0, 6408, 1, 1, 0, 6408, 5121, data );
  11691. }
  11692. return texture;
  11693. }
  11694. const emptyTextures = {};
  11695. emptyTextures[ 3553 ] = createTexture( 3553, 3553, 1 );
  11696. emptyTextures[ 34067 ] = createTexture( 34067, 34069, 6 );
  11697. // init
  11698. colorBuffer.setClear( 0, 0, 0, 1 );
  11699. depthBuffer.setClear( 1 );
  11700. stencilBuffer.setClear( 0 );
  11701. enable( 2929 );
  11702. depthBuffer.setFunc( LessEqualDepth );
  11703. setFlipSided( false );
  11704. setCullFace( CullFaceBack );
  11705. enable( 2884 );
  11706. setBlending( NoBlending );
  11707. //
  11708. function enable( id ) {
  11709. if ( enabledCapabilities[ id ] !== true ) {
  11710. gl.enable( id );
  11711. enabledCapabilities[ id ] = true;
  11712. }
  11713. }
  11714. function disable( id ) {
  11715. if ( enabledCapabilities[ id ] !== false ) {
  11716. gl.disable( id );
  11717. enabledCapabilities[ id ] = false;
  11718. }
  11719. }
  11720. function bindXRFramebuffer( framebuffer ) {
  11721. if ( framebuffer !== xrFramebuffer ) {
  11722. gl.bindFramebuffer( 36160, framebuffer );
  11723. xrFramebuffer = framebuffer;
  11724. }
  11725. }
  11726. function bindFramebuffer( target, framebuffer ) {
  11727. if ( framebuffer === null && xrFramebuffer !== null ) framebuffer = xrFramebuffer; // use active XR framebuffer if available
  11728. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  11729. gl.bindFramebuffer( target, framebuffer );
  11730. currentBoundFramebuffers[ target ] = framebuffer;
  11731. if ( isWebGL2 ) {
  11732. // 36009 is equivalent to 36160
  11733. if ( target === 36009 ) {
  11734. currentBoundFramebuffers[ 36160 ] = framebuffer;
  11735. }
  11736. if ( target === 36160 ) {
  11737. currentBoundFramebuffers[ 36009 ] = framebuffer;
  11738. }
  11739. }
  11740. return true;
  11741. }
  11742. return false;
  11743. }
  11744. function useProgram( program ) {
  11745. if ( currentProgram !== program ) {
  11746. gl.useProgram( program );
  11747. currentProgram = program;
  11748. return true;
  11749. }
  11750. return false;
  11751. }
  11752. const equationToGL = {
  11753. [ AddEquation ]: 32774,
  11754. [ SubtractEquation ]: 32778,
  11755. [ ReverseSubtractEquation ]: 32779
  11756. };
  11757. if ( isWebGL2 ) {
  11758. equationToGL[ MinEquation ] = 32775;
  11759. equationToGL[ MaxEquation ] = 32776;
  11760. } else {
  11761. const extension = extensions.get( 'EXT_blend_minmax' );
  11762. if ( extension !== null ) {
  11763. equationToGL[ MinEquation ] = extension.MIN_EXT;
  11764. equationToGL[ MaxEquation ] = extension.MAX_EXT;
  11765. }
  11766. }
  11767. const factorToGL = {
  11768. [ ZeroFactor ]: 0,
  11769. [ OneFactor ]: 1,
  11770. [ SrcColorFactor ]: 768,
  11771. [ SrcAlphaFactor ]: 770,
  11772. [ SrcAlphaSaturateFactor ]: 776,
  11773. [ DstColorFactor ]: 774,
  11774. [ DstAlphaFactor ]: 772,
  11775. [ OneMinusSrcColorFactor ]: 769,
  11776. [ OneMinusSrcAlphaFactor ]: 771,
  11777. [ OneMinusDstColorFactor ]: 775,
  11778. [ OneMinusDstAlphaFactor ]: 773
  11779. };
  11780. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  11781. if ( blending === NoBlending ) {
  11782. if ( currentBlendingEnabled === true ) {
  11783. disable( 3042 );
  11784. currentBlendingEnabled = false;
  11785. }
  11786. return;
  11787. }
  11788. if ( currentBlendingEnabled === false ) {
  11789. enable( 3042 );
  11790. currentBlendingEnabled = true;
  11791. }
  11792. if ( blending !== CustomBlending ) {
  11793. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  11794. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  11795. gl.blendEquation( 32774 );
  11796. currentBlendEquation = AddEquation;
  11797. currentBlendEquationAlpha = AddEquation;
  11798. }
  11799. if ( premultipliedAlpha ) {
  11800. switch ( blending ) {
  11801. case NormalBlending:
  11802. gl.blendFuncSeparate( 1, 771, 1, 771 );
  11803. break;
  11804. case AdditiveBlending:
  11805. gl.blendFunc( 1, 1 );
  11806. break;
  11807. case SubtractiveBlending:
  11808. gl.blendFuncSeparate( 0, 0, 769, 771 );
  11809. break;
  11810. case MultiplyBlending:
  11811. gl.blendFuncSeparate( 0, 768, 0, 770 );
  11812. break;
  11813. default:
  11814. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  11815. break;
  11816. }
  11817. } else {
  11818. switch ( blending ) {
  11819. case NormalBlending:
  11820. gl.blendFuncSeparate( 770, 771, 1, 771 );
  11821. break;
  11822. case AdditiveBlending:
  11823. gl.blendFunc( 770, 1 );
  11824. break;
  11825. case SubtractiveBlending:
  11826. gl.blendFunc( 0, 769 );
  11827. break;
  11828. case MultiplyBlending:
  11829. gl.blendFunc( 0, 768 );
  11830. break;
  11831. default:
  11832. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  11833. break;
  11834. }
  11835. }
  11836. currentBlendSrc = null;
  11837. currentBlendDst = null;
  11838. currentBlendSrcAlpha = null;
  11839. currentBlendDstAlpha = null;
  11840. currentBlending = blending;
  11841. currentPremultipledAlpha = premultipliedAlpha;
  11842. }
  11843. return;
  11844. }
  11845. // custom blending
  11846. blendEquationAlpha = blendEquationAlpha || blendEquation;
  11847. blendSrcAlpha = blendSrcAlpha || blendSrc;
  11848. blendDstAlpha = blendDstAlpha || blendDst;
  11849. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  11850. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  11851. currentBlendEquation = blendEquation;
  11852. currentBlendEquationAlpha = blendEquationAlpha;
  11853. }
  11854. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  11855. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  11856. currentBlendSrc = blendSrc;
  11857. currentBlendDst = blendDst;
  11858. currentBlendSrcAlpha = blendSrcAlpha;
  11859. currentBlendDstAlpha = blendDstAlpha;
  11860. }
  11861. currentBlending = blending;
  11862. currentPremultipledAlpha = null;
  11863. }
  11864. function setMaterial( material, frontFaceCW ) {
  11865. material.side === DoubleSide
  11866. ? disable( 2884 )
  11867. : enable( 2884 );
  11868. let flipSided = ( material.side === BackSide );
  11869. if ( frontFaceCW ) flipSided = ! flipSided;
  11870. setFlipSided( flipSided );
  11871. ( material.blending === NormalBlending && material.transparent === false )
  11872. ? setBlending( NoBlending )
  11873. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  11874. depthBuffer.setFunc( material.depthFunc );
  11875. depthBuffer.setTest( material.depthTest );
  11876. depthBuffer.setMask( material.depthWrite );
  11877. colorBuffer.setMask( material.colorWrite );
  11878. const stencilWrite = material.stencilWrite;
  11879. stencilBuffer.setTest( stencilWrite );
  11880. if ( stencilWrite ) {
  11881. stencilBuffer.setMask( material.stencilWriteMask );
  11882. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  11883. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  11884. }
  11885. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11886. material.alphaToCoverage === true
  11887. ? enable( 32926 )
  11888. : disable( 32926 );
  11889. }
  11890. //
  11891. function setFlipSided( flipSided ) {
  11892. if ( currentFlipSided !== flipSided ) {
  11893. if ( flipSided ) {
  11894. gl.frontFace( 2304 );
  11895. } else {
  11896. gl.frontFace( 2305 );
  11897. }
  11898. currentFlipSided = flipSided;
  11899. }
  11900. }
  11901. function setCullFace( cullFace ) {
  11902. if ( cullFace !== CullFaceNone ) {
  11903. enable( 2884 );
  11904. if ( cullFace !== currentCullFace ) {
  11905. if ( cullFace === CullFaceBack ) {
  11906. gl.cullFace( 1029 );
  11907. } else if ( cullFace === CullFaceFront ) {
  11908. gl.cullFace( 1028 );
  11909. } else {
  11910. gl.cullFace( 1032 );
  11911. }
  11912. }
  11913. } else {
  11914. disable( 2884 );
  11915. }
  11916. currentCullFace = cullFace;
  11917. }
  11918. function setLineWidth( width ) {
  11919. if ( width !== currentLineWidth ) {
  11920. if ( lineWidthAvailable ) gl.lineWidth( width );
  11921. currentLineWidth = width;
  11922. }
  11923. }
  11924. function setPolygonOffset( polygonOffset, factor, units ) {
  11925. if ( polygonOffset ) {
  11926. enable( 32823 );
  11927. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  11928. gl.polygonOffset( factor, units );
  11929. currentPolygonOffsetFactor = factor;
  11930. currentPolygonOffsetUnits = units;
  11931. }
  11932. } else {
  11933. disable( 32823 );
  11934. }
  11935. }
  11936. function setScissorTest( scissorTest ) {
  11937. if ( scissorTest ) {
  11938. enable( 3089 );
  11939. } else {
  11940. disable( 3089 );
  11941. }
  11942. }
  11943. // texture
  11944. function activeTexture( webglSlot ) {
  11945. if ( webglSlot === undefined ) webglSlot = 33984 + maxTextures - 1;
  11946. if ( currentTextureSlot !== webglSlot ) {
  11947. gl.activeTexture( webglSlot );
  11948. currentTextureSlot = webglSlot;
  11949. }
  11950. }
  11951. function bindTexture( webglType, webglTexture ) {
  11952. if ( currentTextureSlot === null ) {
  11953. activeTexture();
  11954. }
  11955. let boundTexture = currentBoundTextures[ currentTextureSlot ];
  11956. if ( boundTexture === undefined ) {
  11957. boundTexture = { type: undefined, texture: undefined };
  11958. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  11959. }
  11960. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  11961. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  11962. boundTexture.type = webglType;
  11963. boundTexture.texture = webglTexture;
  11964. }
  11965. }
  11966. function unbindTexture() {
  11967. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  11968. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  11969. gl.bindTexture( boundTexture.type, null );
  11970. boundTexture.type = undefined;
  11971. boundTexture.texture = undefined;
  11972. }
  11973. }
  11974. function compressedTexImage2D() {
  11975. try {
  11976. gl.compressedTexImage2D.apply( gl, arguments );
  11977. } catch ( error ) {
  11978. console.error( 'THREE.WebGLState:', error );
  11979. }
  11980. }
  11981. function texImage2D() {
  11982. try {
  11983. gl.texImage2D.apply( gl, arguments );
  11984. } catch ( error ) {
  11985. console.error( 'THREE.WebGLState:', error );
  11986. }
  11987. }
  11988. function texImage3D() {
  11989. try {
  11990. gl.texImage3D.apply( gl, arguments );
  11991. } catch ( error ) {
  11992. console.error( 'THREE.WebGLState:', error );
  11993. }
  11994. }
  11995. //
  11996. function scissor( scissor ) {
  11997. if ( currentScissor.equals( scissor ) === false ) {
  11998. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  11999. currentScissor.copy( scissor );
  12000. }
  12001. }
  12002. function viewport( viewport ) {
  12003. if ( currentViewport.equals( viewport ) === false ) {
  12004. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  12005. currentViewport.copy( viewport );
  12006. }
  12007. }
  12008. //
  12009. function reset() {
  12010. // reset state
  12011. gl.disable( 3042 );
  12012. gl.disable( 2884 );
  12013. gl.disable( 2929 );
  12014. gl.disable( 32823 );
  12015. gl.disable( 3089 );
  12016. gl.disable( 2960 );
  12017. gl.disable( 32926 );
  12018. gl.blendEquation( 32774 );
  12019. gl.blendFunc( 1, 0 );
  12020. gl.blendFuncSeparate( 1, 0, 1, 0 );
  12021. gl.colorMask( true, true, true, true );
  12022. gl.clearColor( 0, 0, 0, 0 );
  12023. gl.depthMask( true );
  12024. gl.depthFunc( 513 );
  12025. gl.clearDepth( 1 );
  12026. gl.stencilMask( 0xffffffff );
  12027. gl.stencilFunc( 519, 0, 0xffffffff );
  12028. gl.stencilOp( 7680, 7680, 7680 );
  12029. gl.clearStencil( 0 );
  12030. gl.cullFace( 1029 );
  12031. gl.frontFace( 2305 );
  12032. gl.polygonOffset( 0, 0 );
  12033. gl.activeTexture( 33984 );
  12034. gl.bindFramebuffer( 36160, null );
  12035. if ( isWebGL2 === true ) {
  12036. gl.bindFramebuffer( 36009, null );
  12037. gl.bindFramebuffer( 36008, null );
  12038. }
  12039. gl.useProgram( null );
  12040. gl.lineWidth( 1 );
  12041. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  12042. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  12043. // reset internals
  12044. enabledCapabilities = {};
  12045. currentTextureSlot = null;
  12046. currentBoundTextures = {};
  12047. xrFramebuffer = null;
  12048. currentBoundFramebuffers = {};
  12049. currentProgram = null;
  12050. currentBlendingEnabled = false;
  12051. currentBlending = null;
  12052. currentBlendEquation = null;
  12053. currentBlendSrc = null;
  12054. currentBlendDst = null;
  12055. currentBlendEquationAlpha = null;
  12056. currentBlendSrcAlpha = null;
  12057. currentBlendDstAlpha = null;
  12058. currentPremultipledAlpha = false;
  12059. currentFlipSided = null;
  12060. currentCullFace = null;
  12061. currentLineWidth = null;
  12062. currentPolygonOffsetFactor = null;
  12063. currentPolygonOffsetUnits = null;
  12064. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  12065. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  12066. colorBuffer.reset();
  12067. depthBuffer.reset();
  12068. stencilBuffer.reset();
  12069. }
  12070. return {
  12071. buffers: {
  12072. color: colorBuffer,
  12073. depth: depthBuffer,
  12074. stencil: stencilBuffer
  12075. },
  12076. enable: enable,
  12077. disable: disable,
  12078. bindFramebuffer: bindFramebuffer,
  12079. bindXRFramebuffer: bindXRFramebuffer,
  12080. useProgram: useProgram,
  12081. setBlending: setBlending,
  12082. setMaterial: setMaterial,
  12083. setFlipSided: setFlipSided,
  12084. setCullFace: setCullFace,
  12085. setLineWidth: setLineWidth,
  12086. setPolygonOffset: setPolygonOffset,
  12087. setScissorTest: setScissorTest,
  12088. activeTexture: activeTexture,
  12089. bindTexture: bindTexture,
  12090. unbindTexture: unbindTexture,
  12091. compressedTexImage2D: compressedTexImage2D,
  12092. texImage2D: texImage2D,
  12093. texImage3D: texImage3D,
  12094. scissor: scissor,
  12095. viewport: viewport,
  12096. reset: reset
  12097. };
  12098. }
  12099. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  12100. const isWebGL2 = capabilities.isWebGL2;
  12101. const maxTextures = capabilities.maxTextures;
  12102. const maxCubemapSize = capabilities.maxCubemapSize;
  12103. const maxTextureSize = capabilities.maxTextureSize;
  12104. const maxSamples = capabilities.maxSamples;
  12105. const _videoTextures = new WeakMap();
  12106. let _canvas;
  12107. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  12108. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  12109. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  12110. let useOffscreenCanvas = false;
  12111. try {
  12112. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  12113. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  12114. } catch ( err ) {
  12115. // Ignore any errors
  12116. }
  12117. function createCanvas( width, height ) {
  12118. // Use OffscreenCanvas when available. Specially needed in web workers
  12119. return useOffscreenCanvas ?
  12120. new OffscreenCanvas( width, height ) :
  12121. document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  12122. }
  12123. function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {
  12124. let scale = 1;
  12125. // handle case if texture exceeds max size
  12126. if ( image.width > maxSize || image.height > maxSize ) {
  12127. scale = maxSize / Math.max( image.width, image.height );
  12128. }
  12129. // only perform resize if necessary
  12130. if ( scale < 1 || needsPowerOfTwo === true ) {
  12131. // only perform resize for certain image types
  12132. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  12133. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  12134. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  12135. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  12136. const width = floor( scale * image.width );
  12137. const height = floor( scale * image.height );
  12138. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  12139. // cube textures can't reuse the same canvas
  12140. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  12141. canvas.width = width;
  12142. canvas.height = height;
  12143. const context = canvas.getContext( '2d' );
  12144. context.drawImage( image, 0, 0, width, height );
  12145. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );
  12146. return canvas;
  12147. } else {
  12148. if ( 'data' in image ) {
  12149. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  12150. }
  12151. return image;
  12152. }
  12153. }
  12154. return image;
  12155. }
  12156. function isPowerOfTwo$1( image ) {
  12157. return isPowerOfTwo( image.width ) && isPowerOfTwo( image.height );
  12158. }
  12159. function textureNeedsPowerOfTwo( texture ) {
  12160. if ( isWebGL2 ) return false;
  12161. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  12162. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  12163. }
  12164. function textureNeedsGenerateMipmaps( texture, supportsMips ) {
  12165. return texture.generateMipmaps && supportsMips &&
  12166. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  12167. }
  12168. function generateMipmap( target, texture, width, height, depth = 1 ) {
  12169. _gl.generateMipmap( target );
  12170. const textureProperties = properties.get( texture );
  12171. textureProperties.__maxMipLevel = Math.log2( Math.max( width, height, depth ) );
  12172. }
  12173. function getInternalFormat( internalFormatName, glFormat, glType ) {
  12174. if ( isWebGL2 === false ) return glFormat;
  12175. if ( internalFormatName !== null ) {
  12176. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  12177. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  12178. }
  12179. let internalFormat = glFormat;
  12180. if ( glFormat === 6403 ) {
  12181. if ( glType === 5126 ) internalFormat = 33326;
  12182. if ( glType === 5131 ) internalFormat = 33325;
  12183. if ( glType === 5121 ) internalFormat = 33321;
  12184. }
  12185. if ( glFormat === 6407 ) {
  12186. if ( glType === 5126 ) internalFormat = 34837;
  12187. if ( glType === 5131 ) internalFormat = 34843;
  12188. if ( glType === 5121 ) internalFormat = 32849;
  12189. }
  12190. if ( glFormat === 6408 ) {
  12191. if ( glType === 5126 ) internalFormat = 34836;
  12192. if ( glType === 5131 ) internalFormat = 34842;
  12193. if ( glType === 5121 ) internalFormat = 32856;
  12194. }
  12195. if ( internalFormat === 33325 || internalFormat === 33326 ||
  12196. internalFormat === 34842 || internalFormat === 34836 ) {
  12197. extensions.get( 'EXT_color_buffer_float' );
  12198. }
  12199. return internalFormat;
  12200. }
  12201. // Fallback filters for non-power-of-2 textures
  12202. function filterFallback( f ) {
  12203. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  12204. return 9728;
  12205. }
  12206. return 9729;
  12207. }
  12208. //
  12209. function onTextureDispose( event ) {
  12210. const texture = event.target;
  12211. texture.removeEventListener( 'dispose', onTextureDispose );
  12212. deallocateTexture( texture );
  12213. if ( texture.isVideoTexture ) {
  12214. _videoTextures.delete( texture );
  12215. }
  12216. info.memory.textures --;
  12217. }
  12218. function onRenderTargetDispose( event ) {
  12219. const renderTarget = event.target;
  12220. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  12221. deallocateRenderTarget( renderTarget );
  12222. }
  12223. //
  12224. function deallocateTexture( texture ) {
  12225. const textureProperties = properties.get( texture );
  12226. if ( textureProperties.__webglInit === undefined ) return;
  12227. _gl.deleteTexture( textureProperties.__webglTexture );
  12228. properties.remove( texture );
  12229. }
  12230. function deallocateRenderTarget( renderTarget ) {
  12231. const texture = renderTarget.texture;
  12232. const renderTargetProperties = properties.get( renderTarget );
  12233. const textureProperties = properties.get( texture );
  12234. if ( ! renderTarget ) return;
  12235. if ( textureProperties.__webglTexture !== undefined ) {
  12236. _gl.deleteTexture( textureProperties.__webglTexture );
  12237. info.memory.textures --;
  12238. }
  12239. if ( renderTarget.depthTexture ) {
  12240. renderTarget.depthTexture.dispose();
  12241. }
  12242. if ( renderTarget.isWebGLCubeRenderTarget ) {
  12243. for ( let i = 0; i < 6; i ++ ) {
  12244. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  12245. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  12246. }
  12247. } else {
  12248. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  12249. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  12250. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  12251. if ( renderTargetProperties.__webglColorRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer );
  12252. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  12253. }
  12254. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  12255. for ( let i = 0, il = texture.length; i < il; i ++ ) {
  12256. const attachmentProperties = properties.get( texture[ i ] );
  12257. if ( attachmentProperties.__webglTexture ) {
  12258. _gl.deleteTexture( attachmentProperties.__webglTexture );
  12259. info.memory.textures --;
  12260. }
  12261. properties.remove( texture[ i ] );
  12262. }
  12263. }
  12264. properties.remove( texture );
  12265. properties.remove( renderTarget );
  12266. }
  12267. //
  12268. let textureUnits = 0;
  12269. function resetTextureUnits() {
  12270. textureUnits = 0;
  12271. }
  12272. function allocateTextureUnit() {
  12273. const textureUnit = textureUnits;
  12274. if ( textureUnit >= maxTextures ) {
  12275. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures );
  12276. }
  12277. textureUnits += 1;
  12278. return textureUnit;
  12279. }
  12280. //
  12281. function setTexture2D( texture, slot ) {
  12282. const textureProperties = properties.get( texture );
  12283. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  12284. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  12285. const image = texture.image;
  12286. if ( image === undefined ) {
  12287. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined' );
  12288. } else if ( image.complete === false ) {
  12289. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  12290. } else {
  12291. uploadTexture( textureProperties, texture, slot );
  12292. return;
  12293. }
  12294. }
  12295. state.activeTexture( 33984 + slot );
  12296. state.bindTexture( 3553, textureProperties.__webglTexture );
  12297. }
  12298. function setTexture2DArray( texture, slot ) {
  12299. const textureProperties = properties.get( texture );
  12300. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  12301. uploadTexture( textureProperties, texture, slot );
  12302. return;
  12303. }
  12304. state.activeTexture( 33984 + slot );
  12305. state.bindTexture( 35866, textureProperties.__webglTexture );
  12306. }
  12307. function setTexture3D( texture, slot ) {
  12308. const textureProperties = properties.get( texture );
  12309. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  12310. uploadTexture( textureProperties, texture, slot );
  12311. return;
  12312. }
  12313. state.activeTexture( 33984 + slot );
  12314. state.bindTexture( 32879, textureProperties.__webglTexture );
  12315. }
  12316. function setTextureCube( texture, slot ) {
  12317. const textureProperties = properties.get( texture );
  12318. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  12319. uploadCubeTexture( textureProperties, texture, slot );
  12320. return;
  12321. }
  12322. state.activeTexture( 33984 + slot );
  12323. state.bindTexture( 34067, textureProperties.__webglTexture );
  12324. }
  12325. const wrappingToGL = {
  12326. [ RepeatWrapping ]: 10497,
  12327. [ ClampToEdgeWrapping ]: 33071,
  12328. [ MirroredRepeatWrapping ]: 33648
  12329. };
  12330. const filterToGL = {
  12331. [ NearestFilter ]: 9728,
  12332. [ NearestMipmapNearestFilter ]: 9984,
  12333. [ NearestMipmapLinearFilter ]: 9986,
  12334. [ LinearFilter ]: 9729,
  12335. [ LinearMipmapNearestFilter ]: 9985,
  12336. [ LinearMipmapLinearFilter ]: 9987
  12337. };
  12338. function setTextureParameters( textureType, texture, supportsMips ) {
  12339. if ( supportsMips ) {
  12340. _gl.texParameteri( textureType, 10242, wrappingToGL[ texture.wrapS ] );
  12341. _gl.texParameteri( textureType, 10243, wrappingToGL[ texture.wrapT ] );
  12342. if ( textureType === 32879 || textureType === 35866 ) {
  12343. _gl.texParameteri( textureType, 32882, wrappingToGL[ texture.wrapR ] );
  12344. }
  12345. _gl.texParameteri( textureType, 10240, filterToGL[ texture.magFilter ] );
  12346. _gl.texParameteri( textureType, 10241, filterToGL[ texture.minFilter ] );
  12347. } else {
  12348. _gl.texParameteri( textureType, 10242, 33071 );
  12349. _gl.texParameteri( textureType, 10243, 33071 );
  12350. if ( textureType === 32879 || textureType === 35866 ) {
  12351. _gl.texParameteri( textureType, 32882, 33071 );
  12352. }
  12353. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  12354. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
  12355. }
  12356. _gl.texParameteri( textureType, 10240, filterFallback( texture.magFilter ) );
  12357. _gl.texParameteri( textureType, 10241, filterFallback( texture.minFilter ) );
  12358. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  12359. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
  12360. }
  12361. }
  12362. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  12363. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  12364. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  12365. if ( isWebGL2 === false && ( texture.type === HalfFloatType && extensions.has( 'OES_texture_half_float_linear' ) === false ) ) return; // verify extension for WebGL 1 only
  12366. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  12367. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  12368. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  12369. }
  12370. }
  12371. }
  12372. function initTexture( textureProperties, texture ) {
  12373. if ( textureProperties.__webglInit === undefined ) {
  12374. textureProperties.__webglInit = true;
  12375. texture.addEventListener( 'dispose', onTextureDispose );
  12376. textureProperties.__webglTexture = _gl.createTexture();
  12377. info.memory.textures ++;
  12378. }
  12379. }
  12380. function uploadTexture( textureProperties, texture, slot ) {
  12381. let textureType = 3553;
  12382. if ( texture.isDataTexture2DArray ) textureType = 35866;
  12383. if ( texture.isDataTexture3D ) textureType = 32879;
  12384. initTexture( textureProperties, texture );
  12385. state.activeTexture( 33984 + slot );
  12386. state.bindTexture( textureType, textureProperties.__webglTexture );
  12387. _gl.pixelStorei( 37440, texture.flipY );
  12388. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  12389. _gl.pixelStorei( 3317, texture.unpackAlignment );
  12390. _gl.pixelStorei( 37443, 0 );
  12391. const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo$1( texture.image ) === false;
  12392. const image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );
  12393. const supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  12394. glFormat = utils.convert( texture.format );
  12395. let glType = utils.convert( texture.type ),
  12396. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  12397. setTextureParameters( textureType, texture, supportsMips );
  12398. let mipmap;
  12399. const mipmaps = texture.mipmaps;
  12400. if ( texture.isDepthTexture ) {
  12401. // populate depth texture with dummy data
  12402. glInternalFormat = 6402;
  12403. if ( isWebGL2 ) {
  12404. if ( texture.type === FloatType ) {
  12405. glInternalFormat = 36012;
  12406. } else if ( texture.type === UnsignedIntType ) {
  12407. glInternalFormat = 33190;
  12408. } else if ( texture.type === UnsignedInt248Type ) {
  12409. glInternalFormat = 35056;
  12410. } else {
  12411. glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D
  12412. }
  12413. } else {
  12414. if ( texture.type === FloatType ) {
  12415. console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' );
  12416. }
  12417. }
  12418. // validation checks for WebGL 1
  12419. if ( texture.format === DepthFormat && glInternalFormat === 6402 ) {
  12420. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  12421. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  12422. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  12423. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  12424. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  12425. texture.type = UnsignedShortType;
  12426. glType = utils.convert( texture.type );
  12427. }
  12428. }
  12429. if ( texture.format === DepthStencilFormat && glInternalFormat === 6402 ) {
  12430. // Depth stencil textures need the DEPTH_STENCIL internal format
  12431. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  12432. glInternalFormat = 34041;
  12433. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  12434. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  12435. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  12436. if ( texture.type !== UnsignedInt248Type ) {
  12437. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  12438. texture.type = UnsignedInt248Type;
  12439. glType = utils.convert( texture.type );
  12440. }
  12441. }
  12442. //
  12443. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  12444. } else if ( texture.isDataTexture ) {
  12445. // use manually created mipmaps if available
  12446. // if there are no manual mipmaps
  12447. // set 0 level mipmap and then use GL to generate other mipmap levels
  12448. if ( mipmaps.length > 0 && supportsMips ) {
  12449. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  12450. mipmap = mipmaps[ i ];
  12451. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  12452. }
  12453. texture.generateMipmaps = false;
  12454. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12455. } else {
  12456. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  12457. textureProperties.__maxMipLevel = 0;
  12458. }
  12459. } else if ( texture.isCompressedTexture ) {
  12460. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  12461. mipmap = mipmaps[ i ];
  12462. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  12463. if ( glFormat !== null ) {
  12464. state.compressedTexImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  12465. } else {
  12466. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  12467. }
  12468. } else {
  12469. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  12470. }
  12471. }
  12472. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12473. } else if ( texture.isDataTexture2DArray ) {
  12474. state.texImage3D( 35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  12475. textureProperties.__maxMipLevel = 0;
  12476. } else if ( texture.isDataTexture3D ) {
  12477. state.texImage3D( 32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  12478. textureProperties.__maxMipLevel = 0;
  12479. } else {
  12480. // regular Texture (image, video, canvas)
  12481. // use manually created mipmaps if available
  12482. // if there are no manual mipmaps
  12483. // set 0 level mipmap and then use GL to generate other mipmap levels
  12484. if ( mipmaps.length > 0 && supportsMips ) {
  12485. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  12486. mipmap = mipmaps[ i ];
  12487. state.texImage2D( 3553, i, glInternalFormat, glFormat, glType, mipmap );
  12488. }
  12489. texture.generateMipmaps = false;
  12490. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12491. } else {
  12492. state.texImage2D( 3553, 0, glInternalFormat, glFormat, glType, image );
  12493. textureProperties.__maxMipLevel = 0;
  12494. }
  12495. }
  12496. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  12497. generateMipmap( textureType, texture, image.width, image.height );
  12498. }
  12499. textureProperties.__version = texture.version;
  12500. if ( texture.onUpdate ) texture.onUpdate( texture );
  12501. }
  12502. function uploadCubeTexture( textureProperties, texture, slot ) {
  12503. if ( texture.image.length !== 6 ) return;
  12504. initTexture( textureProperties, texture );
  12505. state.activeTexture( 33984 + slot );
  12506. state.bindTexture( 34067, textureProperties.__webglTexture );
  12507. _gl.pixelStorei( 37440, texture.flipY );
  12508. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  12509. _gl.pixelStorei( 3317, texture.unpackAlignment );
  12510. _gl.pixelStorei( 37443, 0 );
  12511. const isCompressed = ( texture && ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture ) );
  12512. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  12513. const cubeImage = [];
  12514. for ( let i = 0; i < 6; i ++ ) {
  12515. if ( ! isCompressed && ! isDataTexture ) {
  12516. cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize );
  12517. } else {
  12518. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  12519. }
  12520. }
  12521. const image = cubeImage[ 0 ],
  12522. supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  12523. glFormat = utils.convert( texture.format ),
  12524. glType = utils.convert( texture.type ),
  12525. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  12526. setTextureParameters( 34067, texture, supportsMips );
  12527. let mipmaps;
  12528. if ( isCompressed ) {
  12529. for ( let i = 0; i < 6; i ++ ) {
  12530. mipmaps = cubeImage[ i ].mipmaps;
  12531. for ( let j = 0; j < mipmaps.length; j ++ ) {
  12532. const mipmap = mipmaps[ j ];
  12533. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  12534. if ( glFormat !== null ) {
  12535. state.compressedTexImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  12536. } else {
  12537. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  12538. }
  12539. } else {
  12540. state.texImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  12541. }
  12542. }
  12543. }
  12544. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12545. } else {
  12546. mipmaps = texture.mipmaps;
  12547. for ( let i = 0; i < 6; i ++ ) {
  12548. if ( isDataTexture ) {
  12549. state.texImage2D( 34069 + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  12550. for ( let j = 0; j < mipmaps.length; j ++ ) {
  12551. const mipmap = mipmaps[ j ];
  12552. const mipmapImage = mipmap.image[ i ].image;
  12553. state.texImage2D( 34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  12554. }
  12555. } else {
  12556. state.texImage2D( 34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  12557. for ( let j = 0; j < mipmaps.length; j ++ ) {
  12558. const mipmap = mipmaps[ j ];
  12559. state.texImage2D( 34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  12560. }
  12561. }
  12562. }
  12563. textureProperties.__maxMipLevel = mipmaps.length;
  12564. }
  12565. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  12566. // We assume images for cube map have the same size.
  12567. generateMipmap( 34067, texture, image.width, image.height );
  12568. }
  12569. textureProperties.__version = texture.version;
  12570. if ( texture.onUpdate ) texture.onUpdate( texture );
  12571. }
  12572. // Render targets
  12573. // Setup storage for target texture and bind it to correct framebuffer
  12574. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget ) {
  12575. const glFormat = utils.convert( texture.format );
  12576. const glType = utils.convert( texture.type );
  12577. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  12578. if ( textureTarget === 32879 || textureTarget === 35866 ) {
  12579. state.texImage3D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null );
  12580. } else {
  12581. state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  12582. }
  12583. state.bindFramebuffer( 36160, framebuffer );
  12584. _gl.framebufferTexture2D( 36160, attachment, textureTarget, properties.get( texture ).__webglTexture, 0 );
  12585. state.bindFramebuffer( 36160, null );
  12586. }
  12587. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  12588. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  12589. _gl.bindRenderbuffer( 36161, renderbuffer );
  12590. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  12591. let glInternalFormat = 33189;
  12592. if ( isMultisample ) {
  12593. const depthTexture = renderTarget.depthTexture;
  12594. if ( depthTexture && depthTexture.isDepthTexture ) {
  12595. if ( depthTexture.type === FloatType ) {
  12596. glInternalFormat = 36012;
  12597. } else if ( depthTexture.type === UnsignedIntType ) {
  12598. glInternalFormat = 33190;
  12599. }
  12600. }
  12601. const samples = getRenderTargetSamples( renderTarget );
  12602. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  12603. } else {
  12604. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  12605. }
  12606. _gl.framebufferRenderbuffer( 36160, 36096, 36161, renderbuffer );
  12607. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  12608. if ( isMultisample ) {
  12609. const samples = getRenderTargetSamples( renderTarget );
  12610. _gl.renderbufferStorageMultisample( 36161, samples, 35056, renderTarget.width, renderTarget.height );
  12611. } else {
  12612. _gl.renderbufferStorage( 36161, 34041, renderTarget.width, renderTarget.height );
  12613. }
  12614. _gl.framebufferRenderbuffer( 36160, 33306, 36161, renderbuffer );
  12615. } else {
  12616. // Use the first texture for MRT so far
  12617. const texture = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture[ 0 ] : renderTarget.texture;
  12618. const glFormat = utils.convert( texture.format );
  12619. const glType = utils.convert( texture.type );
  12620. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  12621. if ( isMultisample ) {
  12622. const samples = getRenderTargetSamples( renderTarget );
  12623. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  12624. } else {
  12625. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  12626. }
  12627. }
  12628. _gl.bindRenderbuffer( 36161, null );
  12629. }
  12630. // Setup resources for a Depth Texture for a FBO (needs an extension)
  12631. function setupDepthTexture( framebuffer, renderTarget ) {
  12632. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  12633. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  12634. state.bindFramebuffer( 36160, framebuffer );
  12635. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  12636. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  12637. }
  12638. // upload an empty depth texture with framebuffer size
  12639. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  12640. renderTarget.depthTexture.image.width !== renderTarget.width ||
  12641. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  12642. renderTarget.depthTexture.image.width = renderTarget.width;
  12643. renderTarget.depthTexture.image.height = renderTarget.height;
  12644. renderTarget.depthTexture.needsUpdate = true;
  12645. }
  12646. setTexture2D( renderTarget.depthTexture, 0 );
  12647. const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  12648. if ( renderTarget.depthTexture.format === DepthFormat ) {
  12649. _gl.framebufferTexture2D( 36160, 36096, 3553, webglDepthTexture, 0 );
  12650. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  12651. _gl.framebufferTexture2D( 36160, 33306, 3553, webglDepthTexture, 0 );
  12652. } else {
  12653. throw new Error( 'Unknown depthTexture format' );
  12654. }
  12655. }
  12656. // Setup GL resources for a non-texture depth buffer
  12657. function setupDepthRenderbuffer( renderTarget ) {
  12658. const renderTargetProperties = properties.get( renderTarget );
  12659. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  12660. if ( renderTarget.depthTexture ) {
  12661. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  12662. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  12663. } else {
  12664. if ( isCube ) {
  12665. renderTargetProperties.__webglDepthbuffer = [];
  12666. for ( let i = 0; i < 6; i ++ ) {
  12667. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer[ i ] );
  12668. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  12669. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  12670. }
  12671. } else {
  12672. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  12673. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  12674. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  12675. }
  12676. }
  12677. state.bindFramebuffer( 36160, null );
  12678. }
  12679. // Set up GL resources for the render target
  12680. function setupRenderTarget( renderTarget ) {
  12681. const texture = renderTarget.texture;
  12682. const renderTargetProperties = properties.get( renderTarget );
  12683. const textureProperties = properties.get( texture );
  12684. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  12685. if ( renderTarget.isWebGLMultipleRenderTargets !== true ) {
  12686. textureProperties.__webglTexture = _gl.createTexture();
  12687. textureProperties.__version = texture.version;
  12688. info.memory.textures ++;
  12689. }
  12690. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  12691. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  12692. const isMultisample = ( renderTarget.isWebGLMultisampleRenderTarget === true );
  12693. const isRenderTarget3D = texture.isDataTexture3D || texture.isDataTexture2DArray;
  12694. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  12695. // Handles WebGL2 RGBFormat fallback - #18858
  12696. if ( isWebGL2 && texture.format === RGBFormat && ( texture.type === FloatType || texture.type === HalfFloatType ) ) {
  12697. texture.format = RGBAFormat;
  12698. console.warn( 'THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.' );
  12699. }
  12700. // Setup framebuffer
  12701. if ( isCube ) {
  12702. renderTargetProperties.__webglFramebuffer = [];
  12703. for ( let i = 0; i < 6; i ++ ) {
  12704. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  12705. }
  12706. } else {
  12707. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  12708. if ( isMultipleRenderTargets ) {
  12709. if ( capabilities.drawBuffers ) {
  12710. const textures = renderTarget.texture;
  12711. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  12712. const attachmentProperties = properties.get( textures[ i ] );
  12713. if ( attachmentProperties.__webglTexture === undefined ) {
  12714. attachmentProperties.__webglTexture = _gl.createTexture();
  12715. info.memory.textures ++;
  12716. }
  12717. }
  12718. } else {
  12719. console.warn( 'THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.' );
  12720. }
  12721. } else if ( isMultisample ) {
  12722. if ( isWebGL2 ) {
  12723. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  12724. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  12725. _gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer );
  12726. const glFormat = utils.convert( texture.format );
  12727. const glType = utils.convert( texture.type );
  12728. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  12729. const samples = getRenderTargetSamples( renderTarget );
  12730. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  12731. state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  12732. _gl.framebufferRenderbuffer( 36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer );
  12733. _gl.bindRenderbuffer( 36161, null );
  12734. if ( renderTarget.depthBuffer ) {
  12735. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  12736. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  12737. }
  12738. state.bindFramebuffer( 36160, null );
  12739. } else {
  12740. console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
  12741. }
  12742. }
  12743. }
  12744. // Setup color buffer
  12745. if ( isCube ) {
  12746. state.bindTexture( 34067, textureProperties.__webglTexture );
  12747. setTextureParameters( 34067, texture, supportsMips );
  12748. for ( let i = 0; i < 6; i ++ ) {
  12749. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, 36064, 34069 + i );
  12750. }
  12751. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  12752. generateMipmap( 34067, texture, renderTarget.width, renderTarget.height );
  12753. }
  12754. state.bindTexture( 34067, null );
  12755. } else if ( isMultipleRenderTargets ) {
  12756. const textures = renderTarget.texture;
  12757. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  12758. const attachment = textures[ i ];
  12759. const attachmentProperties = properties.get( attachment );
  12760. state.bindTexture( 3553, attachmentProperties.__webglTexture );
  12761. setTextureParameters( 3553, attachment, supportsMips );
  12762. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, 36064 + i, 3553 );
  12763. if ( textureNeedsGenerateMipmaps( attachment, supportsMips ) ) {
  12764. generateMipmap( 3553, attachment, renderTarget.width, renderTarget.height );
  12765. }
  12766. }
  12767. state.bindTexture( 3553, null );
  12768. } else {
  12769. let glTextureType = 3553;
  12770. if ( isRenderTarget3D ) {
  12771. // Render targets containing layers, i.e: Texture 3D and 2d arrays
  12772. if ( isWebGL2 ) {
  12773. const isTexture3D = texture.isDataTexture3D;
  12774. glTextureType = isTexture3D ? 32879 : 35866;
  12775. } else {
  12776. console.warn( 'THREE.DataTexture3D and THREE.DataTexture2DArray only supported with WebGL2.' );
  12777. }
  12778. }
  12779. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  12780. setTextureParameters( glTextureType, texture, supportsMips );
  12781. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, 36064, glTextureType );
  12782. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  12783. generateMipmap( glTextureType, texture, renderTarget.width, renderTarget.height, renderTarget.depth );
  12784. }
  12785. state.bindTexture( glTextureType, null );
  12786. }
  12787. // Setup depth and stencil buffers
  12788. if ( renderTarget.depthBuffer ) {
  12789. setupDepthRenderbuffer( renderTarget );
  12790. }
  12791. }
  12792. function updateRenderTargetMipmap( renderTarget ) {
  12793. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  12794. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  12795. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  12796. const texture = textures[ i ];
  12797. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  12798. const target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553;
  12799. const webglTexture = properties.get( texture ).__webglTexture;
  12800. state.bindTexture( target, webglTexture );
  12801. generateMipmap( target, texture, renderTarget.width, renderTarget.height );
  12802. state.bindTexture( target, null );
  12803. }
  12804. }
  12805. }
  12806. function updateMultisampleRenderTarget( renderTarget ) {
  12807. if ( renderTarget.isWebGLMultisampleRenderTarget ) {
  12808. if ( isWebGL2 ) {
  12809. const width = renderTarget.width;
  12810. const height = renderTarget.height;
  12811. let mask = 16384;
  12812. if ( renderTarget.depthBuffer ) mask |= 256;
  12813. if ( renderTarget.stencilBuffer ) mask |= 1024;
  12814. const renderTargetProperties = properties.get( renderTarget );
  12815. state.bindFramebuffer( 36008, renderTargetProperties.__webglMultisampledFramebuffer );
  12816. state.bindFramebuffer( 36009, renderTargetProperties.__webglFramebuffer );
  12817. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 );
  12818. state.bindFramebuffer( 36008, null );
  12819. state.bindFramebuffer( 36009, renderTargetProperties.__webglMultisampledFramebuffer );
  12820. } else {
  12821. console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
  12822. }
  12823. }
  12824. }
  12825. function getRenderTargetSamples( renderTarget ) {
  12826. return ( isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ) ?
  12827. Math.min( maxSamples, renderTarget.samples ) : 0;
  12828. }
  12829. function updateVideoTexture( texture ) {
  12830. const frame = info.render.frame;
  12831. // Check the last frame we updated the VideoTexture
  12832. if ( _videoTextures.get( texture ) !== frame ) {
  12833. _videoTextures.set( texture, frame );
  12834. texture.update();
  12835. }
  12836. }
  12837. // backwards compatibility
  12838. let warnedTexture2D = false;
  12839. let warnedTextureCube = false;
  12840. function safeSetTexture2D( texture, slot ) {
  12841. if ( texture && texture.isWebGLRenderTarget ) {
  12842. if ( warnedTexture2D === false ) {
  12843. console.warn( 'THREE.WebGLTextures.safeSetTexture2D: don\'t use render targets as textures. Use their .texture property instead.' );
  12844. warnedTexture2D = true;
  12845. }
  12846. texture = texture.texture;
  12847. }
  12848. setTexture2D( texture, slot );
  12849. }
  12850. function safeSetTextureCube( texture, slot ) {
  12851. if ( texture && texture.isWebGLCubeRenderTarget ) {
  12852. if ( warnedTextureCube === false ) {
  12853. console.warn( 'THREE.WebGLTextures.safeSetTextureCube: don\'t use cube render targets as textures. Use their .texture property instead.' );
  12854. warnedTextureCube = true;
  12855. }
  12856. texture = texture.texture;
  12857. }
  12858. setTextureCube( texture, slot );
  12859. }
  12860. //
  12861. this.allocateTextureUnit = allocateTextureUnit;
  12862. this.resetTextureUnits = resetTextureUnits;
  12863. this.setTexture2D = setTexture2D;
  12864. this.setTexture2DArray = setTexture2DArray;
  12865. this.setTexture3D = setTexture3D;
  12866. this.setTextureCube = setTextureCube;
  12867. this.setupRenderTarget = setupRenderTarget;
  12868. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  12869. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  12870. this.safeSetTexture2D = safeSetTexture2D;
  12871. this.safeSetTextureCube = safeSetTextureCube;
  12872. }
  12873. function WebGLUtils( gl, extensions, capabilities ) {
  12874. const isWebGL2 = capabilities.isWebGL2;
  12875. function convert( p ) {
  12876. let extension;
  12877. if ( p === UnsignedByteType ) return 5121;
  12878. if ( p === UnsignedShort4444Type ) return 32819;
  12879. if ( p === UnsignedShort5551Type ) return 32820;
  12880. if ( p === UnsignedShort565Type ) return 33635;
  12881. if ( p === ByteType ) return 5120;
  12882. if ( p === ShortType ) return 5122;
  12883. if ( p === UnsignedShortType ) return 5123;
  12884. if ( p === IntType ) return 5124;
  12885. if ( p === UnsignedIntType ) return 5125;
  12886. if ( p === FloatType ) return 5126;
  12887. if ( p === HalfFloatType ) {
  12888. if ( isWebGL2 ) return 5131;
  12889. extension = extensions.get( 'OES_texture_half_float' );
  12890. if ( extension !== null ) {
  12891. return extension.HALF_FLOAT_OES;
  12892. } else {
  12893. return null;
  12894. }
  12895. }
  12896. if ( p === AlphaFormat ) return 6406;
  12897. if ( p === RGBFormat ) return 6407;
  12898. if ( p === RGBAFormat ) return 6408;
  12899. if ( p === LuminanceFormat ) return 6409;
  12900. if ( p === LuminanceAlphaFormat ) return 6410;
  12901. if ( p === DepthFormat ) return 6402;
  12902. if ( p === DepthStencilFormat ) return 34041;
  12903. if ( p === RedFormat ) return 6403;
  12904. // WebGL2 formats.
  12905. if ( p === RedIntegerFormat ) return 36244;
  12906. if ( p === RGFormat ) return 33319;
  12907. if ( p === RGIntegerFormat ) return 33320;
  12908. if ( p === RGBIntegerFormat ) return 36248;
  12909. if ( p === RGBAIntegerFormat ) return 36249;
  12910. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  12911. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  12912. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  12913. if ( extension !== null ) {
  12914. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  12915. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  12916. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  12917. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  12918. } else {
  12919. return null;
  12920. }
  12921. }
  12922. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  12923. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  12924. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  12925. if ( extension !== null ) {
  12926. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  12927. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  12928. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  12929. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  12930. } else {
  12931. return null;
  12932. }
  12933. }
  12934. if ( p === RGB_ETC1_Format ) {
  12935. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  12936. if ( extension !== null ) {
  12937. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  12938. } else {
  12939. return null;
  12940. }
  12941. }
  12942. if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  12943. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  12944. if ( extension !== null ) {
  12945. if ( p === RGB_ETC2_Format ) return extension.COMPRESSED_RGB8_ETC2;
  12946. if ( p === RGBA_ETC2_EAC_Format ) return extension.COMPRESSED_RGBA8_ETC2_EAC;
  12947. }
  12948. }
  12949. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  12950. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  12951. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  12952. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  12953. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ||
  12954. p === SRGB8_ALPHA8_ASTC_4x4_Format || p === SRGB8_ALPHA8_ASTC_5x4_Format || p === SRGB8_ALPHA8_ASTC_5x5_Format ||
  12955. p === SRGB8_ALPHA8_ASTC_6x5_Format || p === SRGB8_ALPHA8_ASTC_6x6_Format || p === SRGB8_ALPHA8_ASTC_8x5_Format ||
  12956. p === SRGB8_ALPHA8_ASTC_8x6_Format || p === SRGB8_ALPHA8_ASTC_8x8_Format || p === SRGB8_ALPHA8_ASTC_10x5_Format ||
  12957. p === SRGB8_ALPHA8_ASTC_10x6_Format || p === SRGB8_ALPHA8_ASTC_10x8_Format || p === SRGB8_ALPHA8_ASTC_10x10_Format ||
  12958. p === SRGB8_ALPHA8_ASTC_12x10_Format || p === SRGB8_ALPHA8_ASTC_12x12_Format ) {
  12959. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  12960. if ( extension !== null ) {
  12961. // TODO Complete?
  12962. return p;
  12963. } else {
  12964. return null;
  12965. }
  12966. }
  12967. if ( p === RGBA_BPTC_Format ) {
  12968. extension = extensions.get( 'EXT_texture_compression_bptc' );
  12969. if ( extension !== null ) {
  12970. // TODO Complete?
  12971. return p;
  12972. } else {
  12973. return null;
  12974. }
  12975. }
  12976. if ( p === UnsignedInt248Type ) {
  12977. if ( isWebGL2 ) return 34042;
  12978. extension = extensions.get( 'WEBGL_depth_texture' );
  12979. if ( extension !== null ) {
  12980. return extension.UNSIGNED_INT_24_8_WEBGL;
  12981. } else {
  12982. return null;
  12983. }
  12984. }
  12985. }
  12986. return { convert: convert };
  12987. }
  12988. class ArrayCamera extends PerspectiveCamera {
  12989. constructor( array = [] ) {
  12990. super();
  12991. this.cameras = array;
  12992. }
  12993. }
  12994. ArrayCamera.prototype.isArrayCamera = true;
  12995. class Group$1 extends Object3D {
  12996. constructor() {
  12997. super();
  12998. this.type = 'Group';
  12999. }
  13000. }
  13001. Group$1.prototype.isGroup = true;
  13002. const _moveEvent = { type: 'move' };
  13003. class WebXRController {
  13004. constructor() {
  13005. this._targetRay = null;
  13006. this._grip = null;
  13007. this._hand = null;
  13008. }
  13009. getHandSpace() {
  13010. if ( this._hand === null ) {
  13011. this._hand = new Group$1();
  13012. this._hand.matrixAutoUpdate = false;
  13013. this._hand.visible = false;
  13014. this._hand.joints = {};
  13015. this._hand.inputState = { pinching: false };
  13016. }
  13017. return this._hand;
  13018. }
  13019. getTargetRaySpace() {
  13020. if ( this._targetRay === null ) {
  13021. this._targetRay = new Group$1();
  13022. this._targetRay.matrixAutoUpdate = false;
  13023. this._targetRay.visible = false;
  13024. this._targetRay.hasLinearVelocity = false;
  13025. this._targetRay.linearVelocity = new Vector3();
  13026. this._targetRay.hasAngularVelocity = false;
  13027. this._targetRay.angularVelocity = new Vector3();
  13028. }
  13029. return this._targetRay;
  13030. }
  13031. getGripSpace() {
  13032. if ( this._grip === null ) {
  13033. this._grip = new Group$1();
  13034. this._grip.matrixAutoUpdate = false;
  13035. this._grip.visible = false;
  13036. this._grip.hasLinearVelocity = false;
  13037. this._grip.linearVelocity = new Vector3();
  13038. this._grip.hasAngularVelocity = false;
  13039. this._grip.angularVelocity = new Vector3();
  13040. }
  13041. return this._grip;
  13042. }
  13043. dispatchEvent( event ) {
  13044. if ( this._targetRay !== null ) {
  13045. this._targetRay.dispatchEvent( event );
  13046. }
  13047. if ( this._grip !== null ) {
  13048. this._grip.dispatchEvent( event );
  13049. }
  13050. if ( this._hand !== null ) {
  13051. this._hand.dispatchEvent( event );
  13052. }
  13053. return this;
  13054. }
  13055. disconnect( inputSource ) {
  13056. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  13057. if ( this._targetRay !== null ) {
  13058. this._targetRay.visible = false;
  13059. }
  13060. if ( this._grip !== null ) {
  13061. this._grip.visible = false;
  13062. }
  13063. if ( this._hand !== null ) {
  13064. this._hand.visible = false;
  13065. }
  13066. return this;
  13067. }
  13068. update( inputSource, frame, referenceSpace ) {
  13069. let inputPose = null;
  13070. let gripPose = null;
  13071. let handPose = null;
  13072. const targetRay = this._targetRay;
  13073. const grip = this._grip;
  13074. const hand = this._hand;
  13075. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  13076. if ( targetRay !== null ) {
  13077. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  13078. if ( inputPose !== null ) {
  13079. targetRay.matrix.fromArray( inputPose.transform.matrix );
  13080. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  13081. if ( inputPose.linearVelocity ) {
  13082. targetRay.hasLinearVelocity = true;
  13083. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  13084. } else {
  13085. targetRay.hasLinearVelocity = false;
  13086. }
  13087. if ( inputPose.angularVelocity ) {
  13088. targetRay.hasAngularVelocity = true;
  13089. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  13090. } else {
  13091. targetRay.hasAngularVelocity = false;
  13092. }
  13093. this.dispatchEvent( _moveEvent );
  13094. }
  13095. }
  13096. if ( hand && inputSource.hand ) {
  13097. handPose = true;
  13098. for ( const inputjoint of inputSource.hand.values() ) {
  13099. // Update the joints groups with the XRJoint poses
  13100. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  13101. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  13102. // The transform of this joint will be updated with the joint pose on each frame
  13103. const joint = new Group$1();
  13104. joint.matrixAutoUpdate = false;
  13105. joint.visible = false;
  13106. hand.joints[ inputjoint.jointName ] = joint;
  13107. // ??
  13108. hand.add( joint );
  13109. }
  13110. const joint = hand.joints[ inputjoint.jointName ];
  13111. if ( jointPose !== null ) {
  13112. joint.matrix.fromArray( jointPose.transform.matrix );
  13113. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  13114. joint.jointRadius = jointPose.radius;
  13115. }
  13116. joint.visible = jointPose !== null;
  13117. }
  13118. // Custom events
  13119. // Check pinchz
  13120. const indexTip = hand.joints[ 'index-finger-tip' ];
  13121. const thumbTip = hand.joints[ 'thumb-tip' ];
  13122. const distance = indexTip.position.distanceTo( thumbTip.position );
  13123. const distanceToPinch = 0.02;
  13124. const threshold = 0.005;
  13125. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  13126. hand.inputState.pinching = false;
  13127. this.dispatchEvent( {
  13128. type: 'pinchend',
  13129. handedness: inputSource.handedness,
  13130. target: this
  13131. } );
  13132. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  13133. hand.inputState.pinching = true;
  13134. this.dispatchEvent( {
  13135. type: 'pinchstart',
  13136. handedness: inputSource.handedness,
  13137. target: this
  13138. } );
  13139. }
  13140. } else {
  13141. if ( grip !== null && inputSource.gripSpace ) {
  13142. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  13143. if ( gripPose !== null ) {
  13144. grip.matrix.fromArray( gripPose.transform.matrix );
  13145. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  13146. if ( gripPose.linearVelocity ) {
  13147. grip.hasLinearVelocity = true;
  13148. grip.linearVelocity.copy( gripPose.linearVelocity );
  13149. } else {
  13150. grip.hasLinearVelocity = false;
  13151. }
  13152. if ( gripPose.angularVelocity ) {
  13153. grip.hasAngularVelocity = true;
  13154. grip.angularVelocity.copy( gripPose.angularVelocity );
  13155. } else {
  13156. grip.hasAngularVelocity = false;
  13157. }
  13158. }
  13159. }
  13160. }
  13161. }
  13162. if ( targetRay !== null ) {
  13163. targetRay.visible = ( inputPose !== null );
  13164. }
  13165. if ( grip !== null ) {
  13166. grip.visible = ( gripPose !== null );
  13167. }
  13168. if ( hand !== null ) {
  13169. hand.visible = ( handPose !== null );
  13170. }
  13171. return this;
  13172. }
  13173. }
  13174. class WebXRManager extends EventDispatcher {
  13175. constructor( renderer, gl ) {
  13176. super();
  13177. const scope = this;
  13178. const state = renderer.state;
  13179. let session = null;
  13180. let framebufferScaleFactor = 1.0;
  13181. let referenceSpace = null;
  13182. let referenceSpaceType = 'local-floor';
  13183. let pose = null;
  13184. let glBinding = null;
  13185. let glFramebuffer = null;
  13186. let glProjLayer = null;
  13187. const controllers = [];
  13188. const inputSourcesMap = new Map();
  13189. //
  13190. const cameraL = new PerspectiveCamera();
  13191. cameraL.layers.enable( 1 );
  13192. cameraL.viewport = new Vector4();
  13193. const cameraR = new PerspectiveCamera();
  13194. cameraR.layers.enable( 2 );
  13195. cameraR.viewport = new Vector4();
  13196. const cameras = [ cameraL, cameraR ];
  13197. const cameraVR = new ArrayCamera();
  13198. cameraVR.layers.enable( 1 );
  13199. cameraVR.layers.enable( 2 );
  13200. let _currentDepthNear = null;
  13201. let _currentDepthFar = null;
  13202. //
  13203. this.cameraAutoUpdate = true;
  13204. this.enabled = false;
  13205. this.isPresenting = false;
  13206. this.getController = function ( index ) {
  13207. let controller = controllers[ index ];
  13208. if ( controller === undefined ) {
  13209. controller = new WebXRController();
  13210. controllers[ index ] = controller;
  13211. }
  13212. return controller.getTargetRaySpace();
  13213. };
  13214. this.getControllerGrip = function ( index ) {
  13215. let controller = controllers[ index ];
  13216. if ( controller === undefined ) {
  13217. controller = new WebXRController();
  13218. controllers[ index ] = controller;
  13219. }
  13220. return controller.getGripSpace();
  13221. };
  13222. this.getHand = function ( index ) {
  13223. let controller = controllers[ index ];
  13224. if ( controller === undefined ) {
  13225. controller = new WebXRController();
  13226. controllers[ index ] = controller;
  13227. }
  13228. return controller.getHandSpace();
  13229. };
  13230. //
  13231. function onSessionEvent( event ) {
  13232. const controller = inputSourcesMap.get( event.inputSource );
  13233. if ( controller ) {
  13234. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  13235. }
  13236. }
  13237. function onSessionEnd() {
  13238. inputSourcesMap.forEach( function ( controller, inputSource ) {
  13239. controller.disconnect( inputSource );
  13240. } );
  13241. inputSourcesMap.clear();
  13242. _currentDepthNear = null;
  13243. _currentDepthFar = null;
  13244. // restore framebuffer/rendering state
  13245. state.bindXRFramebuffer( null );
  13246. renderer.setRenderTarget( renderer.getRenderTarget() );
  13247. //
  13248. animation.stop();
  13249. scope.isPresenting = false;
  13250. scope.dispatchEvent( { type: 'sessionend' } );
  13251. }
  13252. this.setFramebufferScaleFactor = function ( value ) {
  13253. framebufferScaleFactor = value;
  13254. if ( scope.isPresenting === true ) {
  13255. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  13256. }
  13257. };
  13258. this.setReferenceSpaceType = function ( value ) {
  13259. referenceSpaceType = value;
  13260. if ( scope.isPresenting === true ) {
  13261. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  13262. }
  13263. };
  13264. this.getReferenceSpace = function () {
  13265. return referenceSpace;
  13266. };
  13267. this.getSession = function () {
  13268. return session;
  13269. };
  13270. this.setSession = async function ( value ) {
  13271. session = value;
  13272. if ( session !== null ) {
  13273. session.addEventListener( 'select', onSessionEvent );
  13274. session.addEventListener( 'selectstart', onSessionEvent );
  13275. session.addEventListener( 'selectend', onSessionEvent );
  13276. session.addEventListener( 'squeeze', onSessionEvent );
  13277. session.addEventListener( 'squeezestart', onSessionEvent );
  13278. session.addEventListener( 'squeezeend', onSessionEvent );
  13279. session.addEventListener( 'end', onSessionEnd );
  13280. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  13281. const attributes = gl.getContextAttributes();
  13282. if ( attributes.xrCompatible !== true ) {
  13283. await gl.makeXRCompatible();
  13284. }
  13285. if ( session.renderState.layers === undefined ) {
  13286. const layerInit = {
  13287. antialias: attributes.antialias,
  13288. alpha: attributes.alpha,
  13289. depth: attributes.depth,
  13290. stencil: attributes.stencil,
  13291. framebufferScaleFactor: framebufferScaleFactor
  13292. };
  13293. // eslint-disable-next-line no-undef
  13294. const baseLayer = new XRWebGLLayer( session, gl, layerInit );
  13295. session.updateRenderState( { baseLayer: baseLayer } );
  13296. } else {
  13297. let depthFormat = 0;
  13298. if ( attributes.depth ) {
  13299. depthFormat = attributes.stencil ? 34041 : 6402;
  13300. }
  13301. const projectionlayerInit = {
  13302. colorFormat: attributes.alpha ? 6408 : 6407,
  13303. depthFormat: depthFormat,
  13304. scaleFactor: framebufferScaleFactor
  13305. };
  13306. // eslint-disable-next-line no-undef
  13307. glBinding = new XRWebGLBinding( session, gl );
  13308. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  13309. glFramebuffer = gl.createFramebuffer();
  13310. session.updateRenderState( { layers: [ glProjLayer ] } );
  13311. }
  13312. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  13313. animation.setContext( session );
  13314. animation.start();
  13315. scope.isPresenting = true;
  13316. scope.dispatchEvent( { type: 'sessionstart' } );
  13317. }
  13318. };
  13319. function onInputSourcesChange( event ) {
  13320. const inputSources = session.inputSources;
  13321. // Assign inputSources to available controllers
  13322. for ( let i = 0; i < controllers.length; i ++ ) {
  13323. inputSourcesMap.set( inputSources[ i ], controllers[ i ] );
  13324. }
  13325. // Notify disconnected
  13326. for ( let i = 0; i < event.removed.length; i ++ ) {
  13327. const inputSource = event.removed[ i ];
  13328. const controller = inputSourcesMap.get( inputSource );
  13329. if ( controller ) {
  13330. controller.dispatchEvent( { type: 'disconnected', data: inputSource } );
  13331. inputSourcesMap.delete( inputSource );
  13332. }
  13333. }
  13334. // Notify connected
  13335. for ( let i = 0; i < event.added.length; i ++ ) {
  13336. const inputSource = event.added[ i ];
  13337. const controller = inputSourcesMap.get( inputSource );
  13338. if ( controller ) {
  13339. controller.dispatchEvent( { type: 'connected', data: inputSource } );
  13340. }
  13341. }
  13342. }
  13343. //
  13344. const cameraLPos = new Vector3();
  13345. const cameraRPos = new Vector3();
  13346. /**
  13347. * Assumes 2 cameras that are parallel and share an X-axis, and that
  13348. * the cameras' projection and world matrices have already been set.
  13349. * And that near and far planes are identical for both cameras.
  13350. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  13351. */
  13352. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  13353. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  13354. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  13355. const ipd = cameraLPos.distanceTo( cameraRPos );
  13356. const projL = cameraL.projectionMatrix.elements;
  13357. const projR = cameraR.projectionMatrix.elements;
  13358. // VR systems will have identical far and near planes, and
  13359. // most likely identical top and bottom frustum extents.
  13360. // Use the left camera for these values.
  13361. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  13362. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  13363. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  13364. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  13365. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  13366. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  13367. const left = near * leftFov;
  13368. const right = near * rightFov;
  13369. // Calculate the new camera's position offset from the
  13370. // left camera. xOffset should be roughly half `ipd`.
  13371. const zOffset = ipd / ( - leftFov + rightFov );
  13372. const xOffset = zOffset * - leftFov;
  13373. // TODO: Better way to apply this offset?
  13374. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  13375. camera.translateX( xOffset );
  13376. camera.translateZ( zOffset );
  13377. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  13378. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  13379. // Find the union of the frustum values of the cameras and scale
  13380. // the values so that the near plane's position does not change in world space,
  13381. // although must now be relative to the new union camera.
  13382. const near2 = near + zOffset;
  13383. const far2 = far + zOffset;
  13384. const left2 = left - xOffset;
  13385. const right2 = right + ( ipd - xOffset );
  13386. const top2 = topFov * far / far2 * near2;
  13387. const bottom2 = bottomFov * far / far2 * near2;
  13388. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  13389. }
  13390. function updateCamera( camera, parent ) {
  13391. if ( parent === null ) {
  13392. camera.matrixWorld.copy( camera.matrix );
  13393. } else {
  13394. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  13395. }
  13396. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  13397. }
  13398. this.updateCamera = function ( camera ) {
  13399. if ( session === null ) return;
  13400. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  13401. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  13402. if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) {
  13403. // Note that the new renderState won't apply until the next frame. See #18320
  13404. session.updateRenderState( {
  13405. depthNear: cameraVR.near,
  13406. depthFar: cameraVR.far
  13407. } );
  13408. _currentDepthNear = cameraVR.near;
  13409. _currentDepthFar = cameraVR.far;
  13410. }
  13411. const parent = camera.parent;
  13412. const cameras = cameraVR.cameras;
  13413. updateCamera( cameraVR, parent );
  13414. for ( let i = 0; i < cameras.length; i ++ ) {
  13415. updateCamera( cameras[ i ], parent );
  13416. }
  13417. cameraVR.matrixWorld.decompose( cameraVR.position, cameraVR.quaternion, cameraVR.scale );
  13418. // update user camera and its children
  13419. camera.position.copy( cameraVR.position );
  13420. camera.quaternion.copy( cameraVR.quaternion );
  13421. camera.scale.copy( cameraVR.scale );
  13422. camera.matrix.copy( cameraVR.matrix );
  13423. camera.matrixWorld.copy( cameraVR.matrixWorld );
  13424. const children = camera.children;
  13425. for ( let i = 0, l = children.length; i < l; i ++ ) {
  13426. children[ i ].updateMatrixWorld( true );
  13427. }
  13428. // update projection matrix for proper view frustum culling
  13429. if ( cameras.length === 2 ) {
  13430. setProjectionFromUnion( cameraVR, cameraL, cameraR );
  13431. } else {
  13432. // assume single camera setup (AR)
  13433. cameraVR.projectionMatrix.copy( cameraL.projectionMatrix );
  13434. }
  13435. };
  13436. this.getCamera = function () {
  13437. return cameraVR;
  13438. };
  13439. // Animation Loop
  13440. let onAnimationFrameCallback = null;
  13441. function onAnimationFrame( time, frame ) {
  13442. pose = frame.getViewerPose( referenceSpace );
  13443. if ( pose !== null ) {
  13444. const views = pose.views;
  13445. const baseLayer = session.renderState.baseLayer;
  13446. if ( session.renderState.layers === undefined ) {
  13447. state.bindXRFramebuffer( baseLayer.framebuffer );
  13448. }
  13449. let cameraVRNeedsUpdate = false;
  13450. // check if it's necessary to rebuild cameraVR's camera list
  13451. if ( views.length !== cameraVR.cameras.length ) {
  13452. cameraVR.cameras.length = 0;
  13453. cameraVRNeedsUpdate = true;
  13454. }
  13455. for ( let i = 0; i < views.length; i ++ ) {
  13456. const view = views[ i ];
  13457. let viewport = null;
  13458. if ( session.renderState.layers === undefined ) {
  13459. viewport = baseLayer.getViewport( view );
  13460. } else {
  13461. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  13462. state.bindXRFramebuffer( glFramebuffer );
  13463. gl.framebufferTexture2D( 36160, 36064, 3553, glSubImage.colorTexture, 0 );
  13464. if ( glSubImage.depthStencilTexture !== undefined ) {
  13465. gl.framebufferTexture2D( 36160, 36096, 3553, glSubImage.depthStencilTexture, 0 );
  13466. }
  13467. viewport = glSubImage.viewport;
  13468. }
  13469. const camera = cameras[ i ];
  13470. camera.matrix.fromArray( view.transform.matrix );
  13471. camera.projectionMatrix.fromArray( view.projectionMatrix );
  13472. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  13473. if ( i === 0 ) {
  13474. cameraVR.matrix.copy( camera.matrix );
  13475. }
  13476. if ( cameraVRNeedsUpdate === true ) {
  13477. cameraVR.cameras.push( camera );
  13478. }
  13479. }
  13480. }
  13481. //
  13482. const inputSources = session.inputSources;
  13483. for ( let i = 0; i < controllers.length; i ++ ) {
  13484. const controller = controllers[ i ];
  13485. const inputSource = inputSources[ i ];
  13486. controller.update( inputSource, frame, referenceSpace );
  13487. }
  13488. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  13489. }
  13490. const animation = new WebGLAnimation();
  13491. animation.setAnimationLoop( onAnimationFrame );
  13492. this.setAnimationLoop = function ( callback ) {
  13493. onAnimationFrameCallback = callback;
  13494. };
  13495. this.dispose = function () {};
  13496. }
  13497. }
  13498. function WebGLMaterials( properties ) {
  13499. function refreshFogUniforms( uniforms, fog ) {
  13500. uniforms.fogColor.value.copy( fog.color );
  13501. if ( fog.isFog ) {
  13502. uniforms.fogNear.value = fog.near;
  13503. uniforms.fogFar.value = fog.far;
  13504. } else if ( fog.isFogExp2 ) {
  13505. uniforms.fogDensity.value = fog.density;
  13506. }
  13507. }
  13508. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  13509. if ( material.isMeshBasicMaterial ) {
  13510. refreshUniformsCommon( uniforms, material );
  13511. } else if ( material.isMeshLambertMaterial ) {
  13512. refreshUniformsCommon( uniforms, material );
  13513. refreshUniformsLambert( uniforms, material );
  13514. } else if ( material.isMeshToonMaterial ) {
  13515. refreshUniformsCommon( uniforms, material );
  13516. refreshUniformsToon( uniforms, material );
  13517. } else if ( material.isMeshPhongMaterial ) {
  13518. refreshUniformsCommon( uniforms, material );
  13519. refreshUniformsPhong( uniforms, material );
  13520. } else if ( material.isMeshStandardMaterial ) {
  13521. refreshUniformsCommon( uniforms, material );
  13522. if ( material.isMeshPhysicalMaterial ) {
  13523. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  13524. } else {
  13525. refreshUniformsStandard( uniforms, material );
  13526. }
  13527. } else if ( material.isMeshMatcapMaterial ) {
  13528. refreshUniformsCommon( uniforms, material );
  13529. refreshUniformsMatcap( uniforms, material );
  13530. } else if ( material.isMeshDepthMaterial ) {
  13531. refreshUniformsCommon( uniforms, material );
  13532. refreshUniformsDepth( uniforms, material );
  13533. } else if ( material.isMeshDistanceMaterial ) {
  13534. refreshUniformsCommon( uniforms, material );
  13535. refreshUniformsDistance( uniforms, material );
  13536. } else if ( material.isMeshNormalMaterial ) {
  13537. refreshUniformsCommon( uniforms, material );
  13538. refreshUniformsNormal( uniforms, material );
  13539. } else if ( material.isLineBasicMaterial ) {
  13540. refreshUniformsLine( uniforms, material );
  13541. if ( material.isLineDashedMaterial ) {
  13542. refreshUniformsDash( uniforms, material );
  13543. }
  13544. } else if ( material.isPointsMaterial ) {
  13545. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  13546. } else if ( material.isSpriteMaterial ) {
  13547. refreshUniformsSprites( uniforms, material );
  13548. } else if ( material.isShadowMaterial ) {
  13549. uniforms.color.value.copy( material.color );
  13550. uniforms.opacity.value = material.opacity;
  13551. } else if ( material.isShaderMaterial ) {
  13552. material.uniformsNeedUpdate = false; // #15581
  13553. }
  13554. }
  13555. function refreshUniformsCommon( uniforms, material ) {
  13556. uniforms.opacity.value = material.opacity;
  13557. if ( material.color ) {
  13558. uniforms.diffuse.value.copy( material.color );
  13559. }
  13560. if ( material.emissive ) {
  13561. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  13562. }
  13563. if ( material.map ) {
  13564. uniforms.map.value = material.map;
  13565. }
  13566. if ( material.alphaMap ) {
  13567. uniforms.alphaMap.value = material.alphaMap;
  13568. }
  13569. if ( material.specularMap ) {
  13570. uniforms.specularMap.value = material.specularMap;
  13571. }
  13572. const envMap = properties.get( material ).envMap;
  13573. if ( envMap ) {
  13574. uniforms.envMap.value = envMap;
  13575. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap._needsFlipEnvMap ) ? - 1 : 1;
  13576. uniforms.reflectivity.value = material.reflectivity;
  13577. uniforms.refractionRatio.value = material.refractionRatio;
  13578. const maxMipLevel = properties.get( envMap ).__maxMipLevel;
  13579. if ( maxMipLevel !== undefined ) {
  13580. uniforms.maxMipLevel.value = maxMipLevel;
  13581. }
  13582. }
  13583. if ( material.lightMap ) {
  13584. uniforms.lightMap.value = material.lightMap;
  13585. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  13586. }
  13587. if ( material.aoMap ) {
  13588. uniforms.aoMap.value = material.aoMap;
  13589. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  13590. }
  13591. // uv repeat and offset setting priorities
  13592. // 1. color map
  13593. // 2. specular map
  13594. // 3. displacementMap map
  13595. // 4. normal map
  13596. // 5. bump map
  13597. // 6. roughnessMap map
  13598. // 7. metalnessMap map
  13599. // 8. alphaMap map
  13600. // 9. emissiveMap map
  13601. // 10. clearcoat map
  13602. // 11. clearcoat normal map
  13603. // 12. clearcoat roughnessMap map
  13604. let uvScaleMap;
  13605. if ( material.map ) {
  13606. uvScaleMap = material.map;
  13607. } else if ( material.specularMap ) {
  13608. uvScaleMap = material.specularMap;
  13609. } else if ( material.displacementMap ) {
  13610. uvScaleMap = material.displacementMap;
  13611. } else if ( material.normalMap ) {
  13612. uvScaleMap = material.normalMap;
  13613. } else if ( material.bumpMap ) {
  13614. uvScaleMap = material.bumpMap;
  13615. } else if ( material.roughnessMap ) {
  13616. uvScaleMap = material.roughnessMap;
  13617. } else if ( material.metalnessMap ) {
  13618. uvScaleMap = material.metalnessMap;
  13619. } else if ( material.alphaMap ) {
  13620. uvScaleMap = material.alphaMap;
  13621. } else if ( material.emissiveMap ) {
  13622. uvScaleMap = material.emissiveMap;
  13623. } else if ( material.clearcoatMap ) {
  13624. uvScaleMap = material.clearcoatMap;
  13625. } else if ( material.clearcoatNormalMap ) {
  13626. uvScaleMap = material.clearcoatNormalMap;
  13627. } else if ( material.clearcoatRoughnessMap ) {
  13628. uvScaleMap = material.clearcoatRoughnessMap;
  13629. }
  13630. if ( uvScaleMap !== undefined ) {
  13631. // backwards compatibility
  13632. if ( uvScaleMap.isWebGLRenderTarget ) {
  13633. uvScaleMap = uvScaleMap.texture;
  13634. }
  13635. if ( uvScaleMap.matrixAutoUpdate === true ) {
  13636. uvScaleMap.updateMatrix();
  13637. }
  13638. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  13639. }
  13640. // uv repeat and offset setting priorities for uv2
  13641. // 1. ao map
  13642. // 2. light map
  13643. let uv2ScaleMap;
  13644. if ( material.aoMap ) {
  13645. uv2ScaleMap = material.aoMap;
  13646. } else if ( material.lightMap ) {
  13647. uv2ScaleMap = material.lightMap;
  13648. }
  13649. if ( uv2ScaleMap !== undefined ) {
  13650. // backwards compatibility
  13651. if ( uv2ScaleMap.isWebGLRenderTarget ) {
  13652. uv2ScaleMap = uv2ScaleMap.texture;
  13653. }
  13654. if ( uv2ScaleMap.matrixAutoUpdate === true ) {
  13655. uv2ScaleMap.updateMatrix();
  13656. }
  13657. uniforms.uv2Transform.value.copy( uv2ScaleMap.matrix );
  13658. }
  13659. }
  13660. function refreshUniformsLine( uniforms, material ) {
  13661. uniforms.diffuse.value.copy( material.color );
  13662. uniforms.opacity.value = material.opacity;
  13663. }
  13664. function refreshUniformsDash( uniforms, material ) {
  13665. uniforms.dashSize.value = material.dashSize;
  13666. uniforms.totalSize.value = material.dashSize + material.gapSize;
  13667. uniforms.scale.value = material.scale;
  13668. }
  13669. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  13670. uniforms.diffuse.value.copy( material.color );
  13671. uniforms.opacity.value = material.opacity;
  13672. uniforms.size.value = material.size * pixelRatio;
  13673. uniforms.scale.value = height * 0.5;
  13674. if ( material.map ) {
  13675. uniforms.map.value = material.map;
  13676. }
  13677. if ( material.alphaMap ) {
  13678. uniforms.alphaMap.value = material.alphaMap;
  13679. }
  13680. // uv repeat and offset setting priorities
  13681. // 1. color map
  13682. // 2. alpha map
  13683. let uvScaleMap;
  13684. if ( material.map ) {
  13685. uvScaleMap = material.map;
  13686. } else if ( material.alphaMap ) {
  13687. uvScaleMap = material.alphaMap;
  13688. }
  13689. if ( uvScaleMap !== undefined ) {
  13690. if ( uvScaleMap.matrixAutoUpdate === true ) {
  13691. uvScaleMap.updateMatrix();
  13692. }
  13693. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  13694. }
  13695. }
  13696. function refreshUniformsSprites( uniforms, material ) {
  13697. uniforms.diffuse.value.copy( material.color );
  13698. uniforms.opacity.value = material.opacity;
  13699. uniforms.rotation.value = material.rotation;
  13700. if ( material.map ) {
  13701. uniforms.map.value = material.map;
  13702. }
  13703. if ( material.alphaMap ) {
  13704. uniforms.alphaMap.value = material.alphaMap;
  13705. }
  13706. // uv repeat and offset setting priorities
  13707. // 1. color map
  13708. // 2. alpha map
  13709. let uvScaleMap;
  13710. if ( material.map ) {
  13711. uvScaleMap = material.map;
  13712. } else if ( material.alphaMap ) {
  13713. uvScaleMap = material.alphaMap;
  13714. }
  13715. if ( uvScaleMap !== undefined ) {
  13716. if ( uvScaleMap.matrixAutoUpdate === true ) {
  13717. uvScaleMap.updateMatrix();
  13718. }
  13719. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  13720. }
  13721. }
  13722. function refreshUniformsLambert( uniforms, material ) {
  13723. if ( material.emissiveMap ) {
  13724. uniforms.emissiveMap.value = material.emissiveMap;
  13725. }
  13726. }
  13727. function refreshUniformsPhong( uniforms, material ) {
  13728. uniforms.specular.value.copy( material.specular );
  13729. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  13730. if ( material.emissiveMap ) {
  13731. uniforms.emissiveMap.value = material.emissiveMap;
  13732. }
  13733. if ( material.bumpMap ) {
  13734. uniforms.bumpMap.value = material.bumpMap;
  13735. uniforms.bumpScale.value = material.bumpScale;
  13736. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  13737. }
  13738. if ( material.normalMap ) {
  13739. uniforms.normalMap.value = material.normalMap;
  13740. uniforms.normalScale.value.copy( material.normalScale );
  13741. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  13742. }
  13743. if ( material.displacementMap ) {
  13744. uniforms.displacementMap.value = material.displacementMap;
  13745. uniforms.displacementScale.value = material.displacementScale;
  13746. uniforms.displacementBias.value = material.displacementBias;
  13747. }
  13748. }
  13749. function refreshUniformsToon( uniforms, material ) {
  13750. if ( material.gradientMap ) {
  13751. uniforms.gradientMap.value = material.gradientMap;
  13752. }
  13753. if ( material.emissiveMap ) {
  13754. uniforms.emissiveMap.value = material.emissiveMap;
  13755. }
  13756. if ( material.bumpMap ) {
  13757. uniforms.bumpMap.value = material.bumpMap;
  13758. uniforms.bumpScale.value = material.bumpScale;
  13759. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  13760. }
  13761. if ( material.normalMap ) {
  13762. uniforms.normalMap.value = material.normalMap;
  13763. uniforms.normalScale.value.copy( material.normalScale );
  13764. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  13765. }
  13766. if ( material.displacementMap ) {
  13767. uniforms.displacementMap.value = material.displacementMap;
  13768. uniforms.displacementScale.value = material.displacementScale;
  13769. uniforms.displacementBias.value = material.displacementBias;
  13770. }
  13771. }
  13772. function refreshUniformsStandard( uniforms, material ) {
  13773. uniforms.roughness.value = material.roughness;
  13774. uniforms.metalness.value = material.metalness;
  13775. if ( material.roughnessMap ) {
  13776. uniforms.roughnessMap.value = material.roughnessMap;
  13777. }
  13778. if ( material.metalnessMap ) {
  13779. uniforms.metalnessMap.value = material.metalnessMap;
  13780. }
  13781. if ( material.emissiveMap ) {
  13782. uniforms.emissiveMap.value = material.emissiveMap;
  13783. }
  13784. if ( material.bumpMap ) {
  13785. uniforms.bumpMap.value = material.bumpMap;
  13786. uniforms.bumpScale.value = material.bumpScale;
  13787. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  13788. }
  13789. if ( material.normalMap ) {
  13790. uniforms.normalMap.value = material.normalMap;
  13791. uniforms.normalScale.value.copy( material.normalScale );
  13792. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  13793. }
  13794. if ( material.displacementMap ) {
  13795. uniforms.displacementMap.value = material.displacementMap;
  13796. uniforms.displacementScale.value = material.displacementScale;
  13797. uniforms.displacementBias.value = material.displacementBias;
  13798. }
  13799. const envMap = properties.get( material ).envMap;
  13800. if ( envMap ) {
  13801. //uniforms.envMap.value = material.envMap; // part of uniforms common
  13802. uniforms.envMapIntensity.value = material.envMapIntensity;
  13803. }
  13804. }
  13805. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  13806. refreshUniformsStandard( uniforms, material );
  13807. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  13808. uniforms.clearcoat.value = material.clearcoat;
  13809. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  13810. if ( material.sheen ) uniforms.sheen.value.copy( material.sheen );
  13811. if ( material.clearcoatMap ) {
  13812. uniforms.clearcoatMap.value = material.clearcoatMap;
  13813. }
  13814. if ( material.clearcoatRoughnessMap ) {
  13815. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  13816. }
  13817. if ( material.clearcoatNormalMap ) {
  13818. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  13819. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  13820. if ( material.side === BackSide ) {
  13821. uniforms.clearcoatNormalScale.value.negate();
  13822. }
  13823. }
  13824. uniforms.transmission.value = material.transmission;
  13825. if ( material.transmissionMap ) {
  13826. uniforms.transmissionMap.value = material.transmissionMap;
  13827. }
  13828. if ( material.transmission > 0.0 ) {
  13829. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  13830. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  13831. }
  13832. uniforms.thickness.value = material.thickness;
  13833. if ( material.thicknessMap ) {
  13834. uniforms.thicknessMap.value = material.thicknessMap;
  13835. }
  13836. uniforms.attenuationDistance.value = material.attenuationDistance;
  13837. uniforms.attenuationColor.value.copy( material.attenuationColor );
  13838. }
  13839. function refreshUniformsMatcap( uniforms, material ) {
  13840. if ( material.matcap ) {
  13841. uniforms.matcap.value = material.matcap;
  13842. }
  13843. if ( material.bumpMap ) {
  13844. uniforms.bumpMap.value = material.bumpMap;
  13845. uniforms.bumpScale.value = material.bumpScale;
  13846. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  13847. }
  13848. if ( material.normalMap ) {
  13849. uniforms.normalMap.value = material.normalMap;
  13850. uniforms.normalScale.value.copy( material.normalScale );
  13851. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  13852. }
  13853. if ( material.displacementMap ) {
  13854. uniforms.displacementMap.value = material.displacementMap;
  13855. uniforms.displacementScale.value = material.displacementScale;
  13856. uniforms.displacementBias.value = material.displacementBias;
  13857. }
  13858. }
  13859. function refreshUniformsDepth( uniforms, material ) {
  13860. if ( material.displacementMap ) {
  13861. uniforms.displacementMap.value = material.displacementMap;
  13862. uniforms.displacementScale.value = material.displacementScale;
  13863. uniforms.displacementBias.value = material.displacementBias;
  13864. }
  13865. }
  13866. function refreshUniformsDistance( uniforms, material ) {
  13867. if ( material.displacementMap ) {
  13868. uniforms.displacementMap.value = material.displacementMap;
  13869. uniforms.displacementScale.value = material.displacementScale;
  13870. uniforms.displacementBias.value = material.displacementBias;
  13871. }
  13872. uniforms.referencePosition.value.copy( material.referencePosition );
  13873. uniforms.nearDistance.value = material.nearDistance;
  13874. uniforms.farDistance.value = material.farDistance;
  13875. }
  13876. function refreshUniformsNormal( uniforms, material ) {
  13877. if ( material.bumpMap ) {
  13878. uniforms.bumpMap.value = material.bumpMap;
  13879. uniforms.bumpScale.value = material.bumpScale;
  13880. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  13881. }
  13882. if ( material.normalMap ) {
  13883. uniforms.normalMap.value = material.normalMap;
  13884. uniforms.normalScale.value.copy( material.normalScale );
  13885. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  13886. }
  13887. if ( material.displacementMap ) {
  13888. uniforms.displacementMap.value = material.displacementMap;
  13889. uniforms.displacementScale.value = material.displacementScale;
  13890. uniforms.displacementBias.value = material.displacementBias;
  13891. }
  13892. }
  13893. return {
  13894. refreshFogUniforms: refreshFogUniforms,
  13895. refreshMaterialUniforms: refreshMaterialUniforms
  13896. };
  13897. }
  13898. function createCanvasElement() {
  13899. const canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  13900. canvas.style.display = 'block';
  13901. return canvas;
  13902. }
  13903. function WebGLRenderer( parameters = {} ) {
  13904. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  13905. _context = parameters.context !== undefined ? parameters.context : null,
  13906. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  13907. _depth = parameters.depth !== undefined ? parameters.depth : true,
  13908. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  13909. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  13910. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  13911. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  13912. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  13913. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  13914. let currentRenderList = null;
  13915. let currentRenderState = null;
  13916. // render() can be called from within a callback triggered by another render.
  13917. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  13918. const renderListStack = [];
  13919. const renderStateStack = [];
  13920. // public properties
  13921. this.domElement = _canvas;
  13922. // Debug configuration container
  13923. this.debug = {
  13924. /**
  13925. * Enables error checking and reporting when shader programs are being compiled
  13926. * @type {boolean}
  13927. */
  13928. checkShaderErrors: true
  13929. };
  13930. // clearing
  13931. this.autoClear = true;
  13932. this.autoClearColor = true;
  13933. this.autoClearDepth = true;
  13934. this.autoClearStencil = true;
  13935. // scene graph
  13936. this.sortObjects = true;
  13937. // user-defined clipping
  13938. this.clippingPlanes = [];
  13939. this.localClippingEnabled = false;
  13940. // physically based shading
  13941. this.gammaFactor = 2.0; // for backwards compatibility
  13942. this.outputEncoding = LinearEncoding;
  13943. // physical lights
  13944. this.physicallyCorrectLights = false;
  13945. // tone mapping
  13946. this.toneMapping = NoToneMapping;
  13947. this.toneMappingExposure = 1.0;
  13948. // internal properties
  13949. const _this = this;
  13950. let _isContextLost = false;
  13951. // internal state cache
  13952. let _currentActiveCubeFace = 0;
  13953. let _currentActiveMipmapLevel = 0;
  13954. let _currentRenderTarget = null;
  13955. let _currentMaterialId = - 1;
  13956. let _currentCamera = null;
  13957. const _currentViewport = new Vector4();
  13958. const _currentScissor = new Vector4();
  13959. let _currentScissorTest = null;
  13960. //
  13961. let _width = _canvas.width;
  13962. let _height = _canvas.height;
  13963. let _pixelRatio = 1;
  13964. let _opaqueSort = null;
  13965. let _transparentSort = null;
  13966. const _viewport = new Vector4( 0, 0, _width, _height );
  13967. const _scissor = new Vector4( 0, 0, _width, _height );
  13968. let _scissorTest = false;
  13969. //
  13970. const _currentDrawBuffers = [];
  13971. // frustum
  13972. const _frustum = new Frustum();
  13973. // clipping
  13974. let _clippingEnabled = false;
  13975. let _localClippingEnabled = false;
  13976. // transmission
  13977. let _transmissionRenderTarget = null;
  13978. // camera matrices cache
  13979. const _projScreenMatrix = new Matrix4();
  13980. const _vector3 = new Vector3();
  13981. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  13982. function getTargetPixelRatio() {
  13983. return _currentRenderTarget === null ? _pixelRatio : 1;
  13984. }
  13985. // initialize
  13986. let _gl = _context;
  13987. function getContext( contextNames, contextAttributes ) {
  13988. for ( let i = 0; i < contextNames.length; i ++ ) {
  13989. const contextName = contextNames[ i ];
  13990. const context = _canvas.getContext( contextName, contextAttributes );
  13991. if ( context !== null ) return context;
  13992. }
  13993. return null;
  13994. }
  13995. try {
  13996. const contextAttributes = {
  13997. alpha: _alpha,
  13998. depth: _depth,
  13999. stencil: _stencil,
  14000. antialias: _antialias,
  14001. premultipliedAlpha: _premultipliedAlpha,
  14002. preserveDrawingBuffer: _preserveDrawingBuffer,
  14003. powerPreference: _powerPreference,
  14004. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  14005. };
  14006. // event listeners must be registered before WebGL context is created, see #12753
  14007. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  14008. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  14009. if ( _gl === null ) {
  14010. const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ];
  14011. if ( _this.isWebGL1Renderer === true ) {
  14012. contextNames.shift();
  14013. }
  14014. _gl = getContext( contextNames, contextAttributes );
  14015. if ( _gl === null ) {
  14016. if ( getContext( contextNames ) ) {
  14017. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  14018. } else {
  14019. throw new Error( 'Error creating WebGL context.' );
  14020. }
  14021. }
  14022. }
  14023. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  14024. if ( _gl.getShaderPrecisionFormat === undefined ) {
  14025. _gl.getShaderPrecisionFormat = function () {
  14026. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  14027. };
  14028. }
  14029. } catch ( error ) {
  14030. console.error( 'THREE.WebGLRenderer: ' + error.message );
  14031. throw error;
  14032. }
  14033. let extensions, capabilities, state, info;
  14034. let properties, textures, cubemaps, attributes, geometries, objects;
  14035. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  14036. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  14037. let utils, bindingStates;
  14038. function initGLContext() {
  14039. extensions = new WebGLExtensions( _gl );
  14040. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  14041. extensions.init( capabilities );
  14042. utils = new WebGLUtils( _gl, extensions, capabilities );
  14043. state = new WebGLState( _gl, extensions, capabilities );
  14044. _currentDrawBuffers[ 0 ] = 1029;
  14045. info = new WebGLInfo( _gl );
  14046. properties = new WebGLProperties();
  14047. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  14048. cubemaps = new WebGLCubeMaps( _this );
  14049. attributes = new WebGLAttributes( _gl, capabilities );
  14050. bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities );
  14051. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  14052. objects = new WebGLObjects( _gl, geometries, attributes, info );
  14053. morphtargets = new WebGLMorphtargets( _gl );
  14054. clipping = new WebGLClipping( properties );
  14055. programCache = new WebGLPrograms( _this, cubemaps, extensions, capabilities, bindingStates, clipping );
  14056. materials = new WebGLMaterials( properties );
  14057. renderLists = new WebGLRenderLists( properties );
  14058. renderStates = new WebGLRenderStates( extensions, capabilities );
  14059. background = new WebGLBackground( _this, cubemaps, state, objects, _premultipliedAlpha );
  14060. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  14061. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  14062. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  14063. info.programs = programCache.programs;
  14064. _this.capabilities = capabilities;
  14065. _this.extensions = extensions;
  14066. _this.properties = properties;
  14067. _this.renderLists = renderLists;
  14068. _this.shadowMap = shadowMap;
  14069. _this.state = state;
  14070. _this.info = info;
  14071. }
  14072. initGLContext();
  14073. // xr
  14074. const xr = new WebXRManager( _this, _gl );
  14075. this.xr = xr;
  14076. // API
  14077. this.getContext = function () {
  14078. return _gl;
  14079. };
  14080. this.getContextAttributes = function () {
  14081. return _gl.getContextAttributes();
  14082. };
  14083. this.forceContextLoss = function () {
  14084. const extension = extensions.get( 'WEBGL_lose_context' );
  14085. if ( extension ) extension.loseContext();
  14086. };
  14087. this.forceContextRestore = function () {
  14088. const extension = extensions.get( 'WEBGL_lose_context' );
  14089. if ( extension ) extension.restoreContext();
  14090. };
  14091. this.getPixelRatio = function () {
  14092. return _pixelRatio;
  14093. };
  14094. this.setPixelRatio = function ( value ) {
  14095. if ( value === undefined ) return;
  14096. _pixelRatio = value;
  14097. this.setSize( _width, _height, false );
  14098. };
  14099. this.getSize = function ( target ) {
  14100. return target.set( _width, _height );
  14101. };
  14102. this.setSize = function ( width, height, updateStyle ) {
  14103. if ( xr.isPresenting ) {
  14104. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  14105. return;
  14106. }
  14107. _width = width;
  14108. _height = height;
  14109. _canvas.width = Math.floor( width * _pixelRatio );
  14110. _canvas.height = Math.floor( height * _pixelRatio );
  14111. if ( updateStyle !== false ) {
  14112. _canvas.style.width = width + 'px';
  14113. _canvas.style.height = height + 'px';
  14114. }
  14115. this.setViewport( 0, 0, width, height );
  14116. };
  14117. this.getDrawingBufferSize = function ( target ) {
  14118. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  14119. };
  14120. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  14121. _width = width;
  14122. _height = height;
  14123. _pixelRatio = pixelRatio;
  14124. _canvas.width = Math.floor( width * pixelRatio );
  14125. _canvas.height = Math.floor( height * pixelRatio );
  14126. this.setViewport( 0, 0, width, height );
  14127. };
  14128. this.getCurrentViewport = function ( target ) {
  14129. return target.copy( _currentViewport );
  14130. };
  14131. this.getViewport = function ( target ) {
  14132. return target.copy( _viewport );
  14133. };
  14134. this.setViewport = function ( x, y, width, height ) {
  14135. if ( x.isVector4 ) {
  14136. _viewport.set( x.x, x.y, x.z, x.w );
  14137. } else {
  14138. _viewport.set( x, y, width, height );
  14139. }
  14140. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  14141. };
  14142. this.getScissor = function ( target ) {
  14143. return target.copy( _scissor );
  14144. };
  14145. this.setScissor = function ( x, y, width, height ) {
  14146. if ( x.isVector4 ) {
  14147. _scissor.set( x.x, x.y, x.z, x.w );
  14148. } else {
  14149. _scissor.set( x, y, width, height );
  14150. }
  14151. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  14152. };
  14153. this.getScissorTest = function () {
  14154. return _scissorTest;
  14155. };
  14156. this.setScissorTest = function ( boolean ) {
  14157. state.setScissorTest( _scissorTest = boolean );
  14158. };
  14159. this.setOpaqueSort = function ( method ) {
  14160. _opaqueSort = method;
  14161. };
  14162. this.setTransparentSort = function ( method ) {
  14163. _transparentSort = method;
  14164. };
  14165. // Clearing
  14166. this.getClearColor = function ( target ) {
  14167. return target.copy( background.getClearColor() );
  14168. };
  14169. this.setClearColor = function () {
  14170. background.setClearColor.apply( background, arguments );
  14171. };
  14172. this.getClearAlpha = function () {
  14173. return background.getClearAlpha();
  14174. };
  14175. this.setClearAlpha = function () {
  14176. background.setClearAlpha.apply( background, arguments );
  14177. };
  14178. this.clear = function ( color, depth, stencil ) {
  14179. let bits = 0;
  14180. if ( color === undefined || color ) bits |= 16384;
  14181. if ( depth === undefined || depth ) bits |= 256;
  14182. if ( stencil === undefined || stencil ) bits |= 1024;
  14183. _gl.clear( bits );
  14184. };
  14185. this.clearColor = function () {
  14186. this.clear( true, false, false );
  14187. };
  14188. this.clearDepth = function () {
  14189. this.clear( false, true, false );
  14190. };
  14191. this.clearStencil = function () {
  14192. this.clear( false, false, true );
  14193. };
  14194. //
  14195. this.dispose = function () {
  14196. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  14197. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  14198. renderLists.dispose();
  14199. renderStates.dispose();
  14200. properties.dispose();
  14201. cubemaps.dispose();
  14202. objects.dispose();
  14203. bindingStates.dispose();
  14204. xr.dispose();
  14205. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  14206. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  14207. if ( _transmissionRenderTarget ) {
  14208. _transmissionRenderTarget.dispose();
  14209. _transmissionRenderTarget = null;
  14210. }
  14211. animation.stop();
  14212. };
  14213. // Events
  14214. function onContextLost( event ) {
  14215. event.preventDefault();
  14216. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  14217. _isContextLost = true;
  14218. }
  14219. function onContextRestore( /* event */ ) {
  14220. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  14221. _isContextLost = false;
  14222. const infoAutoReset = info.autoReset;
  14223. const shadowMapEnabled = shadowMap.enabled;
  14224. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  14225. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  14226. const shadowMapType = shadowMap.type;
  14227. initGLContext();
  14228. info.autoReset = infoAutoReset;
  14229. shadowMap.enabled = shadowMapEnabled;
  14230. shadowMap.autoUpdate = shadowMapAutoUpdate;
  14231. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  14232. shadowMap.type = shadowMapType;
  14233. }
  14234. function onMaterialDispose( event ) {
  14235. const material = event.target;
  14236. material.removeEventListener( 'dispose', onMaterialDispose );
  14237. deallocateMaterial( material );
  14238. }
  14239. // Buffer deallocation
  14240. function deallocateMaterial( material ) {
  14241. releaseMaterialProgramReferences( material );
  14242. properties.remove( material );
  14243. }
  14244. function releaseMaterialProgramReferences( material ) {
  14245. const programs = properties.get( material ).programs;
  14246. if ( programs !== undefined ) {
  14247. programs.forEach( function ( program ) {
  14248. programCache.releaseProgram( program );
  14249. } );
  14250. }
  14251. }
  14252. // Buffer rendering
  14253. function renderObjectImmediate( object, program ) {
  14254. object.render( function ( object ) {
  14255. _this.renderBufferImmediate( object, program );
  14256. } );
  14257. }
  14258. this.renderBufferImmediate = function ( object, program ) {
  14259. bindingStates.initAttributes();
  14260. const buffers = properties.get( object );
  14261. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  14262. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  14263. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  14264. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  14265. const programAttributes = program.getAttributes();
  14266. if ( object.hasPositions ) {
  14267. _gl.bindBuffer( 34962, buffers.position );
  14268. _gl.bufferData( 34962, object.positionArray, 35048 );
  14269. bindingStates.enableAttribute( programAttributes.position );
  14270. _gl.vertexAttribPointer( programAttributes.position, 3, 5126, false, 0, 0 );
  14271. }
  14272. if ( object.hasNormals ) {
  14273. _gl.bindBuffer( 34962, buffers.normal );
  14274. _gl.bufferData( 34962, object.normalArray, 35048 );
  14275. bindingStates.enableAttribute( programAttributes.normal );
  14276. _gl.vertexAttribPointer( programAttributes.normal, 3, 5126, false, 0, 0 );
  14277. }
  14278. if ( object.hasUvs ) {
  14279. _gl.bindBuffer( 34962, buffers.uv );
  14280. _gl.bufferData( 34962, object.uvArray, 35048 );
  14281. bindingStates.enableAttribute( programAttributes.uv );
  14282. _gl.vertexAttribPointer( programAttributes.uv, 2, 5126, false, 0, 0 );
  14283. }
  14284. if ( object.hasColors ) {
  14285. _gl.bindBuffer( 34962, buffers.color );
  14286. _gl.bufferData( 34962, object.colorArray, 35048 );
  14287. bindingStates.enableAttribute( programAttributes.color );
  14288. _gl.vertexAttribPointer( programAttributes.color, 3, 5126, false, 0, 0 );
  14289. }
  14290. bindingStates.disableUnusedAttributes();
  14291. _gl.drawArrays( 4, 0, object.count );
  14292. object.count = 0;
  14293. };
  14294. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  14295. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  14296. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  14297. const program = setProgram( camera, scene, material, object );
  14298. state.setMaterial( material, frontFaceCW );
  14299. //
  14300. let index = geometry.index;
  14301. const position = geometry.attributes.position;
  14302. //
  14303. if ( index === null ) {
  14304. if ( position === undefined || position.count === 0 ) return;
  14305. } else if ( index.count === 0 ) {
  14306. return;
  14307. }
  14308. //
  14309. let rangeFactor = 1;
  14310. if ( material.wireframe === true ) {
  14311. index = geometries.getWireframeAttribute( geometry );
  14312. rangeFactor = 2;
  14313. }
  14314. if ( material.morphTargets || material.morphNormals ) {
  14315. morphtargets.update( object, geometry, material, program );
  14316. }
  14317. bindingStates.setup( object, material, program, geometry, index );
  14318. let attribute;
  14319. let renderer = bufferRenderer;
  14320. if ( index !== null ) {
  14321. attribute = attributes.get( index );
  14322. renderer = indexedBufferRenderer;
  14323. renderer.setIndex( attribute );
  14324. }
  14325. //
  14326. const dataCount = ( index !== null ) ? index.count : position.count;
  14327. const rangeStart = geometry.drawRange.start * rangeFactor;
  14328. const rangeCount = geometry.drawRange.count * rangeFactor;
  14329. const groupStart = group !== null ? group.start * rangeFactor : 0;
  14330. const groupCount = group !== null ? group.count * rangeFactor : Infinity;
  14331. const drawStart = Math.max( rangeStart, groupStart );
  14332. const drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  14333. const drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  14334. if ( drawCount === 0 ) return;
  14335. //
  14336. if ( object.isMesh ) {
  14337. if ( material.wireframe === true ) {
  14338. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  14339. renderer.setMode( 1 );
  14340. } else {
  14341. renderer.setMode( 4 );
  14342. }
  14343. } else if ( object.isLine ) {
  14344. let lineWidth = material.linewidth;
  14345. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  14346. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  14347. if ( object.isLineSegments ) {
  14348. renderer.setMode( 1 );
  14349. } else if ( object.isLineLoop ) {
  14350. renderer.setMode( 2 );
  14351. } else {
  14352. renderer.setMode( 3 );
  14353. }
  14354. } else if ( object.isPoints ) {
  14355. renderer.setMode( 0 );
  14356. } else if ( object.isSprite ) {
  14357. renderer.setMode( 4 );
  14358. }
  14359. if ( object.isInstancedMesh ) {
  14360. renderer.renderInstances( drawStart, drawCount, object.count );
  14361. } else if ( geometry.isInstancedBufferGeometry ) {
  14362. const instanceCount = Math.min( geometry.instanceCount, geometry._maxInstanceCount );
  14363. renderer.renderInstances( drawStart, drawCount, instanceCount );
  14364. } else {
  14365. renderer.render( drawStart, drawCount );
  14366. }
  14367. };
  14368. // Compile
  14369. this.compile = function ( scene, camera ) {
  14370. currentRenderState = renderStates.get( scene );
  14371. currentRenderState.init();
  14372. scene.traverseVisible( function ( object ) {
  14373. if ( object.isLight && object.layers.test( camera.layers ) ) {
  14374. currentRenderState.pushLight( object );
  14375. if ( object.castShadow ) {
  14376. currentRenderState.pushShadow( object );
  14377. }
  14378. }
  14379. } );
  14380. currentRenderState.setupLights();
  14381. scene.traverse( function ( object ) {
  14382. const material = object.material;
  14383. if ( material ) {
  14384. if ( Array.isArray( material ) ) {
  14385. for ( let i = 0; i < material.length; i ++ ) {
  14386. const material2 = material[ i ];
  14387. getProgram( material2, scene, object );
  14388. }
  14389. } else {
  14390. getProgram( material, scene, object );
  14391. }
  14392. }
  14393. } );
  14394. };
  14395. // Animation Loop
  14396. let onAnimationFrameCallback = null;
  14397. function onAnimationFrame( time ) {
  14398. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  14399. }
  14400. function onXRSessionStart() {
  14401. animation.stop();
  14402. }
  14403. function onXRSessionEnd() {
  14404. animation.start();
  14405. }
  14406. const animation = new WebGLAnimation();
  14407. animation.setAnimationLoop( onAnimationFrame );
  14408. if ( typeof window !== 'undefined' ) animation.setContext( window );
  14409. this.setAnimationLoop = function ( callback ) {
  14410. onAnimationFrameCallback = callback;
  14411. xr.setAnimationLoop( callback );
  14412. ( callback === null ) ? animation.stop() : animation.start();
  14413. };
  14414. xr.addEventListener( 'sessionstart', onXRSessionStart );
  14415. xr.addEventListener( 'sessionend', onXRSessionEnd );
  14416. // Rendering
  14417. this.render = function ( scene, camera ) {
  14418. if ( camera !== undefined && camera.isCamera !== true ) {
  14419. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  14420. return;
  14421. }
  14422. if ( _isContextLost === true ) return;
  14423. // update scene graph
  14424. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  14425. // update camera matrices and frustum
  14426. if ( camera.parent === null ) camera.updateMatrixWorld();
  14427. if ( xr.enabled === true && xr.isPresenting === true ) {
  14428. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  14429. camera = xr.getCamera(); // use XR camera for rendering
  14430. }
  14431. //
  14432. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  14433. currentRenderState = renderStates.get( scene, renderStateStack.length );
  14434. currentRenderState.init();
  14435. renderStateStack.push( currentRenderState );
  14436. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  14437. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  14438. _localClippingEnabled = this.localClippingEnabled;
  14439. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  14440. currentRenderList = renderLists.get( scene, renderListStack.length );
  14441. currentRenderList.init();
  14442. renderListStack.push( currentRenderList );
  14443. projectObject( scene, camera, 0, _this.sortObjects );
  14444. currentRenderList.finish();
  14445. if ( _this.sortObjects === true ) {
  14446. currentRenderList.sort( _opaqueSort, _transparentSort );
  14447. }
  14448. //
  14449. if ( _clippingEnabled === true ) clipping.beginShadows();
  14450. const shadowsArray = currentRenderState.state.shadowsArray;
  14451. shadowMap.render( shadowsArray, scene, camera );
  14452. currentRenderState.setupLights();
  14453. currentRenderState.setupLightsView( camera );
  14454. if ( _clippingEnabled === true ) clipping.endShadows();
  14455. //
  14456. if ( this.info.autoReset === true ) this.info.reset();
  14457. //
  14458. background.render( currentRenderList, scene );
  14459. // render scene
  14460. const opaqueObjects = currentRenderList.opaque;
  14461. const transmissiveObjects = currentRenderList.transmissive;
  14462. const transparentObjects = currentRenderList.transparent;
  14463. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  14464. if ( transmissiveObjects.length > 0 ) renderTransmissiveObjects( opaqueObjects, transmissiveObjects, scene, camera );
  14465. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  14466. //
  14467. if ( _currentRenderTarget !== null ) {
  14468. // resolve multisample renderbuffers to a single-sample texture if necessary
  14469. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  14470. // Generate mipmap if we're using any kind of mipmap filtering
  14471. textures.updateRenderTargetMipmap( _currentRenderTarget );
  14472. }
  14473. //
  14474. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  14475. // Ensure depth buffer writing is enabled so it can be cleared on next render
  14476. state.buffers.depth.setTest( true );
  14477. state.buffers.depth.setMask( true );
  14478. state.buffers.color.setMask( true );
  14479. state.setPolygonOffset( false );
  14480. // _gl.finish();
  14481. bindingStates.resetDefaultState();
  14482. _currentMaterialId = - 1;
  14483. _currentCamera = null;
  14484. renderStateStack.pop();
  14485. if ( renderStateStack.length > 0 ) {
  14486. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  14487. } else {
  14488. currentRenderState = null;
  14489. }
  14490. renderListStack.pop();
  14491. if ( renderListStack.length > 0 ) {
  14492. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  14493. } else {
  14494. currentRenderList = null;
  14495. }
  14496. };
  14497. function projectObject( object, camera, groupOrder, sortObjects ) {
  14498. if ( object.visible === false ) return;
  14499. const visible = object.layers.test( camera.layers );
  14500. if ( visible ) {
  14501. if ( object.isGroup ) {
  14502. groupOrder = object.renderOrder;
  14503. } else if ( object.isLOD ) {
  14504. if ( object.autoUpdate === true ) object.update( camera );
  14505. } else if ( object.isLight ) {
  14506. currentRenderState.pushLight( object );
  14507. if ( object.castShadow ) {
  14508. currentRenderState.pushShadow( object );
  14509. }
  14510. } else if ( object.isSprite ) {
  14511. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  14512. if ( sortObjects ) {
  14513. _vector3.setFromMatrixPosition( object.matrixWorld )
  14514. .applyMatrix4( _projScreenMatrix );
  14515. }
  14516. const geometry = objects.update( object );
  14517. const material = object.material;
  14518. if ( material.visible ) {
  14519. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  14520. }
  14521. }
  14522. } else if ( object.isImmediateRenderObject ) {
  14523. if ( sortObjects ) {
  14524. _vector3.setFromMatrixPosition( object.matrixWorld )
  14525. .applyMatrix4( _projScreenMatrix );
  14526. }
  14527. currentRenderList.push( object, null, object.material, groupOrder, _vector3.z, null );
  14528. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  14529. if ( object.isSkinnedMesh ) {
  14530. // update skeleton only once in a frame
  14531. if ( object.skeleton.frame !== info.render.frame ) {
  14532. object.skeleton.update();
  14533. object.skeleton.frame = info.render.frame;
  14534. }
  14535. }
  14536. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  14537. if ( sortObjects ) {
  14538. _vector3.setFromMatrixPosition( object.matrixWorld )
  14539. .applyMatrix4( _projScreenMatrix );
  14540. }
  14541. const geometry = objects.update( object );
  14542. const material = object.material;
  14543. if ( Array.isArray( material ) ) {
  14544. const groups = geometry.groups;
  14545. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  14546. const group = groups[ i ];
  14547. const groupMaterial = material[ group.materialIndex ];
  14548. if ( groupMaterial && groupMaterial.visible ) {
  14549. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  14550. }
  14551. }
  14552. } else if ( material.visible ) {
  14553. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  14554. }
  14555. }
  14556. }
  14557. }
  14558. const children = object.children;
  14559. for ( let i = 0, l = children.length; i < l; i ++ ) {
  14560. projectObject( children[ i ], camera, groupOrder, sortObjects );
  14561. }
  14562. }
  14563. function renderTransmissiveObjects( opaqueObjects, transmissiveObjects, scene, camera ) {
  14564. if ( _transmissionRenderTarget === null ) {
  14565. const needsAntialias = _antialias === true && capabilities.isWebGL2 === true;
  14566. const renderTargetType = needsAntialias ? WebGLMultisampleRenderTarget : WebGLRenderTarget;
  14567. _transmissionRenderTarget = new renderTargetType( 1024, 1024, {
  14568. generateMipmaps: true,
  14569. type: utils.convert( HalfFloatType ) !== null ? HalfFloatType : UnsignedByteType,
  14570. minFilter: LinearMipmapLinearFilter,
  14571. magFilter: NearestFilter,
  14572. wrapS: ClampToEdgeWrapping,
  14573. wrapT: ClampToEdgeWrapping
  14574. } );
  14575. }
  14576. const currentRenderTarget = _this.getRenderTarget();
  14577. _this.setRenderTarget( _transmissionRenderTarget );
  14578. _this.clear();
  14579. // Turn off the features which can affect the frag color for opaque objects pass.
  14580. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  14581. const currentToneMapping = _this.toneMapping;
  14582. _this.toneMapping = NoToneMapping;
  14583. renderObjects( opaqueObjects, scene, camera );
  14584. _this.toneMapping = currentToneMapping;
  14585. textures.updateMultisampleRenderTarget( _transmissionRenderTarget );
  14586. textures.updateRenderTargetMipmap( _transmissionRenderTarget );
  14587. _this.setRenderTarget( currentRenderTarget );
  14588. renderObjects( transmissiveObjects, scene, camera );
  14589. }
  14590. function renderObjects( renderList, scene, camera ) {
  14591. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  14592. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  14593. const renderItem = renderList[ i ];
  14594. const object = renderItem.object;
  14595. const geometry = renderItem.geometry;
  14596. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  14597. const group = renderItem.group;
  14598. if ( camera.isArrayCamera ) {
  14599. const cameras = camera.cameras;
  14600. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  14601. const camera2 = cameras[ j ];
  14602. if ( object.layers.test( camera2.layers ) ) {
  14603. state.viewport( _currentViewport.copy( camera2.viewport ) );
  14604. currentRenderState.setupLightsView( camera2 );
  14605. renderObject( object, scene, camera2, geometry, material, group );
  14606. }
  14607. }
  14608. } else {
  14609. renderObject( object, scene, camera, geometry, material, group );
  14610. }
  14611. }
  14612. }
  14613. function renderObject( object, scene, camera, geometry, material, group ) {
  14614. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  14615. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  14616. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  14617. if ( object.isImmediateRenderObject ) {
  14618. const program = setProgram( camera, scene, material, object );
  14619. state.setMaterial( material );
  14620. bindingStates.reset();
  14621. renderObjectImmediate( object, program );
  14622. } else {
  14623. if ( material.transparent === true && material.side === DoubleSide ) {
  14624. material.side = BackSide;
  14625. material.needsUpdate = true;
  14626. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  14627. material.side = FrontSide;
  14628. material.needsUpdate = true;
  14629. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  14630. material.side = DoubleSide;
  14631. } else {
  14632. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  14633. }
  14634. }
  14635. object.onAfterRender( _this, scene, camera, geometry, material, group );
  14636. }
  14637. function getProgram( material, scene, object ) {
  14638. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  14639. const materialProperties = properties.get( material );
  14640. const lights = currentRenderState.state.lights;
  14641. const shadowsArray = currentRenderState.state.shadowsArray;
  14642. const lightsStateVersion = lights.state.version;
  14643. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  14644. const programCacheKey = programCache.getProgramCacheKey( parameters );
  14645. let programs = materialProperties.programs;
  14646. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  14647. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  14648. materialProperties.fog = scene.fog;
  14649. materialProperties.envMap = cubemaps.get( material.envMap || materialProperties.environment );
  14650. if ( programs === undefined ) {
  14651. // new material
  14652. material.addEventListener( 'dispose', onMaterialDispose );
  14653. programs = new Map();
  14654. materialProperties.programs = programs;
  14655. }
  14656. let program = programs.get( programCacheKey );
  14657. if ( program !== undefined ) {
  14658. // early out if program and light state is identical
  14659. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  14660. updateCommonMaterialProperties( material, parameters );
  14661. return program;
  14662. }
  14663. } else {
  14664. parameters.uniforms = programCache.getUniforms( material );
  14665. material.onBuild( parameters, _this );
  14666. material.onBeforeCompile( parameters, _this );
  14667. program = programCache.acquireProgram( parameters, programCacheKey );
  14668. programs.set( programCacheKey, program );
  14669. materialProperties.uniforms = parameters.uniforms;
  14670. }
  14671. const uniforms = materialProperties.uniforms;
  14672. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  14673. uniforms.clippingPlanes = clipping.uniform;
  14674. }
  14675. updateCommonMaterialProperties( material, parameters );
  14676. // store the light setup it was created for
  14677. materialProperties.needsLights = materialNeedsLights( material );
  14678. materialProperties.lightsStateVersion = lightsStateVersion;
  14679. if ( materialProperties.needsLights ) {
  14680. // wire up the material to this renderer's lighting state
  14681. uniforms.ambientLightColor.value = lights.state.ambient;
  14682. uniforms.lightProbe.value = lights.state.probe;
  14683. uniforms.directionalLights.value = lights.state.directional;
  14684. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  14685. uniforms.spotLights.value = lights.state.spot;
  14686. uniforms.spotLightShadows.value = lights.state.spotShadow;
  14687. uniforms.rectAreaLights.value = lights.state.rectArea;
  14688. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  14689. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  14690. uniforms.pointLights.value = lights.state.point;
  14691. uniforms.pointLightShadows.value = lights.state.pointShadow;
  14692. uniforms.hemisphereLights.value = lights.state.hemi;
  14693. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  14694. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  14695. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  14696. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  14697. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  14698. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  14699. // TODO (abelnation): add area lights shadow info to uniforms
  14700. }
  14701. const progUniforms = program.getUniforms();
  14702. const uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  14703. materialProperties.currentProgram = program;
  14704. materialProperties.uniformsList = uniformsList;
  14705. return program;
  14706. }
  14707. function updateCommonMaterialProperties( material, parameters ) {
  14708. const materialProperties = properties.get( material );
  14709. materialProperties.outputEncoding = parameters.outputEncoding;
  14710. materialProperties.instancing = parameters.instancing;
  14711. materialProperties.skinning = parameters.skinning;
  14712. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  14713. materialProperties.numIntersection = parameters.numClipIntersection;
  14714. materialProperties.vertexAlphas = parameters.vertexAlphas;
  14715. }
  14716. function setProgram( camera, scene, material, object ) {
  14717. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  14718. textures.resetTextureUnits();
  14719. const fog = scene.fog;
  14720. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  14721. const encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : _currentRenderTarget.texture.encoding;
  14722. const envMap = cubemaps.get( material.envMap || environment );
  14723. const vertexAlphas = material.vertexColors === true && object.geometry && object.geometry.attributes.color && object.geometry.attributes.color.itemSize === 4;
  14724. const materialProperties = properties.get( material );
  14725. const lights = currentRenderState.state.lights;
  14726. if ( _clippingEnabled === true ) {
  14727. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  14728. const useCache =
  14729. camera === _currentCamera &&
  14730. material.id === _currentMaterialId;
  14731. // we might want to call this function with some ClippingGroup
  14732. // object instead of the material, once it becomes feasible
  14733. // (#8465, #8379)
  14734. clipping.setState( material, camera, useCache );
  14735. }
  14736. }
  14737. //
  14738. let needsProgramChange = false;
  14739. if ( material.version === materialProperties.__version ) {
  14740. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  14741. needsProgramChange = true;
  14742. } else if ( materialProperties.outputEncoding !== encoding ) {
  14743. needsProgramChange = true;
  14744. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  14745. needsProgramChange = true;
  14746. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  14747. needsProgramChange = true;
  14748. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  14749. needsProgramChange = true;
  14750. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  14751. needsProgramChange = true;
  14752. } else if ( materialProperties.envMap !== envMap ) {
  14753. needsProgramChange = true;
  14754. } else if ( material.fog && materialProperties.fog !== fog ) {
  14755. needsProgramChange = true;
  14756. } else if ( materialProperties.numClippingPlanes !== undefined &&
  14757. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  14758. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  14759. needsProgramChange = true;
  14760. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  14761. needsProgramChange = true;
  14762. }
  14763. } else {
  14764. needsProgramChange = true;
  14765. materialProperties.__version = material.version;
  14766. }
  14767. //
  14768. let program = materialProperties.currentProgram;
  14769. if ( needsProgramChange === true ) {
  14770. program = getProgram( material, scene, object );
  14771. }
  14772. let refreshProgram = false;
  14773. let refreshMaterial = false;
  14774. let refreshLights = false;
  14775. const p_uniforms = program.getUniforms(),
  14776. m_uniforms = materialProperties.uniforms;
  14777. if ( state.useProgram( program.program ) ) {
  14778. refreshProgram = true;
  14779. refreshMaterial = true;
  14780. refreshLights = true;
  14781. }
  14782. if ( material.id !== _currentMaterialId ) {
  14783. _currentMaterialId = material.id;
  14784. refreshMaterial = true;
  14785. }
  14786. if ( refreshProgram || _currentCamera !== camera ) {
  14787. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  14788. if ( capabilities.logarithmicDepthBuffer ) {
  14789. p_uniforms.setValue( _gl, 'logDepthBufFC',
  14790. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  14791. }
  14792. if ( _currentCamera !== camera ) {
  14793. _currentCamera = camera;
  14794. // lighting uniforms depend on the camera so enforce an update
  14795. // now, in case this material supports lights - or later, when
  14796. // the next material that does gets activated:
  14797. refreshMaterial = true; // set to true on material change
  14798. refreshLights = true; // remains set until update done
  14799. }
  14800. // load material specific uniforms
  14801. // (shader material also gets them for the sake of genericity)
  14802. if ( material.isShaderMaterial ||
  14803. material.isMeshPhongMaterial ||
  14804. material.isMeshToonMaterial ||
  14805. material.isMeshStandardMaterial ||
  14806. material.envMap ) {
  14807. const uCamPos = p_uniforms.map.cameraPosition;
  14808. if ( uCamPos !== undefined ) {
  14809. uCamPos.setValue( _gl,
  14810. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  14811. }
  14812. }
  14813. if ( material.isMeshPhongMaterial ||
  14814. material.isMeshToonMaterial ||
  14815. material.isMeshLambertMaterial ||
  14816. material.isMeshBasicMaterial ||
  14817. material.isMeshStandardMaterial ||
  14818. material.isShaderMaterial ) {
  14819. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  14820. }
  14821. if ( material.isMeshPhongMaterial ||
  14822. material.isMeshToonMaterial ||
  14823. material.isMeshLambertMaterial ||
  14824. material.isMeshBasicMaterial ||
  14825. material.isMeshStandardMaterial ||
  14826. material.isShaderMaterial ||
  14827. material.isShadowMaterial ||
  14828. object.isSkinnedMesh ) {
  14829. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  14830. }
  14831. }
  14832. // skinning uniforms must be set even if material didn't change
  14833. // auto-setting of texture unit for bone texture must go before other textures
  14834. // otherwise textures used for skinning can take over texture units reserved for other material textures
  14835. if ( object.isSkinnedMesh ) {
  14836. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  14837. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  14838. const skeleton = object.skeleton;
  14839. if ( skeleton ) {
  14840. if ( capabilities.floatVertexTextures ) {
  14841. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  14842. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  14843. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  14844. } else {
  14845. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  14846. }
  14847. }
  14848. }
  14849. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  14850. materialProperties.receiveShadow = object.receiveShadow;
  14851. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  14852. }
  14853. if ( refreshMaterial ) {
  14854. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  14855. if ( materialProperties.needsLights ) {
  14856. // the current material requires lighting info
  14857. // note: all lighting uniforms are always set correctly
  14858. // they simply reference the renderer's state for their
  14859. // values
  14860. //
  14861. // use the current material's .needsUpdate flags to set
  14862. // the GL state when required
  14863. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  14864. }
  14865. // refresh uniforms common to several materials
  14866. if ( fog && material.fog ) {
  14867. materials.refreshFogUniforms( m_uniforms, fog );
  14868. }
  14869. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget );
  14870. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  14871. }
  14872. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  14873. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  14874. material.uniformsNeedUpdate = false;
  14875. }
  14876. if ( material.isSpriteMaterial ) {
  14877. p_uniforms.setValue( _gl, 'center', object.center );
  14878. }
  14879. // common matrices
  14880. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  14881. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  14882. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  14883. return program;
  14884. }
  14885. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  14886. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  14887. uniforms.ambientLightColor.needsUpdate = value;
  14888. uniforms.lightProbe.needsUpdate = value;
  14889. uniforms.directionalLights.needsUpdate = value;
  14890. uniforms.directionalLightShadows.needsUpdate = value;
  14891. uniforms.pointLights.needsUpdate = value;
  14892. uniforms.pointLightShadows.needsUpdate = value;
  14893. uniforms.spotLights.needsUpdate = value;
  14894. uniforms.spotLightShadows.needsUpdate = value;
  14895. uniforms.rectAreaLights.needsUpdate = value;
  14896. uniforms.hemisphereLights.needsUpdate = value;
  14897. }
  14898. function materialNeedsLights( material ) {
  14899. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  14900. material.isMeshStandardMaterial || material.isShadowMaterial ||
  14901. ( material.isShaderMaterial && material.lights === true );
  14902. }
  14903. this.getActiveCubeFace = function () {
  14904. return _currentActiveCubeFace;
  14905. };
  14906. this.getActiveMipmapLevel = function () {
  14907. return _currentActiveMipmapLevel;
  14908. };
  14909. this.getRenderTarget = function () {
  14910. return _currentRenderTarget;
  14911. };
  14912. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  14913. _currentRenderTarget = renderTarget;
  14914. _currentActiveCubeFace = activeCubeFace;
  14915. _currentActiveMipmapLevel = activeMipmapLevel;
  14916. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  14917. textures.setupRenderTarget( renderTarget );
  14918. }
  14919. let framebuffer = null;
  14920. let isCube = false;
  14921. let isRenderTarget3D = false;
  14922. if ( renderTarget ) {
  14923. const texture = renderTarget.texture;
  14924. if ( texture.isDataTexture3D || texture.isDataTexture2DArray ) {
  14925. isRenderTarget3D = true;
  14926. }
  14927. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  14928. if ( renderTarget.isWebGLCubeRenderTarget ) {
  14929. framebuffer = __webglFramebuffer[ activeCubeFace ];
  14930. isCube = true;
  14931. } else if ( renderTarget.isWebGLMultisampleRenderTarget ) {
  14932. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  14933. } else {
  14934. framebuffer = __webglFramebuffer;
  14935. }
  14936. _currentViewport.copy( renderTarget.viewport );
  14937. _currentScissor.copy( renderTarget.scissor );
  14938. _currentScissorTest = renderTarget.scissorTest;
  14939. } else {
  14940. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  14941. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  14942. _currentScissorTest = _scissorTest;
  14943. }
  14944. const framebufferBound = state.bindFramebuffer( 36160, framebuffer );
  14945. if ( framebufferBound && capabilities.drawBuffers ) {
  14946. let needsUpdate = false;
  14947. if ( renderTarget ) {
  14948. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  14949. const textures = renderTarget.texture;
  14950. if ( _currentDrawBuffers.length !== textures.length || _currentDrawBuffers[ 0 ] !== 36064 ) {
  14951. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14952. _currentDrawBuffers[ i ] = 36064 + i;
  14953. }
  14954. _currentDrawBuffers.length = textures.length;
  14955. needsUpdate = true;
  14956. }
  14957. } else {
  14958. if ( _currentDrawBuffers.length !== 1 || _currentDrawBuffers[ 0 ] !== 36064 ) {
  14959. _currentDrawBuffers[ 0 ] = 36064;
  14960. _currentDrawBuffers.length = 1;
  14961. needsUpdate = true;
  14962. }
  14963. }
  14964. } else {
  14965. if ( _currentDrawBuffers.length !== 1 || _currentDrawBuffers[ 0 ] !== 1029 ) {
  14966. _currentDrawBuffers[ 0 ] = 1029;
  14967. _currentDrawBuffers.length = 1;
  14968. needsUpdate = true;
  14969. }
  14970. }
  14971. if ( needsUpdate ) {
  14972. if ( capabilities.isWebGL2 ) {
  14973. _gl.drawBuffers( _currentDrawBuffers );
  14974. } else {
  14975. extensions.get( 'WEBGL_draw_buffers' ).drawBuffersWEBGL( _currentDrawBuffers );
  14976. }
  14977. }
  14978. }
  14979. state.viewport( _currentViewport );
  14980. state.scissor( _currentScissor );
  14981. state.setScissorTest( _currentScissorTest );
  14982. if ( isCube ) {
  14983. const textureProperties = properties.get( renderTarget.texture );
  14984. _gl.framebufferTexture2D( 36160, 36064, 34069 + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  14985. } else if ( isRenderTarget3D ) {
  14986. const textureProperties = properties.get( renderTarget.texture );
  14987. const layer = activeCubeFace || 0;
  14988. _gl.framebufferTextureLayer( 36160, 36064, textureProperties.__webglTexture, activeMipmapLevel || 0, layer );
  14989. }
  14990. };
  14991. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  14992. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  14993. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  14994. return;
  14995. }
  14996. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  14997. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  14998. framebuffer = framebuffer[ activeCubeFaceIndex ];
  14999. }
  15000. if ( framebuffer ) {
  15001. state.bindFramebuffer( 36160, framebuffer );
  15002. try {
  15003. const texture = renderTarget.texture;
  15004. const textureFormat = texture.format;
  15005. const textureType = texture.type;
  15006. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( 35739 ) ) {
  15007. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  15008. return;
  15009. }
  15010. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || ( capabilities.isWebGL2 && extensions.has( 'EXT_color_buffer_float' ) ) );
  15011. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( 35738 ) && // Edge and Chrome Mac < 52 (#9513)
  15012. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.has( 'OES_texture_float' ) || extensions.has( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  15013. ! halfFloatSupportedByExt ) {
  15014. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  15015. return;
  15016. }
  15017. if ( _gl.checkFramebufferStatus( 36160 ) === 36053 ) {
  15018. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  15019. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  15020. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  15021. }
  15022. } else {
  15023. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  15024. }
  15025. } finally {
  15026. // restore framebuffer of current render target if necessary
  15027. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  15028. state.bindFramebuffer( 36160, framebuffer );
  15029. }
  15030. }
  15031. };
  15032. this.copyFramebufferToTexture = function ( position, texture, level = 0 ) {
  15033. const levelScale = Math.pow( 2, - level );
  15034. const width = Math.floor( texture.image.width * levelScale );
  15035. const height = Math.floor( texture.image.height * levelScale );
  15036. let glFormat = utils.convert( texture.format );
  15037. if ( capabilities.isWebGL2 ) {
  15038. // Workaround for https://bugs.chromium.org/p/chromium/issues/detail?id=1120100
  15039. // Not needed in Chrome 93+
  15040. if ( glFormat === 6407 ) glFormat = 32849;
  15041. if ( glFormat === 6408 ) glFormat = 32856;
  15042. }
  15043. textures.setTexture2D( texture, 0 );
  15044. _gl.copyTexImage2D( 3553, level, glFormat, position.x, position.y, width, height, 0 );
  15045. state.unbindTexture();
  15046. };
  15047. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) {
  15048. const width = srcTexture.image.width;
  15049. const height = srcTexture.image.height;
  15050. const glFormat = utils.convert( dstTexture.format );
  15051. const glType = utils.convert( dstTexture.type );
  15052. textures.setTexture2D( dstTexture, 0 );
  15053. // As another texture upload may have changed pixelStorei
  15054. // parameters, make sure they are correct for the dstTexture
  15055. _gl.pixelStorei( 37440, dstTexture.flipY );
  15056. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  15057. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  15058. if ( srcTexture.isDataTexture ) {
  15059. _gl.texSubImage2D( 3553, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  15060. } else {
  15061. if ( srcTexture.isCompressedTexture ) {
  15062. _gl.compressedTexSubImage2D( 3553, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data );
  15063. } else {
  15064. _gl.texSubImage2D( 3553, level, position.x, position.y, glFormat, glType, srcTexture.image );
  15065. }
  15066. }
  15067. // Generate mipmaps only when copying level 0
  15068. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( 3553 );
  15069. state.unbindTexture();
  15070. };
  15071. this.copyTextureToTexture3D = function ( sourceBox, position, srcTexture, dstTexture, level = 0 ) {
  15072. if ( _this.isWebGL1Renderer ) {
  15073. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.' );
  15074. return;
  15075. }
  15076. const width = sourceBox.max.x - sourceBox.min.x + 1;
  15077. const height = sourceBox.max.y - sourceBox.min.y + 1;
  15078. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  15079. const glFormat = utils.convert( dstTexture.format );
  15080. const glType = utils.convert( dstTexture.type );
  15081. let glTarget;
  15082. if ( dstTexture.isDataTexture3D ) {
  15083. textures.setTexture3D( dstTexture, 0 );
  15084. glTarget = 32879;
  15085. } else if ( dstTexture.isDataTexture2DArray ) {
  15086. textures.setTexture2DArray( dstTexture, 0 );
  15087. glTarget = 35866;
  15088. } else {
  15089. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' );
  15090. return;
  15091. }
  15092. _gl.pixelStorei( 37440, dstTexture.flipY );
  15093. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  15094. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  15095. const unpackRowLen = _gl.getParameter( 3314 );
  15096. const unpackImageHeight = _gl.getParameter( 32878 );
  15097. const unpackSkipPixels = _gl.getParameter( 3316 );
  15098. const unpackSkipRows = _gl.getParameter( 3315 );
  15099. const unpackSkipImages = _gl.getParameter( 32877 );
  15100. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ 0 ] : srcTexture.image;
  15101. _gl.pixelStorei( 3314, image.width );
  15102. _gl.pixelStorei( 32878, image.height );
  15103. _gl.pixelStorei( 3316, sourceBox.min.x );
  15104. _gl.pixelStorei( 3315, sourceBox.min.y );
  15105. _gl.pixelStorei( 32877, sourceBox.min.z );
  15106. if ( srcTexture.isDataTexture || srcTexture.isDataTexture3D ) {
  15107. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data );
  15108. } else {
  15109. if ( srcTexture.isCompressedTexture ) {
  15110. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.' );
  15111. _gl.compressedTexSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data );
  15112. } else {
  15113. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image );
  15114. }
  15115. }
  15116. _gl.pixelStorei( 3314, unpackRowLen );
  15117. _gl.pixelStorei( 32878, unpackImageHeight );
  15118. _gl.pixelStorei( 3316, unpackSkipPixels );
  15119. _gl.pixelStorei( 3315, unpackSkipRows );
  15120. _gl.pixelStorei( 32877, unpackSkipImages );
  15121. // Generate mipmaps only when copying level 0
  15122. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget );
  15123. state.unbindTexture();
  15124. };
  15125. this.initTexture = function ( texture ) {
  15126. textures.setTexture2D( texture, 0 );
  15127. state.unbindTexture();
  15128. };
  15129. this.resetState = function () {
  15130. _currentActiveCubeFace = 0;
  15131. _currentActiveMipmapLevel = 0;
  15132. _currentRenderTarget = null;
  15133. state.reset();
  15134. bindingStates.reset();
  15135. };
  15136. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  15137. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef
  15138. }
  15139. }
  15140. class WebGL1Renderer extends WebGLRenderer {}
  15141. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  15142. class Scene extends Object3D {
  15143. constructor() {
  15144. super();
  15145. this.type = 'Scene';
  15146. this.background = null;
  15147. this.environment = null;
  15148. this.fog = null;
  15149. this.overrideMaterial = null;
  15150. this.autoUpdate = true; // checked by the renderer
  15151. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  15152. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef
  15153. }
  15154. }
  15155. copy( source, recursive ) {
  15156. super.copy( source, recursive );
  15157. if ( source.background !== null ) this.background = source.background.clone();
  15158. if ( source.environment !== null ) this.environment = source.environment.clone();
  15159. if ( source.fog !== null ) this.fog = source.fog.clone();
  15160. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  15161. this.autoUpdate = source.autoUpdate;
  15162. this.matrixAutoUpdate = source.matrixAutoUpdate;
  15163. return this;
  15164. }
  15165. toJSON( meta ) {
  15166. const data = super.toJSON( meta );
  15167. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  15168. return data;
  15169. }
  15170. }
  15171. Scene.prototype.isScene = true;
  15172. class InterleavedBuffer {
  15173. constructor( array, stride ) {
  15174. this.array = array;
  15175. this.stride = stride;
  15176. this.count = array !== undefined ? array.length / stride : 0;
  15177. this.usage = StaticDrawUsage;
  15178. this.updateRange = { offset: 0, count: - 1 };
  15179. this.version = 0;
  15180. this.uuid = generateUUID();
  15181. }
  15182. onUploadCallback() {}
  15183. set needsUpdate( value ) {
  15184. if ( value === true ) this.version ++;
  15185. }
  15186. setUsage( value ) {
  15187. this.usage = value;
  15188. return this;
  15189. }
  15190. copy( source ) {
  15191. this.array = new source.array.constructor( source.array );
  15192. this.count = source.count;
  15193. this.stride = source.stride;
  15194. this.usage = source.usage;
  15195. return this;
  15196. }
  15197. copyAt( index1, attribute, index2 ) {
  15198. index1 *= this.stride;
  15199. index2 *= attribute.stride;
  15200. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  15201. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  15202. }
  15203. return this;
  15204. }
  15205. set( value, offset = 0 ) {
  15206. this.array.set( value, offset );
  15207. return this;
  15208. }
  15209. clone( data ) {
  15210. if ( data.arrayBuffers === undefined ) {
  15211. data.arrayBuffers = {};
  15212. }
  15213. if ( this.array.buffer._uuid === undefined ) {
  15214. this.array.buffer._uuid = generateUUID();
  15215. }
  15216. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  15217. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  15218. }
  15219. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  15220. const ib = new this.constructor( array, this.stride );
  15221. ib.setUsage( this.usage );
  15222. return ib;
  15223. }
  15224. onUpload( callback ) {
  15225. this.onUploadCallback = callback;
  15226. return this;
  15227. }
  15228. toJSON( data ) {
  15229. if ( data.arrayBuffers === undefined ) {
  15230. data.arrayBuffers = {};
  15231. }
  15232. // generate UUID for array buffer if necessary
  15233. if ( this.array.buffer._uuid === undefined ) {
  15234. this.array.buffer._uuid = generateUUID();
  15235. }
  15236. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  15237. data.arrayBuffers[ this.array.buffer._uuid ] = Array.prototype.slice.call( new Uint32Array( this.array.buffer ) );
  15238. }
  15239. //
  15240. return {
  15241. uuid: this.uuid,
  15242. buffer: this.array.buffer._uuid,
  15243. type: this.array.constructor.name,
  15244. stride: this.stride
  15245. };
  15246. }
  15247. }
  15248. InterleavedBuffer.prototype.isInterleavedBuffer = true;
  15249. const _vector$6 = /*@__PURE__*/ new Vector3();
  15250. class InterleavedBufferAttribute {
  15251. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  15252. this.name = '';
  15253. this.data = interleavedBuffer;
  15254. this.itemSize = itemSize;
  15255. this.offset = offset;
  15256. this.normalized = normalized === true;
  15257. }
  15258. get count() {
  15259. return this.data.count;
  15260. }
  15261. get array() {
  15262. return this.data.array;
  15263. }
  15264. set needsUpdate( value ) {
  15265. this.data.needsUpdate = value;
  15266. }
  15267. applyMatrix4( m ) {
  15268. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  15269. _vector$6.x = this.getX( i );
  15270. _vector$6.y = this.getY( i );
  15271. _vector$6.z = this.getZ( i );
  15272. _vector$6.applyMatrix4( m );
  15273. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  15274. }
  15275. return this;
  15276. }
  15277. applyNormalMatrix( m ) {
  15278. for ( let i = 0, l = this.count; i < l; i ++ ) {
  15279. _vector$6.x = this.getX( i );
  15280. _vector$6.y = this.getY( i );
  15281. _vector$6.z = this.getZ( i );
  15282. _vector$6.applyNormalMatrix( m );
  15283. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  15284. }
  15285. return this;
  15286. }
  15287. transformDirection( m ) {
  15288. for ( let i = 0, l = this.count; i < l; i ++ ) {
  15289. _vector$6.x = this.getX( i );
  15290. _vector$6.y = this.getY( i );
  15291. _vector$6.z = this.getZ( i );
  15292. _vector$6.transformDirection( m );
  15293. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  15294. }
  15295. return this;
  15296. }
  15297. setX( index, x ) {
  15298. this.data.array[ index * this.data.stride + this.offset ] = x;
  15299. return this;
  15300. }
  15301. setY( index, y ) {
  15302. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  15303. return this;
  15304. }
  15305. setZ( index, z ) {
  15306. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  15307. return this;
  15308. }
  15309. setW( index, w ) {
  15310. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  15311. return this;
  15312. }
  15313. getX( index ) {
  15314. return this.data.array[ index * this.data.stride + this.offset ];
  15315. }
  15316. getY( index ) {
  15317. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  15318. }
  15319. getZ( index ) {
  15320. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  15321. }
  15322. getW( index ) {
  15323. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  15324. }
  15325. setXY( index, x, y ) {
  15326. index = index * this.data.stride + this.offset;
  15327. this.data.array[ index + 0 ] = x;
  15328. this.data.array[ index + 1 ] = y;
  15329. return this;
  15330. }
  15331. setXYZ( index, x, y, z ) {
  15332. index = index * this.data.stride + this.offset;
  15333. this.data.array[ index + 0 ] = x;
  15334. this.data.array[ index + 1 ] = y;
  15335. this.data.array[ index + 2 ] = z;
  15336. return this;
  15337. }
  15338. setXYZW( index, x, y, z, w ) {
  15339. index = index * this.data.stride + this.offset;
  15340. this.data.array[ index + 0 ] = x;
  15341. this.data.array[ index + 1 ] = y;
  15342. this.data.array[ index + 2 ] = z;
  15343. this.data.array[ index + 3 ] = w;
  15344. return this;
  15345. }
  15346. clone( data ) {
  15347. if ( data === undefined ) {
  15348. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.' );
  15349. const array = [];
  15350. for ( let i = 0; i < this.count; i ++ ) {
  15351. const index = i * this.data.stride + this.offset;
  15352. for ( let j = 0; j < this.itemSize; j ++ ) {
  15353. array.push( this.data.array[ index + j ] );
  15354. }
  15355. }
  15356. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  15357. } else {
  15358. if ( data.interleavedBuffers === undefined ) {
  15359. data.interleavedBuffers = {};
  15360. }
  15361. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  15362. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  15363. }
  15364. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  15365. }
  15366. }
  15367. toJSON( data ) {
  15368. if ( data === undefined ) {
  15369. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.' );
  15370. const array = [];
  15371. for ( let i = 0; i < this.count; i ++ ) {
  15372. const index = i * this.data.stride + this.offset;
  15373. for ( let j = 0; j < this.itemSize; j ++ ) {
  15374. array.push( this.data.array[ index + j ] );
  15375. }
  15376. }
  15377. // deinterleave data and save it as an ordinary buffer attribute for now
  15378. return {
  15379. itemSize: this.itemSize,
  15380. type: this.array.constructor.name,
  15381. array: array,
  15382. normalized: this.normalized
  15383. };
  15384. } else {
  15385. // save as true interlaved attribtue
  15386. if ( data.interleavedBuffers === undefined ) {
  15387. data.interleavedBuffers = {};
  15388. }
  15389. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  15390. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  15391. }
  15392. return {
  15393. isInterleavedBufferAttribute: true,
  15394. itemSize: this.itemSize,
  15395. data: this.data.uuid,
  15396. offset: this.offset,
  15397. normalized: this.normalized
  15398. };
  15399. }
  15400. }
  15401. }
  15402. InterleavedBufferAttribute.prototype.isInterleavedBufferAttribute = true;
  15403. /**
  15404. * parameters = {
  15405. * color: <hex>,
  15406. * map: new THREE.Texture( <Image> ),
  15407. * alphaMap: new THREE.Texture( <Image> ),
  15408. * rotation: <float>,
  15409. * sizeAttenuation: <bool>
  15410. * }
  15411. */
  15412. class SpriteMaterial extends Material {
  15413. constructor( parameters ) {
  15414. super();
  15415. this.type = 'SpriteMaterial';
  15416. this.color = new Color( 0xffffff );
  15417. this.map = null;
  15418. this.alphaMap = null;
  15419. this.rotation = 0;
  15420. this.sizeAttenuation = true;
  15421. this.transparent = true;
  15422. this.setValues( parameters );
  15423. }
  15424. copy( source ) {
  15425. super.copy( source );
  15426. this.color.copy( source.color );
  15427. this.map = source.map;
  15428. this.alphaMap = source.alphaMap;
  15429. this.rotation = source.rotation;
  15430. this.sizeAttenuation = source.sizeAttenuation;
  15431. return this;
  15432. }
  15433. }
  15434. SpriteMaterial.prototype.isSpriteMaterial = true;
  15435. let _geometry$2;
  15436. const _intersectPoint = /*@__PURE__*/ new Vector3();
  15437. const _worldScale = /*@__PURE__*/ new Vector3();
  15438. const _mvPosition = /*@__PURE__*/ new Vector3();
  15439. const _alignedPosition = /*@__PURE__*/ new Vector2();
  15440. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  15441. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  15442. const _vA = /*@__PURE__*/ new Vector3();
  15443. const _vB = /*@__PURE__*/ new Vector3();
  15444. const _vC = /*@__PURE__*/ new Vector3();
  15445. const _uvA = /*@__PURE__*/ new Vector2();
  15446. const _uvB = /*@__PURE__*/ new Vector2();
  15447. const _uvC = /*@__PURE__*/ new Vector2();
  15448. class Sprite extends Object3D {
  15449. constructor( material ) {
  15450. super();
  15451. this.type = 'Sprite';
  15452. if ( _geometry$2 === undefined ) {
  15453. _geometry$2 = new BufferGeometry();
  15454. const float32Array = new Float32Array( [
  15455. - 0.5, - 0.5, 0, 0, 0,
  15456. 0.5, - 0.5, 0, 1, 0,
  15457. 0.5, 0.5, 0, 1, 1,
  15458. - 0.5, 0.5, 0, 0, 1
  15459. ] );
  15460. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  15461. _geometry$2.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  15462. _geometry$2.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  15463. _geometry$2.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  15464. }
  15465. this.geometry = _geometry$2;
  15466. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  15467. this.center = new Vector2( 0.5, 0.5 );
  15468. }
  15469. raycast( raycaster, intersects ) {
  15470. if ( raycaster.camera === null ) {
  15471. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  15472. }
  15473. _worldScale.setFromMatrixScale( this.matrixWorld );
  15474. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  15475. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  15476. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  15477. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  15478. _worldScale.multiplyScalar( - _mvPosition.z );
  15479. }
  15480. const rotation = this.material.rotation;
  15481. let sin, cos;
  15482. if ( rotation !== 0 ) {
  15483. cos = Math.cos( rotation );
  15484. sin = Math.sin( rotation );
  15485. }
  15486. const center = this.center;
  15487. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  15488. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  15489. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  15490. _uvA.set( 0, 0 );
  15491. _uvB.set( 1, 0 );
  15492. _uvC.set( 1, 1 );
  15493. // check first triangle
  15494. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  15495. if ( intersect === null ) {
  15496. // check second triangle
  15497. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  15498. _uvB.set( 0, 1 );
  15499. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  15500. if ( intersect === null ) {
  15501. return;
  15502. }
  15503. }
  15504. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  15505. if ( distance < raycaster.near || distance > raycaster.far ) return;
  15506. intersects.push( {
  15507. distance: distance,
  15508. point: _intersectPoint.clone(),
  15509. uv: Triangle.getUV( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  15510. face: null,
  15511. object: this
  15512. } );
  15513. }
  15514. copy( source ) {
  15515. super.copy( source );
  15516. if ( source.center !== undefined ) this.center.copy( source.center );
  15517. this.material = source.material;
  15518. return this;
  15519. }
  15520. }
  15521. Sprite.prototype.isSprite = true;
  15522. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  15523. // compute position in camera space
  15524. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  15525. // to check if rotation is not zero
  15526. if ( sin !== undefined ) {
  15527. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  15528. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  15529. } else {
  15530. _rotatedPosition.copy( _alignedPosition );
  15531. }
  15532. vertexPosition.copy( mvPosition );
  15533. vertexPosition.x += _rotatedPosition.x;
  15534. vertexPosition.y += _rotatedPosition.y;
  15535. // transform to world space
  15536. vertexPosition.applyMatrix4( _viewWorldMatrix );
  15537. }
  15538. const _basePosition = /*@__PURE__*/ new Vector3();
  15539. const _skinIndex = /*@__PURE__*/ new Vector4();
  15540. const _skinWeight = /*@__PURE__*/ new Vector4();
  15541. const _vector$5 = /*@__PURE__*/ new Vector3();
  15542. const _matrix = /*@__PURE__*/ new Matrix4();
  15543. class SkinnedMesh extends Mesh {
  15544. constructor( geometry, material ) {
  15545. super( geometry, material );
  15546. this.type = 'SkinnedMesh';
  15547. this.bindMode = 'attached';
  15548. this.bindMatrix = new Matrix4();
  15549. this.bindMatrixInverse = new Matrix4();
  15550. }
  15551. copy( source ) {
  15552. super.copy( source );
  15553. this.bindMode = source.bindMode;
  15554. this.bindMatrix.copy( source.bindMatrix );
  15555. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  15556. this.skeleton = source.skeleton;
  15557. return this;
  15558. }
  15559. bind( skeleton, bindMatrix ) {
  15560. this.skeleton = skeleton;
  15561. if ( bindMatrix === undefined ) {
  15562. this.updateMatrixWorld( true );
  15563. this.skeleton.calculateInverses();
  15564. bindMatrix = this.matrixWorld;
  15565. }
  15566. this.bindMatrix.copy( bindMatrix );
  15567. this.bindMatrixInverse.copy( bindMatrix ).invert();
  15568. }
  15569. pose() {
  15570. this.skeleton.pose();
  15571. }
  15572. normalizeSkinWeights() {
  15573. const vector = new Vector4();
  15574. const skinWeight = this.geometry.attributes.skinWeight;
  15575. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  15576. vector.x = skinWeight.getX( i );
  15577. vector.y = skinWeight.getY( i );
  15578. vector.z = skinWeight.getZ( i );
  15579. vector.w = skinWeight.getW( i );
  15580. const scale = 1.0 / vector.manhattanLength();
  15581. if ( scale !== Infinity ) {
  15582. vector.multiplyScalar( scale );
  15583. } else {
  15584. vector.set( 1, 0, 0, 0 ); // do something reasonable
  15585. }
  15586. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  15587. }
  15588. }
  15589. updateMatrixWorld( force ) {
  15590. super.updateMatrixWorld( force );
  15591. if ( this.bindMode === 'attached' ) {
  15592. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  15593. } else if ( this.bindMode === 'detached' ) {
  15594. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  15595. } else {
  15596. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  15597. }
  15598. }
  15599. boneTransform( index, target ) {
  15600. const skeleton = this.skeleton;
  15601. const geometry = this.geometry;
  15602. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  15603. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  15604. _basePosition.fromBufferAttribute( geometry.attributes.position, index ).applyMatrix4( this.bindMatrix );
  15605. target.set( 0, 0, 0 );
  15606. for ( let i = 0; i < 4; i ++ ) {
  15607. const weight = _skinWeight.getComponent( i );
  15608. if ( weight !== 0 ) {
  15609. const boneIndex = _skinIndex.getComponent( i );
  15610. _matrix.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  15611. target.addScaledVector( _vector$5.copy( _basePosition ).applyMatrix4( _matrix ), weight );
  15612. }
  15613. }
  15614. return target.applyMatrix4( this.bindMatrixInverse );
  15615. }
  15616. }
  15617. SkinnedMesh.prototype.isSkinnedMesh = true;
  15618. class Bone extends Object3D {
  15619. constructor() {
  15620. super();
  15621. this.type = 'Bone';
  15622. }
  15623. }
  15624. Bone.prototype.isBone = true;
  15625. class DataTexture extends Texture {
  15626. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding ) {
  15627. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  15628. this.image = { data: data, width: width, height: height };
  15629. this.magFilter = magFilter;
  15630. this.minFilter = minFilter;
  15631. this.generateMipmaps = false;
  15632. this.flipY = false;
  15633. this.unpackAlignment = 1;
  15634. this.needsUpdate = true;
  15635. }
  15636. }
  15637. DataTexture.prototype.isDataTexture = true;
  15638. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  15639. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  15640. const _instanceIntersects = [];
  15641. const _mesh = /*@__PURE__*/ new Mesh();
  15642. class InstancedMesh extends Mesh {
  15643. constructor( geometry, material, count ) {
  15644. super( geometry, material );
  15645. this.instanceMatrix = new BufferAttribute( new Float32Array( count * 16 ), 16 );
  15646. this.instanceColor = null;
  15647. this.count = count;
  15648. this.frustumCulled = false;
  15649. }
  15650. copy( source ) {
  15651. super.copy( source );
  15652. this.instanceMatrix.copy( source.instanceMatrix );
  15653. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  15654. this.count = source.count;
  15655. return this;
  15656. }
  15657. getColorAt( index, color ) {
  15658. color.fromArray( this.instanceColor.array, index * 3 );
  15659. }
  15660. getMatrixAt( index, matrix ) {
  15661. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  15662. }
  15663. raycast( raycaster, intersects ) {
  15664. const matrixWorld = this.matrixWorld;
  15665. const raycastTimes = this.count;
  15666. _mesh.geometry = this.geometry;
  15667. _mesh.material = this.material;
  15668. if ( _mesh.material === undefined ) return;
  15669. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  15670. // calculate the world matrix for each instance
  15671. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  15672. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  15673. // the mesh represents this single instance
  15674. _mesh.matrixWorld = _instanceWorldMatrix;
  15675. _mesh.raycast( raycaster, _instanceIntersects );
  15676. // process the result of raycast
  15677. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  15678. const intersect = _instanceIntersects[ i ];
  15679. intersect.instanceId = instanceId;
  15680. intersect.object = this;
  15681. intersects.push( intersect );
  15682. }
  15683. _instanceIntersects.length = 0;
  15684. }
  15685. }
  15686. setColorAt( index, color ) {
  15687. if ( this.instanceColor === null ) {
  15688. this.instanceColor = new BufferAttribute( new Float32Array( this.count * 3 ), 3 );
  15689. }
  15690. color.toArray( this.instanceColor.array, index * 3 );
  15691. }
  15692. setMatrixAt( index, matrix ) {
  15693. matrix.toArray( this.instanceMatrix.array, index * 16 );
  15694. }
  15695. updateMorphTargets() {
  15696. }
  15697. dispose() {
  15698. this.dispatchEvent( { type: 'dispose' } );
  15699. }
  15700. }
  15701. InstancedMesh.prototype.isInstancedMesh = true;
  15702. /**
  15703. * parameters = {
  15704. * color: <hex>,
  15705. * opacity: <float>,
  15706. *
  15707. * linewidth: <float>,
  15708. * linecap: "round",
  15709. * linejoin: "round"
  15710. * }
  15711. */
  15712. class LineBasicMaterial extends Material {
  15713. constructor( parameters ) {
  15714. super();
  15715. this.type = 'LineBasicMaterial';
  15716. this.color = new Color( 0xffffff );
  15717. this.linewidth = 1;
  15718. this.linecap = 'round';
  15719. this.linejoin = 'round';
  15720. this.morphTargets = false;
  15721. this.setValues( parameters );
  15722. }
  15723. copy( source ) {
  15724. super.copy( source );
  15725. this.color.copy( source.color );
  15726. this.linewidth = source.linewidth;
  15727. this.linecap = source.linecap;
  15728. this.linejoin = source.linejoin;
  15729. this.morphTargets = source.morphTargets;
  15730. return this;
  15731. }
  15732. }
  15733. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  15734. const _start$1 = /*@__PURE__*/ new Vector3();
  15735. const _end$1 = /*@__PURE__*/ new Vector3();
  15736. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  15737. const _ray$1 = /*@__PURE__*/ new Ray();
  15738. const _sphere$1 = /*@__PURE__*/ new Sphere();
  15739. class Line extends Object3D {
  15740. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  15741. super();
  15742. this.type = 'Line';
  15743. this.geometry = geometry;
  15744. this.material = material;
  15745. this.updateMorphTargets();
  15746. }
  15747. copy( source ) {
  15748. super.copy( source );
  15749. this.material = source.material;
  15750. this.geometry = source.geometry;
  15751. return this;
  15752. }
  15753. computeLineDistances() {
  15754. const geometry = this.geometry;
  15755. if ( geometry.isBufferGeometry ) {
  15756. // we assume non-indexed geometry
  15757. if ( geometry.index === null ) {
  15758. const positionAttribute = geometry.attributes.position;
  15759. const lineDistances = [ 0 ];
  15760. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  15761. _start$1.fromBufferAttribute( positionAttribute, i - 1 );
  15762. _end$1.fromBufferAttribute( positionAttribute, i );
  15763. lineDistances[ i ] = lineDistances[ i - 1 ];
  15764. lineDistances[ i ] += _start$1.distanceTo( _end$1 );
  15765. }
  15766. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  15767. } else {
  15768. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  15769. }
  15770. } else if ( geometry.isGeometry ) {
  15771. console.error( 'THREE.Line.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  15772. }
  15773. return this;
  15774. }
  15775. raycast( raycaster, intersects ) {
  15776. const geometry = this.geometry;
  15777. const matrixWorld = this.matrixWorld;
  15778. const threshold = raycaster.params.Line.threshold;
  15779. const drawRange = geometry.drawRange;
  15780. // Checking boundingSphere distance to ray
  15781. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  15782. _sphere$1.copy( geometry.boundingSphere );
  15783. _sphere$1.applyMatrix4( matrixWorld );
  15784. _sphere$1.radius += threshold;
  15785. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  15786. //
  15787. _inverseMatrix$1.copy( matrixWorld ).invert();
  15788. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  15789. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  15790. const localThresholdSq = localThreshold * localThreshold;
  15791. const vStart = new Vector3();
  15792. const vEnd = new Vector3();
  15793. const interSegment = new Vector3();
  15794. const interRay = new Vector3();
  15795. const step = this.isLineSegments ? 2 : 1;
  15796. if ( geometry.isBufferGeometry ) {
  15797. const index = geometry.index;
  15798. const attributes = geometry.attributes;
  15799. const positionAttribute = attributes.position;
  15800. if ( index !== null ) {
  15801. const start = Math.max( 0, drawRange.start );
  15802. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  15803. for ( let i = start, l = end - 1; i < l; i += step ) {
  15804. const a = index.getX( i );
  15805. const b = index.getX( i + 1 );
  15806. vStart.fromBufferAttribute( positionAttribute, a );
  15807. vEnd.fromBufferAttribute( positionAttribute, b );
  15808. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  15809. if ( distSq > localThresholdSq ) continue;
  15810. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  15811. const distance = raycaster.ray.origin.distanceTo( interRay );
  15812. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  15813. intersects.push( {
  15814. distance: distance,
  15815. // What do we want? intersection point on the ray or on the segment??
  15816. // point: raycaster.ray.at( distance ),
  15817. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  15818. index: i,
  15819. face: null,
  15820. faceIndex: null,
  15821. object: this
  15822. } );
  15823. }
  15824. } else {
  15825. const start = Math.max( 0, drawRange.start );
  15826. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  15827. for ( let i = start, l = end - 1; i < l; i += step ) {
  15828. vStart.fromBufferAttribute( positionAttribute, i );
  15829. vEnd.fromBufferAttribute( positionAttribute, i + 1 );
  15830. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  15831. if ( distSq > localThresholdSq ) continue;
  15832. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  15833. const distance = raycaster.ray.origin.distanceTo( interRay );
  15834. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  15835. intersects.push( {
  15836. distance: distance,
  15837. // What do we want? intersection point on the ray or on the segment??
  15838. // point: raycaster.ray.at( distance ),
  15839. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  15840. index: i,
  15841. face: null,
  15842. faceIndex: null,
  15843. object: this
  15844. } );
  15845. }
  15846. }
  15847. } else if ( geometry.isGeometry ) {
  15848. console.error( 'THREE.Line.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  15849. }
  15850. }
  15851. updateMorphTargets() {
  15852. const geometry = this.geometry;
  15853. if ( geometry.isBufferGeometry ) {
  15854. const morphAttributes = geometry.morphAttributes;
  15855. const keys = Object.keys( morphAttributes );
  15856. if ( keys.length > 0 ) {
  15857. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  15858. if ( morphAttribute !== undefined ) {
  15859. this.morphTargetInfluences = [];
  15860. this.morphTargetDictionary = {};
  15861. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  15862. const name = morphAttribute[ m ].name || String( m );
  15863. this.morphTargetInfluences.push( 0 );
  15864. this.morphTargetDictionary[ name ] = m;
  15865. }
  15866. }
  15867. }
  15868. } else {
  15869. const morphTargets = geometry.morphTargets;
  15870. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  15871. console.error( 'THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' );
  15872. }
  15873. }
  15874. }
  15875. }
  15876. Line.prototype.isLine = true;
  15877. const _start = /*@__PURE__*/ new Vector3();
  15878. const _end = /*@__PURE__*/ new Vector3();
  15879. class LineSegments extends Line {
  15880. constructor( geometry, material ) {
  15881. super( geometry, material );
  15882. this.type = 'LineSegments';
  15883. }
  15884. computeLineDistances() {
  15885. const geometry = this.geometry;
  15886. if ( geometry.isBufferGeometry ) {
  15887. // we assume non-indexed geometry
  15888. if ( geometry.index === null ) {
  15889. const positionAttribute = geometry.attributes.position;
  15890. const lineDistances = [];
  15891. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  15892. _start.fromBufferAttribute( positionAttribute, i );
  15893. _end.fromBufferAttribute( positionAttribute, i + 1 );
  15894. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  15895. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  15896. }
  15897. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  15898. } else {
  15899. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  15900. }
  15901. } else if ( geometry.isGeometry ) {
  15902. console.error( 'THREE.LineSegments.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  15903. }
  15904. return this;
  15905. }
  15906. }
  15907. LineSegments.prototype.isLineSegments = true;
  15908. class LineLoop extends Line {
  15909. constructor( geometry, material ) {
  15910. super( geometry, material );
  15911. this.type = 'LineLoop';
  15912. }
  15913. }
  15914. LineLoop.prototype.isLineLoop = true;
  15915. /**
  15916. * parameters = {
  15917. * color: <hex>,
  15918. * opacity: <float>,
  15919. * map: new THREE.Texture( <Image> ),
  15920. * alphaMap: new THREE.Texture( <Image> ),
  15921. *
  15922. * size: <float>,
  15923. * sizeAttenuation: <bool>
  15924. *
  15925. * morphTargets: <bool>
  15926. * }
  15927. */
  15928. class PointsMaterial extends Material {
  15929. constructor( parameters ) {
  15930. super();
  15931. this.type = 'PointsMaterial';
  15932. this.color = new Color( 0xffffff );
  15933. this.map = null;
  15934. this.alphaMap = null;
  15935. this.size = 1;
  15936. this.sizeAttenuation = true;
  15937. this.morphTargets = false;
  15938. this.setValues( parameters );
  15939. }
  15940. copy( source ) {
  15941. super.copy( source );
  15942. this.color.copy( source.color );
  15943. this.map = source.map;
  15944. this.alphaMap = source.alphaMap;
  15945. this.size = source.size;
  15946. this.sizeAttenuation = source.sizeAttenuation;
  15947. this.morphTargets = source.morphTargets;
  15948. return this;
  15949. }
  15950. }
  15951. PointsMaterial.prototype.isPointsMaterial = true;
  15952. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  15953. const _ray = /*@__PURE__*/ new Ray();
  15954. const _sphere = /*@__PURE__*/ new Sphere();
  15955. const _position$2 = /*@__PURE__*/ new Vector3();
  15956. class Points extends Object3D {
  15957. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  15958. super();
  15959. this.type = 'Points';
  15960. this.geometry = geometry;
  15961. this.material = material;
  15962. this.updateMorphTargets();
  15963. }
  15964. copy( source ) {
  15965. super.copy( source );
  15966. this.material = source.material;
  15967. this.geometry = source.geometry;
  15968. return this;
  15969. }
  15970. raycast( raycaster, intersects ) {
  15971. const geometry = this.geometry;
  15972. const matrixWorld = this.matrixWorld;
  15973. const threshold = raycaster.params.Points.threshold;
  15974. const drawRange = geometry.drawRange;
  15975. // Checking boundingSphere distance to ray
  15976. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  15977. _sphere.copy( geometry.boundingSphere );
  15978. _sphere.applyMatrix4( matrixWorld );
  15979. _sphere.radius += threshold;
  15980. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  15981. //
  15982. _inverseMatrix$3.copy( matrixWorld ).invert();
  15983. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  15984. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  15985. const localThresholdSq = localThreshold * localThreshold;
  15986. if ( geometry.isBufferGeometry ) {
  15987. const index = geometry.index;
  15988. const attributes = geometry.attributes;
  15989. const positionAttribute = attributes.position;
  15990. if ( index !== null ) {
  15991. const start = Math.max( 0, drawRange.start );
  15992. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  15993. for ( let i = start, il = end; i < il; i ++ ) {
  15994. const a = index.getX( i );
  15995. _position$2.fromBufferAttribute( positionAttribute, a );
  15996. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  15997. }
  15998. } else {
  15999. const start = Math.max( 0, drawRange.start );
  16000. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  16001. for ( let i = start, l = end; i < l; i ++ ) {
  16002. _position$2.fromBufferAttribute( positionAttribute, i );
  16003. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  16004. }
  16005. }
  16006. } else {
  16007. console.error( 'THREE.Points.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  16008. }
  16009. }
  16010. updateMorphTargets() {
  16011. const geometry = this.geometry;
  16012. if ( geometry.isBufferGeometry ) {
  16013. const morphAttributes = geometry.morphAttributes;
  16014. const keys = Object.keys( morphAttributes );
  16015. if ( keys.length > 0 ) {
  16016. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  16017. if ( morphAttribute !== undefined ) {
  16018. this.morphTargetInfluences = [];
  16019. this.morphTargetDictionary = {};
  16020. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  16021. const name = morphAttribute[ m ].name || String( m );
  16022. this.morphTargetInfluences.push( 0 );
  16023. this.morphTargetDictionary[ name ] = m;
  16024. }
  16025. }
  16026. }
  16027. } else {
  16028. const morphTargets = geometry.morphTargets;
  16029. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  16030. console.error( 'THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' );
  16031. }
  16032. }
  16033. }
  16034. }
  16035. Points.prototype.isPoints = true;
  16036. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  16037. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  16038. if ( rayPointDistanceSq < localThresholdSq ) {
  16039. const intersectPoint = new Vector3();
  16040. _ray.closestPointToPoint( point, intersectPoint );
  16041. intersectPoint.applyMatrix4( matrixWorld );
  16042. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  16043. if ( distance < raycaster.near || distance > raycaster.far ) return;
  16044. intersects.push( {
  16045. distance: distance,
  16046. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  16047. point: intersectPoint,
  16048. index: index,
  16049. face: null,
  16050. object: object
  16051. } );
  16052. }
  16053. }
  16054. class VideoTexture extends Texture {
  16055. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  16056. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  16057. this.format = format !== undefined ? format : RGBFormat;
  16058. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  16059. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  16060. this.generateMipmaps = false;
  16061. const scope = this;
  16062. function updateVideo() {
  16063. scope.needsUpdate = true;
  16064. video.requestVideoFrameCallback( updateVideo );
  16065. }
  16066. if ( 'requestVideoFrameCallback' in video ) {
  16067. video.requestVideoFrameCallback( updateVideo );
  16068. }
  16069. }
  16070. clone() {
  16071. return new this.constructor( this.image ).copy( this );
  16072. }
  16073. update() {
  16074. const video = this.image;
  16075. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  16076. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  16077. this.needsUpdate = true;
  16078. }
  16079. }
  16080. }
  16081. VideoTexture.prototype.isVideoTexture = true;
  16082. class CompressedTexture extends Texture {
  16083. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  16084. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  16085. this.image = { width: width, height: height };
  16086. this.mipmaps = mipmaps;
  16087. // no flipping for cube textures
  16088. // (also flipping doesn't work for compressed textures )
  16089. this.flipY = false;
  16090. // can't generate mipmaps for compressed textures
  16091. // mips must be embedded in DDS files
  16092. this.generateMipmaps = false;
  16093. }
  16094. }
  16095. CompressedTexture.prototype.isCompressedTexture = true;
  16096. class CanvasTexture extends Texture {
  16097. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  16098. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  16099. this.needsUpdate = true;
  16100. }
  16101. }
  16102. CanvasTexture.prototype.isCanvasTexture = true;
  16103. class DepthTexture extends Texture {
  16104. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  16105. format = format !== undefined ? format : DepthFormat;
  16106. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  16107. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  16108. }
  16109. if ( type === undefined && format === DepthFormat ) type = UnsignedShortType;
  16110. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  16111. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  16112. this.image = { width: width, height: height };
  16113. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  16114. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  16115. this.flipY = false;
  16116. this.generateMipmaps = false;
  16117. }
  16118. }
  16119. DepthTexture.prototype.isDepthTexture = true;
  16120. class CylinderGeometry extends BufferGeometry {
  16121. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  16122. super();
  16123. this.type = 'CylinderGeometry';
  16124. this.parameters = {
  16125. radiusTop: radiusTop,
  16126. radiusBottom: radiusBottom,
  16127. height: height,
  16128. radialSegments: radialSegments,
  16129. heightSegments: heightSegments,
  16130. openEnded: openEnded,
  16131. thetaStart: thetaStart,
  16132. thetaLength: thetaLength
  16133. };
  16134. const scope = this;
  16135. radialSegments = Math.floor( radialSegments );
  16136. heightSegments = Math.floor( heightSegments );
  16137. // buffers
  16138. const indices = [];
  16139. const vertices = [];
  16140. const normals = [];
  16141. const uvs = [];
  16142. // helper variables
  16143. let index = 0;
  16144. const indexArray = [];
  16145. const halfHeight = height / 2;
  16146. let groupStart = 0;
  16147. // generate geometry
  16148. generateTorso();
  16149. if ( openEnded === false ) {
  16150. if ( radiusTop > 0 ) generateCap( true );
  16151. if ( radiusBottom > 0 ) generateCap( false );
  16152. }
  16153. // build geometry
  16154. this.setIndex( indices );
  16155. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16156. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  16157. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16158. function generateTorso() {
  16159. const normal = new Vector3();
  16160. const vertex = new Vector3();
  16161. let groupCount = 0;
  16162. // this will be used to calculate the normal
  16163. const slope = ( radiusBottom - radiusTop ) / height;
  16164. // generate vertices, normals and uvs
  16165. for ( let y = 0; y <= heightSegments; y ++ ) {
  16166. const indexRow = [];
  16167. const v = y / heightSegments;
  16168. // calculate the radius of the current row
  16169. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  16170. for ( let x = 0; x <= radialSegments; x ++ ) {
  16171. const u = x / radialSegments;
  16172. const theta = u * thetaLength + thetaStart;
  16173. const sinTheta = Math.sin( theta );
  16174. const cosTheta = Math.cos( theta );
  16175. // vertex
  16176. vertex.x = radius * sinTheta;
  16177. vertex.y = - v * height + halfHeight;
  16178. vertex.z = radius * cosTheta;
  16179. vertices.push( vertex.x, vertex.y, vertex.z );
  16180. // normal
  16181. normal.set( sinTheta, slope, cosTheta ).normalize();
  16182. normals.push( normal.x, normal.y, normal.z );
  16183. // uv
  16184. uvs.push( u, 1 - v );
  16185. // save index of vertex in respective row
  16186. indexRow.push( index ++ );
  16187. }
  16188. // now save vertices of the row in our index array
  16189. indexArray.push( indexRow );
  16190. }
  16191. // generate indices
  16192. for ( let x = 0; x < radialSegments; x ++ ) {
  16193. for ( let y = 0; y < heightSegments; y ++ ) {
  16194. // we use the index array to access the correct indices
  16195. const a = indexArray[ y ][ x ];
  16196. const b = indexArray[ y + 1 ][ x ];
  16197. const c = indexArray[ y + 1 ][ x + 1 ];
  16198. const d = indexArray[ y ][ x + 1 ];
  16199. // faces
  16200. indices.push( a, b, d );
  16201. indices.push( b, c, d );
  16202. // update group counter
  16203. groupCount += 6;
  16204. }
  16205. }
  16206. // add a group to the geometry. this will ensure multi material support
  16207. scope.addGroup( groupStart, groupCount, 0 );
  16208. // calculate new start value for groups
  16209. groupStart += groupCount;
  16210. }
  16211. function generateCap( top ) {
  16212. // save the index of the first center vertex
  16213. const centerIndexStart = index;
  16214. const uv = new Vector2();
  16215. const vertex = new Vector3();
  16216. let groupCount = 0;
  16217. const radius = ( top === true ) ? radiusTop : radiusBottom;
  16218. const sign = ( top === true ) ? 1 : - 1;
  16219. // first we generate the center vertex data of the cap.
  16220. // because the geometry needs one set of uvs per face,
  16221. // we must generate a center vertex per face/segment
  16222. for ( let x = 1; x <= radialSegments; x ++ ) {
  16223. // vertex
  16224. vertices.push( 0, halfHeight * sign, 0 );
  16225. // normal
  16226. normals.push( 0, sign, 0 );
  16227. // uv
  16228. uvs.push( 0.5, 0.5 );
  16229. // increase index
  16230. index ++;
  16231. }
  16232. // save the index of the last center vertex
  16233. const centerIndexEnd = index;
  16234. // now we generate the surrounding vertices, normals and uvs
  16235. for ( let x = 0; x <= radialSegments; x ++ ) {
  16236. const u = x / radialSegments;
  16237. const theta = u * thetaLength + thetaStart;
  16238. const cosTheta = Math.cos( theta );
  16239. const sinTheta = Math.sin( theta );
  16240. // vertex
  16241. vertex.x = radius * sinTheta;
  16242. vertex.y = halfHeight * sign;
  16243. vertex.z = radius * cosTheta;
  16244. vertices.push( vertex.x, vertex.y, vertex.z );
  16245. // normal
  16246. normals.push( 0, sign, 0 );
  16247. // uv
  16248. uv.x = ( cosTheta * 0.5 ) + 0.5;
  16249. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  16250. uvs.push( uv.x, uv.y );
  16251. // increase index
  16252. index ++;
  16253. }
  16254. // generate indices
  16255. for ( let x = 0; x < radialSegments; x ++ ) {
  16256. const c = centerIndexStart + x;
  16257. const i = centerIndexEnd + x;
  16258. if ( top === true ) {
  16259. // face top
  16260. indices.push( i, i + 1, c );
  16261. } else {
  16262. // face bottom
  16263. indices.push( i + 1, i, c );
  16264. }
  16265. groupCount += 3;
  16266. }
  16267. // add a group to the geometry. this will ensure multi material support
  16268. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  16269. // calculate new start value for groups
  16270. groupStart += groupCount;
  16271. }
  16272. }
  16273. static fromJSON( data ) {
  16274. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  16275. }
  16276. }
  16277. class ConeGeometry extends CylinderGeometry {
  16278. constructor( radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  16279. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  16280. this.type = 'ConeGeometry';
  16281. this.parameters = {
  16282. radius: radius,
  16283. height: height,
  16284. radialSegments: radialSegments,
  16285. heightSegments: heightSegments,
  16286. openEnded: openEnded,
  16287. thetaStart: thetaStart,
  16288. thetaLength: thetaLength
  16289. };
  16290. }
  16291. static fromJSON( data ) {
  16292. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  16293. }
  16294. }
  16295. new Vector3();
  16296. new Vector3();
  16297. new Vector3();
  16298. new Triangle();
  16299. /**
  16300. * Extensible curve object.
  16301. *
  16302. * Some common of curve methods:
  16303. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  16304. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  16305. * .getPoints(), .getSpacedPoints()
  16306. * .getLength()
  16307. * .updateArcLengths()
  16308. *
  16309. * This following curves inherit from THREE.Curve:
  16310. *
  16311. * -- 2D curves --
  16312. * THREE.ArcCurve
  16313. * THREE.CubicBezierCurve
  16314. * THREE.EllipseCurve
  16315. * THREE.LineCurve
  16316. * THREE.QuadraticBezierCurve
  16317. * THREE.SplineCurve
  16318. *
  16319. * -- 3D curves --
  16320. * THREE.CatmullRomCurve3
  16321. * THREE.CubicBezierCurve3
  16322. * THREE.LineCurve3
  16323. * THREE.QuadraticBezierCurve3
  16324. *
  16325. * A series of curves can be represented as a THREE.CurvePath.
  16326. *
  16327. **/
  16328. class Curve {
  16329. constructor() {
  16330. this.type = 'Curve';
  16331. this.arcLengthDivisions = 200;
  16332. }
  16333. // Virtual base class method to overwrite and implement in subclasses
  16334. // - t [0 .. 1]
  16335. getPoint( /* t, optionalTarget */ ) {
  16336. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  16337. return null;
  16338. }
  16339. // Get point at relative position in curve according to arc length
  16340. // - u [0 .. 1]
  16341. getPointAt( u, optionalTarget ) {
  16342. const t = this.getUtoTmapping( u );
  16343. return this.getPoint( t, optionalTarget );
  16344. }
  16345. // Get sequence of points using getPoint( t )
  16346. getPoints( divisions = 5 ) {
  16347. const points = [];
  16348. for ( let d = 0; d <= divisions; d ++ ) {
  16349. points.push( this.getPoint( d / divisions ) );
  16350. }
  16351. return points;
  16352. }
  16353. // Get sequence of points using getPointAt( u )
  16354. getSpacedPoints( divisions = 5 ) {
  16355. const points = [];
  16356. for ( let d = 0; d <= divisions; d ++ ) {
  16357. points.push( this.getPointAt( d / divisions ) );
  16358. }
  16359. return points;
  16360. }
  16361. // Get total curve arc length
  16362. getLength() {
  16363. const lengths = this.getLengths();
  16364. return lengths[ lengths.length - 1 ];
  16365. }
  16366. // Get list of cumulative segment lengths
  16367. getLengths( divisions = this.arcLengthDivisions ) {
  16368. if ( this.cacheArcLengths &&
  16369. ( this.cacheArcLengths.length === divisions + 1 ) &&
  16370. ! this.needsUpdate ) {
  16371. return this.cacheArcLengths;
  16372. }
  16373. this.needsUpdate = false;
  16374. const cache = [];
  16375. let current, last = this.getPoint( 0 );
  16376. let sum = 0;
  16377. cache.push( 0 );
  16378. for ( let p = 1; p <= divisions; p ++ ) {
  16379. current = this.getPoint( p / divisions );
  16380. sum += current.distanceTo( last );
  16381. cache.push( sum );
  16382. last = current;
  16383. }
  16384. this.cacheArcLengths = cache;
  16385. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  16386. }
  16387. updateArcLengths() {
  16388. this.needsUpdate = true;
  16389. this.getLengths();
  16390. }
  16391. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  16392. getUtoTmapping( u, distance ) {
  16393. const arcLengths = this.getLengths();
  16394. let i = 0;
  16395. const il = arcLengths.length;
  16396. let targetArcLength; // The targeted u distance value to get
  16397. if ( distance ) {
  16398. targetArcLength = distance;
  16399. } else {
  16400. targetArcLength = u * arcLengths[ il - 1 ];
  16401. }
  16402. // binary search for the index with largest value smaller than target u distance
  16403. let low = 0, high = il - 1, comparison;
  16404. while ( low <= high ) {
  16405. 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
  16406. comparison = arcLengths[ i ] - targetArcLength;
  16407. if ( comparison < 0 ) {
  16408. low = i + 1;
  16409. } else if ( comparison > 0 ) {
  16410. high = i - 1;
  16411. } else {
  16412. high = i;
  16413. break;
  16414. // DONE
  16415. }
  16416. }
  16417. i = high;
  16418. if ( arcLengths[ i ] === targetArcLength ) {
  16419. return i / ( il - 1 );
  16420. }
  16421. // we could get finer grain at lengths, or use simple interpolation between two points
  16422. const lengthBefore = arcLengths[ i ];
  16423. const lengthAfter = arcLengths[ i + 1 ];
  16424. const segmentLength = lengthAfter - lengthBefore;
  16425. // determine where we are between the 'before' and 'after' points
  16426. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16427. // add that fractional amount to t
  16428. const t = ( i + segmentFraction ) / ( il - 1 );
  16429. return t;
  16430. }
  16431. // Returns a unit vector tangent at t
  16432. // In case any sub curve does not implement its tangent derivation,
  16433. // 2 points a small delta apart will be used to find its gradient
  16434. // which seems to give a reasonable approximation
  16435. getTangent( t, optionalTarget ) {
  16436. const delta = 0.0001;
  16437. let t1 = t - delta;
  16438. let t2 = t + delta;
  16439. // Capping in case of danger
  16440. if ( t1 < 0 ) t1 = 0;
  16441. if ( t2 > 1 ) t2 = 1;
  16442. const pt1 = this.getPoint( t1 );
  16443. const pt2 = this.getPoint( t2 );
  16444. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  16445. tangent.copy( pt2 ).sub( pt1 ).normalize();
  16446. return tangent;
  16447. }
  16448. getTangentAt( u, optionalTarget ) {
  16449. const t = this.getUtoTmapping( u );
  16450. return this.getTangent( t, optionalTarget );
  16451. }
  16452. computeFrenetFrames( segments, closed ) {
  16453. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  16454. const normal = new Vector3();
  16455. const tangents = [];
  16456. const normals = [];
  16457. const binormals = [];
  16458. const vec = new Vector3();
  16459. const mat = new Matrix4();
  16460. // compute the tangent vectors for each segment on the curve
  16461. for ( let i = 0; i <= segments; i ++ ) {
  16462. const u = i / segments;
  16463. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  16464. tangents[ i ].normalize();
  16465. }
  16466. // select an initial normal vector perpendicular to the first tangent vector,
  16467. // and in the direction of the minimum tangent xyz component
  16468. normals[ 0 ] = new Vector3();
  16469. binormals[ 0 ] = new Vector3();
  16470. let min = Number.MAX_VALUE;
  16471. const tx = Math.abs( tangents[ 0 ].x );
  16472. const ty = Math.abs( tangents[ 0 ].y );
  16473. const tz = Math.abs( tangents[ 0 ].z );
  16474. if ( tx <= min ) {
  16475. min = tx;
  16476. normal.set( 1, 0, 0 );
  16477. }
  16478. if ( ty <= min ) {
  16479. min = ty;
  16480. normal.set( 0, 1, 0 );
  16481. }
  16482. if ( tz <= min ) {
  16483. normal.set( 0, 0, 1 );
  16484. }
  16485. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  16486. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  16487. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  16488. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  16489. for ( let i = 1; i <= segments; i ++ ) {
  16490. normals[ i ] = normals[ i - 1 ].clone();
  16491. binormals[ i ] = binormals[ i - 1 ].clone();
  16492. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  16493. if ( vec.length() > Number.EPSILON ) {
  16494. vec.normalize();
  16495. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  16496. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  16497. }
  16498. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  16499. }
  16500. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  16501. if ( closed === true ) {
  16502. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  16503. theta /= segments;
  16504. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  16505. theta = - theta;
  16506. }
  16507. for ( let i = 1; i <= segments; i ++ ) {
  16508. // twist a little...
  16509. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  16510. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  16511. }
  16512. }
  16513. return {
  16514. tangents: tangents,
  16515. normals: normals,
  16516. binormals: binormals
  16517. };
  16518. }
  16519. clone() {
  16520. return new this.constructor().copy( this );
  16521. }
  16522. copy( source ) {
  16523. this.arcLengthDivisions = source.arcLengthDivisions;
  16524. return this;
  16525. }
  16526. toJSON() {
  16527. const data = {
  16528. metadata: {
  16529. version: 4.5,
  16530. type: 'Curve',
  16531. generator: 'Curve.toJSON'
  16532. }
  16533. };
  16534. data.arcLengthDivisions = this.arcLengthDivisions;
  16535. data.type = this.type;
  16536. return data;
  16537. }
  16538. fromJSON( json ) {
  16539. this.arcLengthDivisions = json.arcLengthDivisions;
  16540. return this;
  16541. }
  16542. }
  16543. class EllipseCurve extends Curve {
  16544. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  16545. super();
  16546. this.type = 'EllipseCurve';
  16547. this.aX = aX;
  16548. this.aY = aY;
  16549. this.xRadius = xRadius;
  16550. this.yRadius = yRadius;
  16551. this.aStartAngle = aStartAngle;
  16552. this.aEndAngle = aEndAngle;
  16553. this.aClockwise = aClockwise;
  16554. this.aRotation = aRotation;
  16555. }
  16556. getPoint( t, optionalTarget ) {
  16557. const point = optionalTarget || new Vector2();
  16558. const twoPi = Math.PI * 2;
  16559. let deltaAngle = this.aEndAngle - this.aStartAngle;
  16560. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  16561. // ensures that deltaAngle is 0 .. 2 PI
  16562. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  16563. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  16564. if ( deltaAngle < Number.EPSILON ) {
  16565. if ( samePoints ) {
  16566. deltaAngle = 0;
  16567. } else {
  16568. deltaAngle = twoPi;
  16569. }
  16570. }
  16571. if ( this.aClockwise === true && ! samePoints ) {
  16572. if ( deltaAngle === twoPi ) {
  16573. deltaAngle = - twoPi;
  16574. } else {
  16575. deltaAngle = deltaAngle - twoPi;
  16576. }
  16577. }
  16578. const angle = this.aStartAngle + t * deltaAngle;
  16579. let x = this.aX + this.xRadius * Math.cos( angle );
  16580. let y = this.aY + this.yRadius * Math.sin( angle );
  16581. if ( this.aRotation !== 0 ) {
  16582. const cos = Math.cos( this.aRotation );
  16583. const sin = Math.sin( this.aRotation );
  16584. const tx = x - this.aX;
  16585. const ty = y - this.aY;
  16586. // Rotate the point about the center of the ellipse.
  16587. x = tx * cos - ty * sin + this.aX;
  16588. y = tx * sin + ty * cos + this.aY;
  16589. }
  16590. return point.set( x, y );
  16591. }
  16592. copy( source ) {
  16593. super.copy( source );
  16594. this.aX = source.aX;
  16595. this.aY = source.aY;
  16596. this.xRadius = source.xRadius;
  16597. this.yRadius = source.yRadius;
  16598. this.aStartAngle = source.aStartAngle;
  16599. this.aEndAngle = source.aEndAngle;
  16600. this.aClockwise = source.aClockwise;
  16601. this.aRotation = source.aRotation;
  16602. return this;
  16603. }
  16604. toJSON() {
  16605. const data = super.toJSON();
  16606. data.aX = this.aX;
  16607. data.aY = this.aY;
  16608. data.xRadius = this.xRadius;
  16609. data.yRadius = this.yRadius;
  16610. data.aStartAngle = this.aStartAngle;
  16611. data.aEndAngle = this.aEndAngle;
  16612. data.aClockwise = this.aClockwise;
  16613. data.aRotation = this.aRotation;
  16614. return data;
  16615. }
  16616. fromJSON( json ) {
  16617. super.fromJSON( json );
  16618. this.aX = json.aX;
  16619. this.aY = json.aY;
  16620. this.xRadius = json.xRadius;
  16621. this.yRadius = json.yRadius;
  16622. this.aStartAngle = json.aStartAngle;
  16623. this.aEndAngle = json.aEndAngle;
  16624. this.aClockwise = json.aClockwise;
  16625. this.aRotation = json.aRotation;
  16626. return this;
  16627. }
  16628. }
  16629. EllipseCurve.prototype.isEllipseCurve = true;
  16630. class ArcCurve extends EllipseCurve {
  16631. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  16632. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  16633. this.type = 'ArcCurve';
  16634. }
  16635. }
  16636. ArcCurve.prototype.isArcCurve = true;
  16637. /**
  16638. * Centripetal CatmullRom Curve - which is useful for avoiding
  16639. * cusps and self-intersections in non-uniform catmull rom curves.
  16640. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  16641. *
  16642. * curve.type accepts centripetal(default), chordal and catmullrom
  16643. * curve.tension is used for catmullrom which defaults to 0.5
  16644. */
  16645. /*
  16646. Based on an optimized c++ solution in
  16647. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  16648. - http://ideone.com/NoEbVM
  16649. This CubicPoly class could be used for reusing some variables and calculations,
  16650. but for three.js curve use, it could be possible inlined and flatten into a single function call
  16651. which can be placed in CurveUtils.
  16652. */
  16653. function CubicPoly() {
  16654. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  16655. /*
  16656. * Compute coefficients for a cubic polynomial
  16657. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  16658. * such that
  16659. * p(0) = x0, p(1) = x1
  16660. * and
  16661. * p'(0) = t0, p'(1) = t1.
  16662. */
  16663. function init( x0, x1, t0, t1 ) {
  16664. c0 = x0;
  16665. c1 = t0;
  16666. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  16667. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  16668. }
  16669. return {
  16670. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  16671. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  16672. },
  16673. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  16674. // compute tangents when parameterized in [t1,t2]
  16675. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  16676. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  16677. // rescale tangents for parametrization in [0,1]
  16678. t1 *= dt1;
  16679. t2 *= dt1;
  16680. init( x1, x2, t1, t2 );
  16681. },
  16682. calc: function ( t ) {
  16683. const t2 = t * t;
  16684. const t3 = t2 * t;
  16685. return c0 + c1 * t + c2 * t2 + c3 * t3;
  16686. }
  16687. };
  16688. }
  16689. //
  16690. const tmp = new Vector3();
  16691. const px = new CubicPoly(), py = new CubicPoly(), pz = new CubicPoly();
  16692. class CatmullRomCurve3 extends Curve {
  16693. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  16694. super();
  16695. this.type = 'CatmullRomCurve3';
  16696. this.points = points;
  16697. this.closed = closed;
  16698. this.curveType = curveType;
  16699. this.tension = tension;
  16700. }
  16701. getPoint( t, optionalTarget = new Vector3() ) {
  16702. const point = optionalTarget;
  16703. const points = this.points;
  16704. const l = points.length;
  16705. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  16706. let intPoint = Math.floor( p );
  16707. let weight = p - intPoint;
  16708. if ( this.closed ) {
  16709. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  16710. } else if ( weight === 0 && intPoint === l - 1 ) {
  16711. intPoint = l - 2;
  16712. weight = 1;
  16713. }
  16714. let p0, p3; // 4 points (p1 & p2 defined below)
  16715. if ( this.closed || intPoint > 0 ) {
  16716. p0 = points[ ( intPoint - 1 ) % l ];
  16717. } else {
  16718. // extrapolate first point
  16719. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  16720. p0 = tmp;
  16721. }
  16722. const p1 = points[ intPoint % l ];
  16723. const p2 = points[ ( intPoint + 1 ) % l ];
  16724. if ( this.closed || intPoint + 2 < l ) {
  16725. p3 = points[ ( intPoint + 2 ) % l ];
  16726. } else {
  16727. // extrapolate last point
  16728. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  16729. p3 = tmp;
  16730. }
  16731. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  16732. // init Centripetal / Chordal Catmull-Rom
  16733. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  16734. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  16735. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  16736. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  16737. // safety check for repeated points
  16738. if ( dt1 < 1e-4 ) dt1 = 1.0;
  16739. if ( dt0 < 1e-4 ) dt0 = dt1;
  16740. if ( dt2 < 1e-4 ) dt2 = dt1;
  16741. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  16742. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  16743. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  16744. } else if ( this.curveType === 'catmullrom' ) {
  16745. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  16746. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  16747. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  16748. }
  16749. point.set(
  16750. px.calc( weight ),
  16751. py.calc( weight ),
  16752. pz.calc( weight )
  16753. );
  16754. return point;
  16755. }
  16756. copy( source ) {
  16757. super.copy( source );
  16758. this.points = [];
  16759. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  16760. const point = source.points[ i ];
  16761. this.points.push( point.clone() );
  16762. }
  16763. this.closed = source.closed;
  16764. this.curveType = source.curveType;
  16765. this.tension = source.tension;
  16766. return this;
  16767. }
  16768. toJSON() {
  16769. const data = super.toJSON();
  16770. data.points = [];
  16771. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  16772. const point = this.points[ i ];
  16773. data.points.push( point.toArray() );
  16774. }
  16775. data.closed = this.closed;
  16776. data.curveType = this.curveType;
  16777. data.tension = this.tension;
  16778. return data;
  16779. }
  16780. fromJSON( json ) {
  16781. super.fromJSON( json );
  16782. this.points = [];
  16783. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  16784. const point = json.points[ i ];
  16785. this.points.push( new Vector3().fromArray( point ) );
  16786. }
  16787. this.closed = json.closed;
  16788. this.curveType = json.curveType;
  16789. this.tension = json.tension;
  16790. return this;
  16791. }
  16792. }
  16793. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  16794. /**
  16795. * Bezier Curves formulas obtained from
  16796. * http://en.wikipedia.org/wiki/Bézier_curve
  16797. */
  16798. function CatmullRom( t, p0, p1, p2, p3 ) {
  16799. const v0 = ( p2 - p0 ) * 0.5;
  16800. const v1 = ( p3 - p1 ) * 0.5;
  16801. const t2 = t * t;
  16802. const t3 = t * t2;
  16803. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16804. }
  16805. //
  16806. function QuadraticBezierP0( t, p ) {
  16807. const k = 1 - t;
  16808. return k * k * p;
  16809. }
  16810. function QuadraticBezierP1( t, p ) {
  16811. return 2 * ( 1 - t ) * t * p;
  16812. }
  16813. function QuadraticBezierP2( t, p ) {
  16814. return t * t * p;
  16815. }
  16816. function QuadraticBezier( t, p0, p1, p2 ) {
  16817. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  16818. QuadraticBezierP2( t, p2 );
  16819. }
  16820. //
  16821. function CubicBezierP0( t, p ) {
  16822. const k = 1 - t;
  16823. return k * k * k * p;
  16824. }
  16825. function CubicBezierP1( t, p ) {
  16826. const k = 1 - t;
  16827. return 3 * k * k * t * p;
  16828. }
  16829. function CubicBezierP2( t, p ) {
  16830. return 3 * ( 1 - t ) * t * t * p;
  16831. }
  16832. function CubicBezierP3( t, p ) {
  16833. return t * t * t * p;
  16834. }
  16835. function CubicBezier( t, p0, p1, p2, p3 ) {
  16836. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  16837. CubicBezierP3( t, p3 );
  16838. }
  16839. class CubicBezierCurve extends Curve {
  16840. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  16841. super();
  16842. this.type = 'CubicBezierCurve';
  16843. this.v0 = v0;
  16844. this.v1 = v1;
  16845. this.v2 = v2;
  16846. this.v3 = v3;
  16847. }
  16848. getPoint( t, optionalTarget = new Vector2() ) {
  16849. const point = optionalTarget;
  16850. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  16851. point.set(
  16852. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  16853. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  16854. );
  16855. return point;
  16856. }
  16857. copy( source ) {
  16858. super.copy( source );
  16859. this.v0.copy( source.v0 );
  16860. this.v1.copy( source.v1 );
  16861. this.v2.copy( source.v2 );
  16862. this.v3.copy( source.v3 );
  16863. return this;
  16864. }
  16865. toJSON() {
  16866. const data = super.toJSON();
  16867. data.v0 = this.v0.toArray();
  16868. data.v1 = this.v1.toArray();
  16869. data.v2 = this.v2.toArray();
  16870. data.v3 = this.v3.toArray();
  16871. return data;
  16872. }
  16873. fromJSON( json ) {
  16874. super.fromJSON( json );
  16875. this.v0.fromArray( json.v0 );
  16876. this.v1.fromArray( json.v1 );
  16877. this.v2.fromArray( json.v2 );
  16878. this.v3.fromArray( json.v3 );
  16879. return this;
  16880. }
  16881. }
  16882. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  16883. class CubicBezierCurve3 extends Curve {
  16884. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  16885. super();
  16886. this.type = 'CubicBezierCurve3';
  16887. this.v0 = v0;
  16888. this.v1 = v1;
  16889. this.v2 = v2;
  16890. this.v3 = v3;
  16891. }
  16892. getPoint( t, optionalTarget = new Vector3() ) {
  16893. const point = optionalTarget;
  16894. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  16895. point.set(
  16896. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  16897. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  16898. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  16899. );
  16900. return point;
  16901. }
  16902. copy( source ) {
  16903. super.copy( source );
  16904. this.v0.copy( source.v0 );
  16905. this.v1.copy( source.v1 );
  16906. this.v2.copy( source.v2 );
  16907. this.v3.copy( source.v3 );
  16908. return this;
  16909. }
  16910. toJSON() {
  16911. const data = super.toJSON();
  16912. data.v0 = this.v0.toArray();
  16913. data.v1 = this.v1.toArray();
  16914. data.v2 = this.v2.toArray();
  16915. data.v3 = this.v3.toArray();
  16916. return data;
  16917. }
  16918. fromJSON( json ) {
  16919. super.fromJSON( json );
  16920. this.v0.fromArray( json.v0 );
  16921. this.v1.fromArray( json.v1 );
  16922. this.v2.fromArray( json.v2 );
  16923. this.v3.fromArray( json.v3 );
  16924. return this;
  16925. }
  16926. }
  16927. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  16928. class LineCurve extends Curve {
  16929. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  16930. super();
  16931. this.type = 'LineCurve';
  16932. this.v1 = v1;
  16933. this.v2 = v2;
  16934. }
  16935. getPoint( t, optionalTarget = new Vector2() ) {
  16936. const point = optionalTarget;
  16937. if ( t === 1 ) {
  16938. point.copy( this.v2 );
  16939. } else {
  16940. point.copy( this.v2 ).sub( this.v1 );
  16941. point.multiplyScalar( t ).add( this.v1 );
  16942. }
  16943. return point;
  16944. }
  16945. // Line curve is linear, so we can overwrite default getPointAt
  16946. getPointAt( u, optionalTarget ) {
  16947. return this.getPoint( u, optionalTarget );
  16948. }
  16949. getTangent( t, optionalTarget ) {
  16950. const tangent = optionalTarget || new Vector2();
  16951. tangent.copy( this.v2 ).sub( this.v1 ).normalize();
  16952. return tangent;
  16953. }
  16954. copy( source ) {
  16955. super.copy( source );
  16956. this.v1.copy( source.v1 );
  16957. this.v2.copy( source.v2 );
  16958. return this;
  16959. }
  16960. toJSON() {
  16961. const data = super.toJSON();
  16962. data.v1 = this.v1.toArray();
  16963. data.v2 = this.v2.toArray();
  16964. return data;
  16965. }
  16966. fromJSON( json ) {
  16967. super.fromJSON( json );
  16968. this.v1.fromArray( json.v1 );
  16969. this.v2.fromArray( json.v2 );
  16970. return this;
  16971. }
  16972. }
  16973. LineCurve.prototype.isLineCurve = true;
  16974. class LineCurve3 extends Curve {
  16975. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  16976. super();
  16977. this.type = 'LineCurve3';
  16978. this.isLineCurve3 = true;
  16979. this.v1 = v1;
  16980. this.v2 = v2;
  16981. }
  16982. getPoint( t, optionalTarget = new Vector3() ) {
  16983. const point = optionalTarget;
  16984. if ( t === 1 ) {
  16985. point.copy( this.v2 );
  16986. } else {
  16987. point.copy( this.v2 ).sub( this.v1 );
  16988. point.multiplyScalar( t ).add( this.v1 );
  16989. }
  16990. return point;
  16991. }
  16992. // Line curve is linear, so we can overwrite default getPointAt
  16993. getPointAt( u, optionalTarget ) {
  16994. return this.getPoint( u, optionalTarget );
  16995. }
  16996. copy( source ) {
  16997. super.copy( source );
  16998. this.v1.copy( source.v1 );
  16999. this.v2.copy( source.v2 );
  17000. return this;
  17001. }
  17002. toJSON() {
  17003. const data = super.toJSON();
  17004. data.v1 = this.v1.toArray();
  17005. data.v2 = this.v2.toArray();
  17006. return data;
  17007. }
  17008. fromJSON( json ) {
  17009. super.fromJSON( json );
  17010. this.v1.fromArray( json.v1 );
  17011. this.v2.fromArray( json.v2 );
  17012. return this;
  17013. }
  17014. }
  17015. class QuadraticBezierCurve extends Curve {
  17016. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  17017. super();
  17018. this.type = 'QuadraticBezierCurve';
  17019. this.v0 = v0;
  17020. this.v1 = v1;
  17021. this.v2 = v2;
  17022. }
  17023. getPoint( t, optionalTarget = new Vector2() ) {
  17024. const point = optionalTarget;
  17025. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  17026. point.set(
  17027. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  17028. QuadraticBezier( t, v0.y, v1.y, v2.y )
  17029. );
  17030. return point;
  17031. }
  17032. copy( source ) {
  17033. super.copy( source );
  17034. this.v0.copy( source.v0 );
  17035. this.v1.copy( source.v1 );
  17036. this.v2.copy( source.v2 );
  17037. return this;
  17038. }
  17039. toJSON() {
  17040. const data = super.toJSON();
  17041. data.v0 = this.v0.toArray();
  17042. data.v1 = this.v1.toArray();
  17043. data.v2 = this.v2.toArray();
  17044. return data;
  17045. }
  17046. fromJSON( json ) {
  17047. super.fromJSON( json );
  17048. this.v0.fromArray( json.v0 );
  17049. this.v1.fromArray( json.v1 );
  17050. this.v2.fromArray( json.v2 );
  17051. return this;
  17052. }
  17053. }
  17054. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  17055. class QuadraticBezierCurve3 extends Curve {
  17056. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  17057. super();
  17058. this.type = 'QuadraticBezierCurve3';
  17059. this.v0 = v0;
  17060. this.v1 = v1;
  17061. this.v2 = v2;
  17062. }
  17063. getPoint( t, optionalTarget = new Vector3() ) {
  17064. const point = optionalTarget;
  17065. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  17066. point.set(
  17067. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  17068. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  17069. QuadraticBezier( t, v0.z, v1.z, v2.z )
  17070. );
  17071. return point;
  17072. }
  17073. copy( source ) {
  17074. super.copy( source );
  17075. this.v0.copy( source.v0 );
  17076. this.v1.copy( source.v1 );
  17077. this.v2.copy( source.v2 );
  17078. return this;
  17079. }
  17080. toJSON() {
  17081. const data = super.toJSON();
  17082. data.v0 = this.v0.toArray();
  17083. data.v1 = this.v1.toArray();
  17084. data.v2 = this.v2.toArray();
  17085. return data;
  17086. }
  17087. fromJSON( json ) {
  17088. super.fromJSON( json );
  17089. this.v0.fromArray( json.v0 );
  17090. this.v1.fromArray( json.v1 );
  17091. this.v2.fromArray( json.v2 );
  17092. return this;
  17093. }
  17094. }
  17095. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  17096. class SplineCurve extends Curve {
  17097. constructor( points = [] ) {
  17098. super();
  17099. this.type = 'SplineCurve';
  17100. this.points = points;
  17101. }
  17102. getPoint( t, optionalTarget = new Vector2() ) {
  17103. const point = optionalTarget;
  17104. const points = this.points;
  17105. const p = ( points.length - 1 ) * t;
  17106. const intPoint = Math.floor( p );
  17107. const weight = p - intPoint;
  17108. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  17109. const p1 = points[ intPoint ];
  17110. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  17111. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  17112. point.set(
  17113. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  17114. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  17115. );
  17116. return point;
  17117. }
  17118. copy( source ) {
  17119. super.copy( source );
  17120. this.points = [];
  17121. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  17122. const point = source.points[ i ];
  17123. this.points.push( point.clone() );
  17124. }
  17125. return this;
  17126. }
  17127. toJSON() {
  17128. const data = super.toJSON();
  17129. data.points = [];
  17130. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  17131. const point = this.points[ i ];
  17132. data.points.push( point.toArray() );
  17133. }
  17134. return data;
  17135. }
  17136. fromJSON( json ) {
  17137. super.fromJSON( json );
  17138. this.points = [];
  17139. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  17140. const point = json.points[ i ];
  17141. this.points.push( new Vector2().fromArray( point ) );
  17142. }
  17143. return this;
  17144. }
  17145. }
  17146. SplineCurve.prototype.isSplineCurve = true;
  17147. var Curves = /*#__PURE__*/Object.freeze({
  17148. __proto__: null,
  17149. ArcCurve: ArcCurve,
  17150. CatmullRomCurve3: CatmullRomCurve3,
  17151. CubicBezierCurve: CubicBezierCurve,
  17152. CubicBezierCurve3: CubicBezierCurve3,
  17153. EllipseCurve: EllipseCurve,
  17154. LineCurve: LineCurve,
  17155. LineCurve3: LineCurve3,
  17156. QuadraticBezierCurve: QuadraticBezierCurve,
  17157. QuadraticBezierCurve3: QuadraticBezierCurve3,
  17158. SplineCurve: SplineCurve
  17159. });
  17160. /**
  17161. * Port from https://github.com/mapbox/earcut (v2.2.2)
  17162. */
  17163. const Earcut = {
  17164. triangulate: function ( data, holeIndices, dim = 2 ) {
  17165. const hasHoles = holeIndices && holeIndices.length;
  17166. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  17167. let outerNode = linkedList( data, 0, outerLen, dim, true );
  17168. const triangles = [];
  17169. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  17170. let minX, minY, maxX, maxY, x, y, invSize;
  17171. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  17172. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  17173. if ( data.length > 80 * dim ) {
  17174. minX = maxX = data[ 0 ];
  17175. minY = maxY = data[ 1 ];
  17176. for ( let i = dim; i < outerLen; i += dim ) {
  17177. x = data[ i ];
  17178. y = data[ i + 1 ];
  17179. if ( x < minX ) minX = x;
  17180. if ( y < minY ) minY = y;
  17181. if ( x > maxX ) maxX = x;
  17182. if ( y > maxY ) maxY = y;
  17183. }
  17184. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  17185. invSize = Math.max( maxX - minX, maxY - minY );
  17186. invSize = invSize !== 0 ? 1 / invSize : 0;
  17187. }
  17188. earcutLinked( outerNode, triangles, dim, minX, minY, invSize );
  17189. return triangles;
  17190. }
  17191. };
  17192. // create a circular doubly linked list from polygon points in the specified winding order
  17193. function linkedList( data, start, end, dim, clockwise ) {
  17194. let i, last;
  17195. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  17196. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  17197. } else {
  17198. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  17199. }
  17200. if ( last && equals( last, last.next ) ) {
  17201. removeNode( last );
  17202. last = last.next;
  17203. }
  17204. return last;
  17205. }
  17206. // eliminate colinear or duplicate points
  17207. function filterPoints( start, end ) {
  17208. if ( ! start ) return start;
  17209. if ( ! end ) end = start;
  17210. let p = start,
  17211. again;
  17212. do {
  17213. again = false;
  17214. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  17215. removeNode( p );
  17216. p = end = p.prev;
  17217. if ( p === p.next ) break;
  17218. again = true;
  17219. } else {
  17220. p = p.next;
  17221. }
  17222. } while ( again || p !== end );
  17223. return end;
  17224. }
  17225. // main ear slicing loop which triangulates a polygon (given as a linked list)
  17226. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  17227. if ( ! ear ) return;
  17228. // interlink polygon nodes in z-order
  17229. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  17230. let stop = ear,
  17231. prev, next;
  17232. // iterate through ears, slicing them one by one
  17233. while ( ear.prev !== ear.next ) {
  17234. prev = ear.prev;
  17235. next = ear.next;
  17236. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  17237. // cut off the triangle
  17238. triangles.push( prev.i / dim );
  17239. triangles.push( ear.i / dim );
  17240. triangles.push( next.i / dim );
  17241. removeNode( ear );
  17242. // skipping the next vertex leads to less sliver triangles
  17243. ear = next.next;
  17244. stop = next.next;
  17245. continue;
  17246. }
  17247. ear = next;
  17248. // if we looped through the whole remaining polygon and can't find any more ears
  17249. if ( ear === stop ) {
  17250. // try filtering points and slicing again
  17251. if ( ! pass ) {
  17252. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  17253. // if this didn't work, try curing all small self-intersections locally
  17254. } else if ( pass === 1 ) {
  17255. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  17256. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  17257. // as a last resort, try splitting the remaining polygon into two
  17258. } else if ( pass === 2 ) {
  17259. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  17260. }
  17261. break;
  17262. }
  17263. }
  17264. }
  17265. // check whether a polygon node forms a valid ear with adjacent nodes
  17266. function isEar( ear ) {
  17267. const a = ear.prev,
  17268. b = ear,
  17269. c = ear.next;
  17270. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  17271. // now make sure we don't have other points inside the potential ear
  17272. let p = ear.next.next;
  17273. while ( p !== ear.prev ) {
  17274. if ( pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  17275. area( p.prev, p, p.next ) >= 0 ) return false;
  17276. p = p.next;
  17277. }
  17278. return true;
  17279. }
  17280. function isEarHashed( ear, minX, minY, invSize ) {
  17281. const a = ear.prev,
  17282. b = ear,
  17283. c = ear.next;
  17284. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  17285. // triangle bbox; min & max are calculated like this for speed
  17286. const minTX = a.x < b.x ? ( a.x < c.x ? a.x : c.x ) : ( b.x < c.x ? b.x : c.x ),
  17287. minTY = a.y < b.y ? ( a.y < c.y ? a.y : c.y ) : ( b.y < c.y ? b.y : c.y ),
  17288. maxTX = a.x > b.x ? ( a.x > c.x ? a.x : c.x ) : ( b.x > c.x ? b.x : c.x ),
  17289. maxTY = a.y > b.y ? ( a.y > c.y ? a.y : c.y ) : ( b.y > c.y ? b.y : c.y );
  17290. // z-order range for the current triangle bbox;
  17291. const minZ = zOrder( minTX, minTY, minX, minY, invSize ),
  17292. maxZ = zOrder( maxTX, maxTY, minX, minY, invSize );
  17293. let p = ear.prevZ,
  17294. n = ear.nextZ;
  17295. // look for points inside the triangle in both directions
  17296. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  17297. if ( p !== ear.prev && p !== ear.next &&
  17298. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  17299. area( p.prev, p, p.next ) >= 0 ) return false;
  17300. p = p.prevZ;
  17301. if ( n !== ear.prev && n !== ear.next &&
  17302. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  17303. area( n.prev, n, n.next ) >= 0 ) return false;
  17304. n = n.nextZ;
  17305. }
  17306. // look for remaining points in decreasing z-order
  17307. while ( p && p.z >= minZ ) {
  17308. if ( p !== ear.prev && p !== ear.next &&
  17309. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  17310. area( p.prev, p, p.next ) >= 0 ) return false;
  17311. p = p.prevZ;
  17312. }
  17313. // look for remaining points in increasing z-order
  17314. while ( n && n.z <= maxZ ) {
  17315. if ( n !== ear.prev && n !== ear.next &&
  17316. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  17317. area( n.prev, n, n.next ) >= 0 ) return false;
  17318. n = n.nextZ;
  17319. }
  17320. return true;
  17321. }
  17322. // go through all polygon nodes and cure small local self-intersections
  17323. function cureLocalIntersections( start, triangles, dim ) {
  17324. let p = start;
  17325. do {
  17326. const a = p.prev,
  17327. b = p.next.next;
  17328. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  17329. triangles.push( a.i / dim );
  17330. triangles.push( p.i / dim );
  17331. triangles.push( b.i / dim );
  17332. // remove two nodes involved
  17333. removeNode( p );
  17334. removeNode( p.next );
  17335. p = start = b;
  17336. }
  17337. p = p.next;
  17338. } while ( p !== start );
  17339. return filterPoints( p );
  17340. }
  17341. // try splitting polygon into two and triangulate them independently
  17342. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  17343. // look for a valid diagonal that divides the polygon into two
  17344. let a = start;
  17345. do {
  17346. let b = a.next.next;
  17347. while ( b !== a.prev ) {
  17348. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  17349. // split the polygon in two by the diagonal
  17350. let c = splitPolygon( a, b );
  17351. // filter colinear points around the cuts
  17352. a = filterPoints( a, a.next );
  17353. c = filterPoints( c, c.next );
  17354. // run earcut on each half
  17355. earcutLinked( a, triangles, dim, minX, minY, invSize );
  17356. earcutLinked( c, triangles, dim, minX, minY, invSize );
  17357. return;
  17358. }
  17359. b = b.next;
  17360. }
  17361. a = a.next;
  17362. } while ( a !== start );
  17363. }
  17364. // link every hole into the outer loop, producing a single-ring polygon without holes
  17365. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  17366. const queue = [];
  17367. let i, len, start, end, list;
  17368. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  17369. start = holeIndices[ i ] * dim;
  17370. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  17371. list = linkedList( data, start, end, dim, false );
  17372. if ( list === list.next ) list.steiner = true;
  17373. queue.push( getLeftmost( list ) );
  17374. }
  17375. queue.sort( compareX );
  17376. // process holes from left to right
  17377. for ( i = 0; i < queue.length; i ++ ) {
  17378. eliminateHole( queue[ i ], outerNode );
  17379. outerNode = filterPoints( outerNode, outerNode.next );
  17380. }
  17381. return outerNode;
  17382. }
  17383. function compareX( a, b ) {
  17384. return a.x - b.x;
  17385. }
  17386. // find a bridge between vertices that connects hole with an outer ring and and link it
  17387. function eliminateHole( hole, outerNode ) {
  17388. outerNode = findHoleBridge( hole, outerNode );
  17389. if ( outerNode ) {
  17390. const b = splitPolygon( outerNode, hole );
  17391. // filter collinear points around the cuts
  17392. filterPoints( outerNode, outerNode.next );
  17393. filterPoints( b, b.next );
  17394. }
  17395. }
  17396. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  17397. function findHoleBridge( hole, outerNode ) {
  17398. let p = outerNode;
  17399. const hx = hole.x;
  17400. const hy = hole.y;
  17401. let qx = - Infinity, m;
  17402. // find a segment intersected by a ray from the hole's leftmost point to the left;
  17403. // segment's endpoint with lesser x will be potential connection point
  17404. do {
  17405. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  17406. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  17407. if ( x <= hx && x > qx ) {
  17408. qx = x;
  17409. if ( x === hx ) {
  17410. if ( hy === p.y ) return p;
  17411. if ( hy === p.next.y ) return p.next;
  17412. }
  17413. m = p.x < p.next.x ? p : p.next;
  17414. }
  17415. }
  17416. p = p.next;
  17417. } while ( p !== outerNode );
  17418. if ( ! m ) return null;
  17419. if ( hx === qx ) return m; // hole touches outer segment; pick leftmost endpoint
  17420. // look for points inside the triangle of hole point, segment intersection and endpoint;
  17421. // if there are no points found, we have a valid connection;
  17422. // otherwise choose the point of the minimum angle with the ray as connection point
  17423. const stop = m,
  17424. mx = m.x,
  17425. my = m.y;
  17426. let tanMin = Infinity, tan;
  17427. p = m;
  17428. do {
  17429. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  17430. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  17431. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  17432. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  17433. m = p;
  17434. tanMin = tan;
  17435. }
  17436. }
  17437. p = p.next;
  17438. } while ( p !== stop );
  17439. return m;
  17440. }
  17441. // whether sector in vertex m contains sector in vertex p in the same coordinates
  17442. function sectorContainsSector( m, p ) {
  17443. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  17444. }
  17445. // interlink polygon nodes in z-order
  17446. function indexCurve( start, minX, minY, invSize ) {
  17447. let p = start;
  17448. do {
  17449. if ( p.z === null ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  17450. p.prevZ = p.prev;
  17451. p.nextZ = p.next;
  17452. p = p.next;
  17453. } while ( p !== start );
  17454. p.prevZ.nextZ = null;
  17455. p.prevZ = null;
  17456. sortLinked( p );
  17457. }
  17458. // Simon Tatham's linked list merge sort algorithm
  17459. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  17460. function sortLinked( list ) {
  17461. let i, p, q, e, tail, numMerges, pSize, qSize,
  17462. inSize = 1;
  17463. do {
  17464. p = list;
  17465. list = null;
  17466. tail = null;
  17467. numMerges = 0;
  17468. while ( p ) {
  17469. numMerges ++;
  17470. q = p;
  17471. pSize = 0;
  17472. for ( i = 0; i < inSize; i ++ ) {
  17473. pSize ++;
  17474. q = q.nextZ;
  17475. if ( ! q ) break;
  17476. }
  17477. qSize = inSize;
  17478. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  17479. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  17480. e = p;
  17481. p = p.nextZ;
  17482. pSize --;
  17483. } else {
  17484. e = q;
  17485. q = q.nextZ;
  17486. qSize --;
  17487. }
  17488. if ( tail ) tail.nextZ = e;
  17489. else list = e;
  17490. e.prevZ = tail;
  17491. tail = e;
  17492. }
  17493. p = q;
  17494. }
  17495. tail.nextZ = null;
  17496. inSize *= 2;
  17497. } while ( numMerges > 1 );
  17498. return list;
  17499. }
  17500. // z-order of a point given coords and inverse of the longer side of data bbox
  17501. function zOrder( x, y, minX, minY, invSize ) {
  17502. // coords are transformed into non-negative 15-bit integer range
  17503. x = 32767 * ( x - minX ) * invSize;
  17504. y = 32767 * ( y - minY ) * invSize;
  17505. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  17506. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  17507. x = ( x | ( x << 2 ) ) & 0x33333333;
  17508. x = ( x | ( x << 1 ) ) & 0x55555555;
  17509. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  17510. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  17511. y = ( y | ( y << 2 ) ) & 0x33333333;
  17512. y = ( y | ( y << 1 ) ) & 0x55555555;
  17513. return x | ( y << 1 );
  17514. }
  17515. // find the leftmost node of a polygon ring
  17516. function getLeftmost( start ) {
  17517. let p = start,
  17518. leftmost = start;
  17519. do {
  17520. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  17521. p = p.next;
  17522. } while ( p !== start );
  17523. return leftmost;
  17524. }
  17525. // check if a point lies within a convex triangle
  17526. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  17527. return ( cx - px ) * ( ay - py ) - ( ax - px ) * ( cy - py ) >= 0 &&
  17528. ( ax - px ) * ( by - py ) - ( bx - px ) * ( ay - py ) >= 0 &&
  17529. ( bx - px ) * ( cy - py ) - ( cx - px ) * ( by - py ) >= 0;
  17530. }
  17531. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  17532. function isValidDiagonal( a, b ) {
  17533. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  17534. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  17535. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  17536. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  17537. }
  17538. // signed area of a triangle
  17539. function area( p, q, r ) {
  17540. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  17541. }
  17542. // check if two points are equal
  17543. function equals( p1, p2 ) {
  17544. return p1.x === p2.x && p1.y === p2.y;
  17545. }
  17546. // check if two segments intersect
  17547. function intersects( p1, q1, p2, q2 ) {
  17548. const o1 = sign( area( p1, q1, p2 ) );
  17549. const o2 = sign( area( p1, q1, q2 ) );
  17550. const o3 = sign( area( p2, q2, p1 ) );
  17551. const o4 = sign( area( p2, q2, q1 ) );
  17552. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  17553. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  17554. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  17555. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  17556. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  17557. return false;
  17558. }
  17559. // for collinear points p, q, r, check if point q lies on segment pr
  17560. function onSegment( p, q, r ) {
  17561. 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 );
  17562. }
  17563. function sign( num ) {
  17564. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  17565. }
  17566. // check if a polygon diagonal intersects any polygon segments
  17567. function intersectsPolygon( a, b ) {
  17568. let p = a;
  17569. do {
  17570. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  17571. intersects( p, p.next, a, b ) ) return true;
  17572. p = p.next;
  17573. } while ( p !== a );
  17574. return false;
  17575. }
  17576. // check if a polygon diagonal is locally inside the polygon
  17577. function locallyInside( a, b ) {
  17578. return area( a.prev, a, a.next ) < 0 ?
  17579. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  17580. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  17581. }
  17582. // check if the middle point of a polygon diagonal is inside the polygon
  17583. function middleInside( a, b ) {
  17584. let p = a,
  17585. inside = false;
  17586. const px = ( a.x + b.x ) / 2,
  17587. py = ( a.y + b.y ) / 2;
  17588. do {
  17589. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  17590. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  17591. inside = ! inside;
  17592. p = p.next;
  17593. } while ( p !== a );
  17594. return inside;
  17595. }
  17596. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  17597. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  17598. function splitPolygon( a, b ) {
  17599. const a2 = new Node$1( a.i, a.x, a.y ),
  17600. b2 = new Node$1( b.i, b.x, b.y ),
  17601. an = a.next,
  17602. bp = b.prev;
  17603. a.next = b;
  17604. b.prev = a;
  17605. a2.next = an;
  17606. an.prev = a2;
  17607. b2.next = a2;
  17608. a2.prev = b2;
  17609. bp.next = b2;
  17610. b2.prev = bp;
  17611. return b2;
  17612. }
  17613. // create a node and optionally link it with previous one (in a circular doubly linked list)
  17614. function insertNode( i, x, y, last ) {
  17615. const p = new Node$1( i, x, y );
  17616. if ( ! last ) {
  17617. p.prev = p;
  17618. p.next = p;
  17619. } else {
  17620. p.next = last.next;
  17621. p.prev = last;
  17622. last.next.prev = p;
  17623. last.next = p;
  17624. }
  17625. return p;
  17626. }
  17627. function removeNode( p ) {
  17628. p.next.prev = p.prev;
  17629. p.prev.next = p.next;
  17630. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  17631. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  17632. }
  17633. function Node$1( i, x, y ) {
  17634. // vertex index in coordinates array
  17635. this.i = i;
  17636. // vertex coordinates
  17637. this.x = x;
  17638. this.y = y;
  17639. // previous and next vertex nodes in a polygon ring
  17640. this.prev = null;
  17641. this.next = null;
  17642. // z-order curve value
  17643. this.z = null;
  17644. // previous and next nodes in z-order
  17645. this.prevZ = null;
  17646. this.nextZ = null;
  17647. // indicates whether this is a steiner point
  17648. this.steiner = false;
  17649. }
  17650. function signedArea( data, start, end, dim ) {
  17651. let sum = 0;
  17652. for ( let i = start, j = end - dim; i < end; i += dim ) {
  17653. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  17654. j = i;
  17655. }
  17656. return sum;
  17657. }
  17658. class ShapeUtils {
  17659. // calculate area of the contour polygon
  17660. static area( contour ) {
  17661. const n = contour.length;
  17662. let a = 0.0;
  17663. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  17664. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  17665. }
  17666. return a * 0.5;
  17667. }
  17668. static isClockWise( pts ) {
  17669. return ShapeUtils.area( pts ) < 0;
  17670. }
  17671. static triangulateShape( contour, holes ) {
  17672. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  17673. const holeIndices = []; // array of hole indices
  17674. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  17675. removeDupEndPts( contour );
  17676. addContour( vertices, contour );
  17677. //
  17678. let holeIndex = contour.length;
  17679. holes.forEach( removeDupEndPts );
  17680. for ( let i = 0; i < holes.length; i ++ ) {
  17681. holeIndices.push( holeIndex );
  17682. holeIndex += holes[ i ].length;
  17683. addContour( vertices, holes[ i ] );
  17684. }
  17685. //
  17686. const triangles = Earcut.triangulate( vertices, holeIndices );
  17687. //
  17688. for ( let i = 0; i < triangles.length; i += 3 ) {
  17689. faces.push( triangles.slice( i, i + 3 ) );
  17690. }
  17691. return faces;
  17692. }
  17693. }
  17694. function removeDupEndPts( points ) {
  17695. const l = points.length;
  17696. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  17697. points.pop();
  17698. }
  17699. }
  17700. function addContour( vertices, contour ) {
  17701. for ( let i = 0; i < contour.length; i ++ ) {
  17702. vertices.push( contour[ i ].x );
  17703. vertices.push( contour[ i ].y );
  17704. }
  17705. }
  17706. /**
  17707. * Creates extruded geometry from a path shape.
  17708. *
  17709. * parameters = {
  17710. *
  17711. * curveSegments: <int>, // number of points on the curves
  17712. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  17713. * depth: <float>, // Depth to extrude the shape
  17714. *
  17715. * bevelEnabled: <bool>, // turn on bevel
  17716. * bevelThickness: <float>, // how deep into the original shape bevel goes
  17717. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  17718. * bevelOffset: <float>, // how far from shape outline does bevel start
  17719. * bevelSegments: <int>, // number of bevel layers
  17720. *
  17721. * extrudePath: <THREE.Curve> // curve to extrude shape along
  17722. *
  17723. * UVGenerator: <Object> // object that provides UV generator functions
  17724. *
  17725. * }
  17726. */
  17727. class ExtrudeGeometry extends BufferGeometry {
  17728. constructor( shapes, options ) {
  17729. super();
  17730. this.type = 'ExtrudeGeometry';
  17731. this.parameters = {
  17732. shapes: shapes,
  17733. options: options
  17734. };
  17735. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  17736. const scope = this;
  17737. const verticesArray = [];
  17738. const uvArray = [];
  17739. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  17740. const shape = shapes[ i ];
  17741. addShape( shape );
  17742. }
  17743. // build geometry
  17744. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  17745. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  17746. this.computeVertexNormals();
  17747. // functions
  17748. function addShape( shape ) {
  17749. const placeholder = [];
  17750. // options
  17751. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  17752. const steps = options.steps !== undefined ? options.steps : 1;
  17753. let depth = options.depth !== undefined ? options.depth : 100;
  17754. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  17755. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  17756. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  17757. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  17758. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  17759. const extrudePath = options.extrudePath;
  17760. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  17761. // deprecated options
  17762. if ( options.amount !== undefined ) {
  17763. console.warn( 'THREE.ExtrudeBufferGeometry: amount has been renamed to depth.' );
  17764. depth = options.amount;
  17765. }
  17766. //
  17767. let extrudePts, extrudeByPath = false;
  17768. let splineTube, binormal, normal, position2;
  17769. if ( extrudePath ) {
  17770. extrudePts = extrudePath.getSpacedPoints( steps );
  17771. extrudeByPath = true;
  17772. bevelEnabled = false; // bevels not supported for path extrusion
  17773. // SETUP TNB variables
  17774. // TODO1 - have a .isClosed in spline?
  17775. splineTube = extrudePath.computeFrenetFrames( steps, false );
  17776. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  17777. binormal = new Vector3();
  17778. normal = new Vector3();
  17779. position2 = new Vector3();
  17780. }
  17781. // Safeguards if bevels are not enabled
  17782. if ( ! bevelEnabled ) {
  17783. bevelSegments = 0;
  17784. bevelThickness = 0;
  17785. bevelSize = 0;
  17786. bevelOffset = 0;
  17787. }
  17788. // Variables initialization
  17789. const shapePoints = shape.extractPoints( curveSegments );
  17790. let vertices = shapePoints.shape;
  17791. const holes = shapePoints.holes;
  17792. const reverse = ! ShapeUtils.isClockWise( vertices );
  17793. if ( reverse ) {
  17794. vertices = vertices.reverse();
  17795. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  17796. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  17797. const ahole = holes[ h ];
  17798. if ( ShapeUtils.isClockWise( ahole ) ) {
  17799. holes[ h ] = ahole.reverse();
  17800. }
  17801. }
  17802. }
  17803. const faces = ShapeUtils.triangulateShape( vertices, holes );
  17804. /* Vertices */
  17805. const contour = vertices; // vertices has all points but contour has only points of circumference
  17806. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  17807. const ahole = holes[ h ];
  17808. vertices = vertices.concat( ahole );
  17809. }
  17810. function scalePt2( pt, vec, size ) {
  17811. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  17812. return vec.clone().multiplyScalar( size ).add( pt );
  17813. }
  17814. const vlen = vertices.length, flen = faces.length;
  17815. // Find directions for point movement
  17816. function getBevelVec( inPt, inPrev, inNext ) {
  17817. // computes for inPt the corresponding point inPt' on a new contour
  17818. // shifted by 1 unit (length of normalized vector) to the left
  17819. // if we walk along contour clockwise, this new contour is outside the old one
  17820. //
  17821. // inPt' is the intersection of the two lines parallel to the two
  17822. // adjacent edges of inPt at a distance of 1 unit on the left side.
  17823. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  17824. // good reading for geometry algorithms (here: line-line intersection)
  17825. // http://geomalgorithms.com/a05-_intersect-1.html
  17826. const v_prev_x = inPt.x - inPrev.x,
  17827. v_prev_y = inPt.y - inPrev.y;
  17828. const v_next_x = inNext.x - inPt.x,
  17829. v_next_y = inNext.y - inPt.y;
  17830. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  17831. // check for collinear edges
  17832. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  17833. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  17834. // not collinear
  17835. // length of vectors for normalizing
  17836. const v_prev_len = Math.sqrt( v_prev_lensq );
  17837. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  17838. // shift adjacent points by unit vectors to the left
  17839. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  17840. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  17841. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  17842. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  17843. // scaling factor for v_prev to intersection point
  17844. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  17845. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  17846. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  17847. // vector from inPt to intersection point
  17848. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  17849. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  17850. // Don't normalize!, otherwise sharp corners become ugly
  17851. // but prevent crazy spikes
  17852. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  17853. if ( v_trans_lensq <= 2 ) {
  17854. return new Vector2( v_trans_x, v_trans_y );
  17855. } else {
  17856. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  17857. }
  17858. } else {
  17859. // handle special case of collinear edges
  17860. let direction_eq = false; // assumes: opposite
  17861. if ( v_prev_x > Number.EPSILON ) {
  17862. if ( v_next_x > Number.EPSILON ) {
  17863. direction_eq = true;
  17864. }
  17865. } else {
  17866. if ( v_prev_x < - Number.EPSILON ) {
  17867. if ( v_next_x < - Number.EPSILON ) {
  17868. direction_eq = true;
  17869. }
  17870. } else {
  17871. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  17872. direction_eq = true;
  17873. }
  17874. }
  17875. }
  17876. if ( direction_eq ) {
  17877. // console.log("Warning: lines are a straight sequence");
  17878. v_trans_x = - v_prev_y;
  17879. v_trans_y = v_prev_x;
  17880. shrink_by = Math.sqrt( v_prev_lensq );
  17881. } else {
  17882. // console.log("Warning: lines are a straight spike");
  17883. v_trans_x = v_prev_x;
  17884. v_trans_y = v_prev_y;
  17885. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  17886. }
  17887. }
  17888. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  17889. }
  17890. const contourMovements = [];
  17891. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  17892. if ( j === il ) j = 0;
  17893. if ( k === il ) k = 0;
  17894. // (j)---(i)---(k)
  17895. // console.log('i,j,k', i, j , k)
  17896. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  17897. }
  17898. const holesMovements = [];
  17899. let oneHoleMovements, verticesMovements = contourMovements.concat();
  17900. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  17901. const ahole = holes[ h ];
  17902. oneHoleMovements = [];
  17903. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  17904. if ( j === il ) j = 0;
  17905. if ( k === il ) k = 0;
  17906. // (j)---(i)---(k)
  17907. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  17908. }
  17909. holesMovements.push( oneHoleMovements );
  17910. verticesMovements = verticesMovements.concat( oneHoleMovements );
  17911. }
  17912. // Loop bevelSegments, 1 for the front, 1 for the back
  17913. for ( let b = 0; b < bevelSegments; b ++ ) {
  17914. //for ( b = bevelSegments; b > 0; b -- ) {
  17915. const t = b / bevelSegments;
  17916. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  17917. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  17918. // contract shape
  17919. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  17920. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  17921. v( vert.x, vert.y, - z );
  17922. }
  17923. // expand holes
  17924. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  17925. const ahole = holes[ h ];
  17926. oneHoleMovements = holesMovements[ h ];
  17927. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  17928. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  17929. v( vert.x, vert.y, - z );
  17930. }
  17931. }
  17932. }
  17933. const bs = bevelSize + bevelOffset;
  17934. // Back facing vertices
  17935. for ( let i = 0; i < vlen; i ++ ) {
  17936. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  17937. if ( ! extrudeByPath ) {
  17938. v( vert.x, vert.y, 0 );
  17939. } else {
  17940. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  17941. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  17942. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  17943. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  17944. v( position2.x, position2.y, position2.z );
  17945. }
  17946. }
  17947. // Add stepped vertices...
  17948. // Including front facing vertices
  17949. for ( let s = 1; s <= steps; s ++ ) {
  17950. for ( let i = 0; i < vlen; i ++ ) {
  17951. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  17952. if ( ! extrudeByPath ) {
  17953. v( vert.x, vert.y, depth / steps * s );
  17954. } else {
  17955. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  17956. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  17957. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  17958. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  17959. v( position2.x, position2.y, position2.z );
  17960. }
  17961. }
  17962. }
  17963. // Add bevel segments planes
  17964. //for ( b = 1; b <= bevelSegments; b ++ ) {
  17965. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  17966. const t = b / bevelSegments;
  17967. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  17968. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  17969. // contract shape
  17970. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  17971. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  17972. v( vert.x, vert.y, depth + z );
  17973. }
  17974. // expand holes
  17975. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  17976. const ahole = holes[ h ];
  17977. oneHoleMovements = holesMovements[ h ];
  17978. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  17979. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  17980. if ( ! extrudeByPath ) {
  17981. v( vert.x, vert.y, depth + z );
  17982. } else {
  17983. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  17984. }
  17985. }
  17986. }
  17987. }
  17988. /* Faces */
  17989. // Top and bottom faces
  17990. buildLidFaces();
  17991. // Sides faces
  17992. buildSideFaces();
  17993. ///// Internal functions
  17994. function buildLidFaces() {
  17995. const start = verticesArray.length / 3;
  17996. if ( bevelEnabled ) {
  17997. let layer = 0; // steps + 1
  17998. let offset = vlen * layer;
  17999. // Bottom faces
  18000. for ( let i = 0; i < flen; i ++ ) {
  18001. const face = faces[ i ];
  18002. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  18003. }
  18004. layer = steps + bevelSegments * 2;
  18005. offset = vlen * layer;
  18006. // Top faces
  18007. for ( let i = 0; i < flen; i ++ ) {
  18008. const face = faces[ i ];
  18009. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  18010. }
  18011. } else {
  18012. // Bottom faces
  18013. for ( let i = 0; i < flen; i ++ ) {
  18014. const face = faces[ i ];
  18015. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  18016. }
  18017. // Top faces
  18018. for ( let i = 0; i < flen; i ++ ) {
  18019. const face = faces[ i ];
  18020. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  18021. }
  18022. }
  18023. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  18024. }
  18025. // Create faces for the z-sides of the shape
  18026. function buildSideFaces() {
  18027. const start = verticesArray.length / 3;
  18028. let layeroffset = 0;
  18029. sidewalls( contour, layeroffset );
  18030. layeroffset += contour.length;
  18031. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  18032. const ahole = holes[ h ];
  18033. sidewalls( ahole, layeroffset );
  18034. //, true
  18035. layeroffset += ahole.length;
  18036. }
  18037. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  18038. }
  18039. function sidewalls( contour, layeroffset ) {
  18040. let i = contour.length;
  18041. while ( -- i >= 0 ) {
  18042. const j = i;
  18043. let k = i - 1;
  18044. if ( k < 0 ) k = contour.length - 1;
  18045. //console.log('b', i,j, i-1, k,vertices.length);
  18046. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  18047. const slen1 = vlen * s;
  18048. const slen2 = vlen * ( s + 1 );
  18049. const a = layeroffset + j + slen1,
  18050. b = layeroffset + k + slen1,
  18051. c = layeroffset + k + slen2,
  18052. d = layeroffset + j + slen2;
  18053. f4( a, b, c, d );
  18054. }
  18055. }
  18056. }
  18057. function v( x, y, z ) {
  18058. placeholder.push( x );
  18059. placeholder.push( y );
  18060. placeholder.push( z );
  18061. }
  18062. function f3( a, b, c ) {
  18063. addVertex( a );
  18064. addVertex( b );
  18065. addVertex( c );
  18066. const nextIndex = verticesArray.length / 3;
  18067. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  18068. addUV( uvs[ 0 ] );
  18069. addUV( uvs[ 1 ] );
  18070. addUV( uvs[ 2 ] );
  18071. }
  18072. function f4( a, b, c, d ) {
  18073. addVertex( a );
  18074. addVertex( b );
  18075. addVertex( d );
  18076. addVertex( b );
  18077. addVertex( c );
  18078. addVertex( d );
  18079. const nextIndex = verticesArray.length / 3;
  18080. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  18081. addUV( uvs[ 0 ] );
  18082. addUV( uvs[ 1 ] );
  18083. addUV( uvs[ 3 ] );
  18084. addUV( uvs[ 1 ] );
  18085. addUV( uvs[ 2 ] );
  18086. addUV( uvs[ 3 ] );
  18087. }
  18088. function addVertex( index ) {
  18089. verticesArray.push( placeholder[ index * 3 + 0 ] );
  18090. verticesArray.push( placeholder[ index * 3 + 1 ] );
  18091. verticesArray.push( placeholder[ index * 3 + 2 ] );
  18092. }
  18093. function addUV( vector2 ) {
  18094. uvArray.push( vector2.x );
  18095. uvArray.push( vector2.y );
  18096. }
  18097. }
  18098. }
  18099. toJSON() {
  18100. const data = super.toJSON();
  18101. const shapes = this.parameters.shapes;
  18102. const options = this.parameters.options;
  18103. return toJSON$1( shapes, options, data );
  18104. }
  18105. static fromJSON( data, shapes ) {
  18106. const geometryShapes = [];
  18107. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  18108. const shape = shapes[ data.shapes[ j ] ];
  18109. geometryShapes.push( shape );
  18110. }
  18111. const extrudePath = data.options.extrudePath;
  18112. if ( extrudePath !== undefined ) {
  18113. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  18114. }
  18115. return new ExtrudeGeometry( geometryShapes, data.options );
  18116. }
  18117. }
  18118. const WorldUVGenerator = {
  18119. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  18120. const a_x = vertices[ indexA * 3 ];
  18121. const a_y = vertices[ indexA * 3 + 1 ];
  18122. const b_x = vertices[ indexB * 3 ];
  18123. const b_y = vertices[ indexB * 3 + 1 ];
  18124. const c_x = vertices[ indexC * 3 ];
  18125. const c_y = vertices[ indexC * 3 + 1 ];
  18126. return [
  18127. new Vector2( a_x, a_y ),
  18128. new Vector2( b_x, b_y ),
  18129. new Vector2( c_x, c_y )
  18130. ];
  18131. },
  18132. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  18133. const a_x = vertices[ indexA * 3 ];
  18134. const a_y = vertices[ indexA * 3 + 1 ];
  18135. const a_z = vertices[ indexA * 3 + 2 ];
  18136. const b_x = vertices[ indexB * 3 ];
  18137. const b_y = vertices[ indexB * 3 + 1 ];
  18138. const b_z = vertices[ indexB * 3 + 2 ];
  18139. const c_x = vertices[ indexC * 3 ];
  18140. const c_y = vertices[ indexC * 3 + 1 ];
  18141. const c_z = vertices[ indexC * 3 + 2 ];
  18142. const d_x = vertices[ indexD * 3 ];
  18143. const d_y = vertices[ indexD * 3 + 1 ];
  18144. const d_z = vertices[ indexD * 3 + 2 ];
  18145. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  18146. return [
  18147. new Vector2( a_x, 1 - a_z ),
  18148. new Vector2( b_x, 1 - b_z ),
  18149. new Vector2( c_x, 1 - c_z ),
  18150. new Vector2( d_x, 1 - d_z )
  18151. ];
  18152. } else {
  18153. return [
  18154. new Vector2( a_y, 1 - a_z ),
  18155. new Vector2( b_y, 1 - b_z ),
  18156. new Vector2( c_y, 1 - c_z ),
  18157. new Vector2( d_y, 1 - d_z )
  18158. ];
  18159. }
  18160. }
  18161. };
  18162. function toJSON$1( shapes, options, data ) {
  18163. data.shapes = [];
  18164. if ( Array.isArray( shapes ) ) {
  18165. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  18166. const shape = shapes[ i ];
  18167. data.shapes.push( shape.uuid );
  18168. }
  18169. } else {
  18170. data.shapes.push( shapes.uuid );
  18171. }
  18172. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  18173. return data;
  18174. }
  18175. class ShapeGeometry extends BufferGeometry {
  18176. constructor( shapes, curveSegments = 12 ) {
  18177. super();
  18178. this.type = 'ShapeGeometry';
  18179. this.parameters = {
  18180. shapes: shapes,
  18181. curveSegments: curveSegments
  18182. };
  18183. // buffers
  18184. const indices = [];
  18185. const vertices = [];
  18186. const normals = [];
  18187. const uvs = [];
  18188. // helper variables
  18189. let groupStart = 0;
  18190. let groupCount = 0;
  18191. // allow single and array values for "shapes" parameter
  18192. if ( Array.isArray( shapes ) === false ) {
  18193. addShape( shapes );
  18194. } else {
  18195. for ( let i = 0; i < shapes.length; i ++ ) {
  18196. addShape( shapes[ i ] );
  18197. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  18198. groupStart += groupCount;
  18199. groupCount = 0;
  18200. }
  18201. }
  18202. // build geometry
  18203. this.setIndex( indices );
  18204. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18205. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  18206. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  18207. // helper functions
  18208. function addShape( shape ) {
  18209. const indexOffset = vertices.length / 3;
  18210. const points = shape.extractPoints( curveSegments );
  18211. let shapeVertices = points.shape;
  18212. const shapeHoles = points.holes;
  18213. // check direction of vertices
  18214. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  18215. shapeVertices = shapeVertices.reverse();
  18216. }
  18217. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  18218. const shapeHole = shapeHoles[ i ];
  18219. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  18220. shapeHoles[ i ] = shapeHole.reverse();
  18221. }
  18222. }
  18223. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  18224. // join vertices of inner and outer paths to a single array
  18225. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  18226. const shapeHole = shapeHoles[ i ];
  18227. shapeVertices = shapeVertices.concat( shapeHole );
  18228. }
  18229. // vertices, normals, uvs
  18230. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  18231. const vertex = shapeVertices[ i ];
  18232. vertices.push( vertex.x, vertex.y, 0 );
  18233. normals.push( 0, 0, 1 );
  18234. uvs.push( vertex.x, vertex.y ); // world uvs
  18235. }
  18236. // incides
  18237. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  18238. const face = faces[ i ];
  18239. const a = face[ 0 ] + indexOffset;
  18240. const b = face[ 1 ] + indexOffset;
  18241. const c = face[ 2 ] + indexOffset;
  18242. indices.push( a, b, c );
  18243. groupCount += 3;
  18244. }
  18245. }
  18246. }
  18247. toJSON() {
  18248. const data = super.toJSON();
  18249. const shapes = this.parameters.shapes;
  18250. return toJSON( shapes, data );
  18251. }
  18252. static fromJSON( data, shapes ) {
  18253. const geometryShapes = [];
  18254. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  18255. const shape = shapes[ data.shapes[ j ] ];
  18256. geometryShapes.push( shape );
  18257. }
  18258. return new ShapeGeometry( geometryShapes, data.curveSegments );
  18259. }
  18260. }
  18261. function toJSON( shapes, data ) {
  18262. data.shapes = [];
  18263. if ( Array.isArray( shapes ) ) {
  18264. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  18265. const shape = shapes[ i ];
  18266. data.shapes.push( shape.uuid );
  18267. }
  18268. } else {
  18269. data.shapes.push( shapes.uuid );
  18270. }
  18271. return data;
  18272. }
  18273. class SphereGeometry extends BufferGeometry {
  18274. constructor( radius = 1, widthSegments = 8, heightSegments = 6, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  18275. super();
  18276. this.type = 'SphereGeometry';
  18277. this.parameters = {
  18278. radius: radius,
  18279. widthSegments: widthSegments,
  18280. heightSegments: heightSegments,
  18281. phiStart: phiStart,
  18282. phiLength: phiLength,
  18283. thetaStart: thetaStart,
  18284. thetaLength: thetaLength
  18285. };
  18286. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  18287. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  18288. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  18289. let index = 0;
  18290. const grid = [];
  18291. const vertex = new Vector3();
  18292. const normal = new Vector3();
  18293. // buffers
  18294. const indices = [];
  18295. const vertices = [];
  18296. const normals = [];
  18297. const uvs = [];
  18298. // generate vertices, normals and uvs
  18299. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  18300. const verticesRow = [];
  18301. const v = iy / heightSegments;
  18302. // special case for the poles
  18303. let uOffset = 0;
  18304. if ( iy == 0 && thetaStart == 0 ) {
  18305. uOffset = 0.5 / widthSegments;
  18306. } else if ( iy == heightSegments && thetaEnd == Math.PI ) {
  18307. uOffset = - 0.5 / widthSegments;
  18308. }
  18309. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  18310. const u = ix / widthSegments;
  18311. // vertex
  18312. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  18313. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  18314. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  18315. vertices.push( vertex.x, vertex.y, vertex.z );
  18316. // normal
  18317. normal.copy( vertex ).normalize();
  18318. normals.push( normal.x, normal.y, normal.z );
  18319. // uv
  18320. uvs.push( u + uOffset, 1 - v );
  18321. verticesRow.push( index ++ );
  18322. }
  18323. grid.push( verticesRow );
  18324. }
  18325. // indices
  18326. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  18327. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  18328. const a = grid[ iy ][ ix + 1 ];
  18329. const b = grid[ iy ][ ix ];
  18330. const c = grid[ iy + 1 ][ ix ];
  18331. const d = grid[ iy + 1 ][ ix + 1 ];
  18332. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  18333. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  18334. }
  18335. }
  18336. // build geometry
  18337. this.setIndex( indices );
  18338. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18339. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  18340. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  18341. }
  18342. static fromJSON( data ) {
  18343. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  18344. }
  18345. }
  18346. class TubeGeometry extends BufferGeometry {
  18347. constructor( path, tubularSegments = 64, radius = 1, radialSegments = 8, closed = false ) {
  18348. super();
  18349. this.type = 'TubeGeometry';
  18350. this.parameters = {
  18351. path: path,
  18352. tubularSegments: tubularSegments,
  18353. radius: radius,
  18354. radialSegments: radialSegments,
  18355. closed: closed
  18356. };
  18357. const frames = path.computeFrenetFrames( tubularSegments, closed );
  18358. // expose internals
  18359. this.tangents = frames.tangents;
  18360. this.normals = frames.normals;
  18361. this.binormals = frames.binormals;
  18362. // helper variables
  18363. const vertex = new Vector3();
  18364. const normal = new Vector3();
  18365. const uv = new Vector2();
  18366. let P = new Vector3();
  18367. // buffer
  18368. const vertices = [];
  18369. const normals = [];
  18370. const uvs = [];
  18371. const indices = [];
  18372. // create buffer data
  18373. generateBufferData();
  18374. // build geometry
  18375. this.setIndex( indices );
  18376. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18377. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  18378. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  18379. // functions
  18380. function generateBufferData() {
  18381. for ( let i = 0; i < tubularSegments; i ++ ) {
  18382. generateSegment( i );
  18383. }
  18384. // if the geometry is not closed, generate the last row of vertices and normals
  18385. // at the regular position on the given path
  18386. //
  18387. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  18388. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  18389. // uvs are generated in a separate function.
  18390. // this makes it easy compute correct values for closed geometries
  18391. generateUVs();
  18392. // finally create faces
  18393. generateIndices();
  18394. }
  18395. function generateSegment( i ) {
  18396. // we use getPointAt to sample evenly distributed points from the given path
  18397. P = path.getPointAt( i / tubularSegments, P );
  18398. // retrieve corresponding normal and binormal
  18399. const N = frames.normals[ i ];
  18400. const B = frames.binormals[ i ];
  18401. // generate normals and vertices for the current segment
  18402. for ( let j = 0; j <= radialSegments; j ++ ) {
  18403. const v = j / radialSegments * Math.PI * 2;
  18404. const sin = Math.sin( v );
  18405. const cos = - Math.cos( v );
  18406. // normal
  18407. normal.x = ( cos * N.x + sin * B.x );
  18408. normal.y = ( cos * N.y + sin * B.y );
  18409. normal.z = ( cos * N.z + sin * B.z );
  18410. normal.normalize();
  18411. normals.push( normal.x, normal.y, normal.z );
  18412. // vertex
  18413. vertex.x = P.x + radius * normal.x;
  18414. vertex.y = P.y + radius * normal.y;
  18415. vertex.z = P.z + radius * normal.z;
  18416. vertices.push( vertex.x, vertex.y, vertex.z );
  18417. }
  18418. }
  18419. function generateIndices() {
  18420. for ( let j = 1; j <= tubularSegments; j ++ ) {
  18421. for ( let i = 1; i <= radialSegments; i ++ ) {
  18422. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  18423. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  18424. const c = ( radialSegments + 1 ) * j + i;
  18425. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  18426. // faces
  18427. indices.push( a, b, d );
  18428. indices.push( b, c, d );
  18429. }
  18430. }
  18431. }
  18432. function generateUVs() {
  18433. for ( let i = 0; i <= tubularSegments; i ++ ) {
  18434. for ( let j = 0; j <= radialSegments; j ++ ) {
  18435. uv.x = i / tubularSegments;
  18436. uv.y = j / radialSegments;
  18437. uvs.push( uv.x, uv.y );
  18438. }
  18439. }
  18440. }
  18441. }
  18442. toJSON() {
  18443. const data = super.toJSON();
  18444. data.path = this.parameters.path.toJSON();
  18445. return data;
  18446. }
  18447. static fromJSON( data ) {
  18448. // This only works for built-in curves (e.g. CatmullRomCurve3).
  18449. // User defined curves or instances of CurvePath will not be deserialized.
  18450. return new TubeGeometry(
  18451. new Curves[ data.path.type ]().fromJSON( data.path ),
  18452. data.tubularSegments,
  18453. data.radius,
  18454. data.radialSegments,
  18455. data.closed
  18456. );
  18457. }
  18458. }
  18459. /**
  18460. * parameters = {
  18461. * color: <THREE.Color>
  18462. * }
  18463. */
  18464. class ShadowMaterial extends Material {
  18465. constructor( parameters ) {
  18466. super();
  18467. this.type = 'ShadowMaterial';
  18468. this.color = new Color( 0x000000 );
  18469. this.transparent = true;
  18470. this.setValues( parameters );
  18471. }
  18472. copy( source ) {
  18473. super.copy( source );
  18474. this.color.copy( source.color );
  18475. return this;
  18476. }
  18477. }
  18478. ShadowMaterial.prototype.isShadowMaterial = true;
  18479. class RawShaderMaterial extends ShaderMaterial {
  18480. constructor( parameters ) {
  18481. super( parameters );
  18482. this.type = 'RawShaderMaterial';
  18483. }
  18484. }
  18485. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  18486. /**
  18487. * parameters = {
  18488. * color: <hex>,
  18489. * roughness: <float>,
  18490. * metalness: <float>,
  18491. * opacity: <float>,
  18492. *
  18493. * map: new THREE.Texture( <Image> ),
  18494. *
  18495. * lightMap: new THREE.Texture( <Image> ),
  18496. * lightMapIntensity: <float>
  18497. *
  18498. * aoMap: new THREE.Texture( <Image> ),
  18499. * aoMapIntensity: <float>
  18500. *
  18501. * emissive: <hex>,
  18502. * emissiveIntensity: <float>
  18503. * emissiveMap: new THREE.Texture( <Image> ),
  18504. *
  18505. * bumpMap: new THREE.Texture( <Image> ),
  18506. * bumpScale: <float>,
  18507. *
  18508. * normalMap: new THREE.Texture( <Image> ),
  18509. * normalMapType: THREE.TangentSpaceNormalMap,
  18510. * normalScale: <Vector2>,
  18511. *
  18512. * displacementMap: new THREE.Texture( <Image> ),
  18513. * displacementScale: <float>,
  18514. * displacementBias: <float>,
  18515. *
  18516. * roughnessMap: new THREE.Texture( <Image> ),
  18517. *
  18518. * metalnessMap: new THREE.Texture( <Image> ),
  18519. *
  18520. * alphaMap: new THREE.Texture( <Image> ),
  18521. *
  18522. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  18523. * envMapIntensity: <float>
  18524. *
  18525. * refractionRatio: <float>,
  18526. *
  18527. * wireframe: <boolean>,
  18528. * wireframeLinewidth: <float>,
  18529. *
  18530. * morphTargets: <bool>,
  18531. * morphNormals: <bool>,
  18532. *
  18533. * flatShading: <bool>
  18534. * }
  18535. */
  18536. class MeshStandardMaterial extends Material {
  18537. constructor( parameters ) {
  18538. super();
  18539. this.defines = { 'STANDARD': '' };
  18540. this.type = 'MeshStandardMaterial';
  18541. this.color = new Color( 0xffffff ); // diffuse
  18542. this.roughness = 1.0;
  18543. this.metalness = 0.0;
  18544. this.map = null;
  18545. this.lightMap = null;
  18546. this.lightMapIntensity = 1.0;
  18547. this.aoMap = null;
  18548. this.aoMapIntensity = 1.0;
  18549. this.emissive = new Color( 0x000000 );
  18550. this.emissiveIntensity = 1.0;
  18551. this.emissiveMap = null;
  18552. this.bumpMap = null;
  18553. this.bumpScale = 1;
  18554. this.normalMap = null;
  18555. this.normalMapType = TangentSpaceNormalMap;
  18556. this.normalScale = new Vector2( 1, 1 );
  18557. this.displacementMap = null;
  18558. this.displacementScale = 1;
  18559. this.displacementBias = 0;
  18560. this.roughnessMap = null;
  18561. this.metalnessMap = null;
  18562. this.alphaMap = null;
  18563. this.envMap = null;
  18564. this.envMapIntensity = 1.0;
  18565. this.refractionRatio = 0.98;
  18566. this.wireframe = false;
  18567. this.wireframeLinewidth = 1;
  18568. this.wireframeLinecap = 'round';
  18569. this.wireframeLinejoin = 'round';
  18570. this.morphTargets = false;
  18571. this.morphNormals = false;
  18572. this.flatShading = false;
  18573. this.vertexTangents = false;
  18574. this.setValues( parameters );
  18575. }
  18576. copy( source ) {
  18577. super.copy( source );
  18578. this.defines = { 'STANDARD': '' };
  18579. this.color.copy( source.color );
  18580. this.roughness = source.roughness;
  18581. this.metalness = source.metalness;
  18582. this.map = source.map;
  18583. this.lightMap = source.lightMap;
  18584. this.lightMapIntensity = source.lightMapIntensity;
  18585. this.aoMap = source.aoMap;
  18586. this.aoMapIntensity = source.aoMapIntensity;
  18587. this.emissive.copy( source.emissive );
  18588. this.emissiveMap = source.emissiveMap;
  18589. this.emissiveIntensity = source.emissiveIntensity;
  18590. this.bumpMap = source.bumpMap;
  18591. this.bumpScale = source.bumpScale;
  18592. this.normalMap = source.normalMap;
  18593. this.normalMapType = source.normalMapType;
  18594. this.normalScale.copy( source.normalScale );
  18595. this.displacementMap = source.displacementMap;
  18596. this.displacementScale = source.displacementScale;
  18597. this.displacementBias = source.displacementBias;
  18598. this.roughnessMap = source.roughnessMap;
  18599. this.metalnessMap = source.metalnessMap;
  18600. this.alphaMap = source.alphaMap;
  18601. this.envMap = source.envMap;
  18602. this.envMapIntensity = source.envMapIntensity;
  18603. this.refractionRatio = source.refractionRatio;
  18604. this.wireframe = source.wireframe;
  18605. this.wireframeLinewidth = source.wireframeLinewidth;
  18606. this.wireframeLinecap = source.wireframeLinecap;
  18607. this.wireframeLinejoin = source.wireframeLinejoin;
  18608. this.morphTargets = source.morphTargets;
  18609. this.morphNormals = source.morphNormals;
  18610. this.flatShading = source.flatShading;
  18611. this.vertexTangents = source.vertexTangents;
  18612. return this;
  18613. }
  18614. }
  18615. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  18616. /**
  18617. * parameters = {
  18618. * clearcoat: <float>,
  18619. * clearcoatMap: new THREE.Texture( <Image> ),
  18620. * clearcoatRoughness: <float>,
  18621. * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
  18622. * clearcoatNormalScale: <Vector2>,
  18623. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  18624. *
  18625. * reflectivity: <float>,
  18626. * ior: <float>,
  18627. *
  18628. * sheen: <Color>,
  18629. *
  18630. * transmission: <float>,
  18631. * transmissionMap: new THREE.Texture( <Image> ),
  18632. *
  18633. * thickness: <float>,
  18634. * thicknessMap: new THREE.Texture( <Image> ),
  18635. * attenuationDistance: <float>,
  18636. * attenuationColor: <Color>
  18637. * }
  18638. */
  18639. class MeshPhysicalMaterial extends MeshStandardMaterial {
  18640. constructor( parameters ) {
  18641. super();
  18642. this.defines = {
  18643. 'STANDARD': '',
  18644. 'PHYSICAL': ''
  18645. };
  18646. this.type = 'MeshPhysicalMaterial';
  18647. this.clearcoat = 0.0;
  18648. this.clearcoatMap = null;
  18649. this.clearcoatRoughness = 0.0;
  18650. this.clearcoatRoughnessMap = null;
  18651. this.clearcoatNormalScale = new Vector2( 1, 1 );
  18652. this.clearcoatNormalMap = null;
  18653. this.reflectivity = 0.5; // maps to F0 = 0.04
  18654. Object.defineProperty( this, 'ior', {
  18655. get: function () {
  18656. return ( 1 + 0.4 * this.reflectivity ) / ( 1 - 0.4 * this.reflectivity );
  18657. },
  18658. set: function ( ior ) {
  18659. this.reflectivity = clamp( 2.5 * ( ior - 1 ) / ( ior + 1 ), 0, 1 );
  18660. }
  18661. } );
  18662. this.sheen = null; // null will disable sheen bsdf
  18663. this.transmission = 0.0;
  18664. this.transmissionMap = null;
  18665. this.thickness = 0.01;
  18666. this.thicknessMap = null;
  18667. this.attenuationDistance = 0.0;
  18668. this.attenuationColor = new Color( 1, 1, 1 );
  18669. this.setValues( parameters );
  18670. }
  18671. copy( source ) {
  18672. super.copy( source );
  18673. this.defines = {
  18674. 'STANDARD': '',
  18675. 'PHYSICAL': ''
  18676. };
  18677. this.clearcoat = source.clearcoat;
  18678. this.clearcoatMap = source.clearcoatMap;
  18679. this.clearcoatRoughness = source.clearcoatRoughness;
  18680. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  18681. this.clearcoatNormalMap = source.clearcoatNormalMap;
  18682. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  18683. this.reflectivity = source.reflectivity;
  18684. if ( source.sheen ) {
  18685. this.sheen = ( this.sheen || new Color() ).copy( source.sheen );
  18686. } else {
  18687. this.sheen = null;
  18688. }
  18689. this.transmission = source.transmission;
  18690. this.transmissionMap = source.transmissionMap;
  18691. this.thickness = source.thickness;
  18692. this.thicknessMap = source.thicknessMap;
  18693. this.attenuationDistance = source.attenuationDistance;
  18694. this.attenuationColor.copy( source.attenuationColor );
  18695. return this;
  18696. }
  18697. }
  18698. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  18699. /**
  18700. * parameters = {
  18701. * color: <hex>,
  18702. * specular: <hex>,
  18703. * shininess: <float>,
  18704. * opacity: <float>,
  18705. *
  18706. * map: new THREE.Texture( <Image> ),
  18707. *
  18708. * lightMap: new THREE.Texture( <Image> ),
  18709. * lightMapIntensity: <float>
  18710. *
  18711. * aoMap: new THREE.Texture( <Image> ),
  18712. * aoMapIntensity: <float>
  18713. *
  18714. * emissive: <hex>,
  18715. * emissiveIntensity: <float>
  18716. * emissiveMap: new THREE.Texture( <Image> ),
  18717. *
  18718. * bumpMap: new THREE.Texture( <Image> ),
  18719. * bumpScale: <float>,
  18720. *
  18721. * normalMap: new THREE.Texture( <Image> ),
  18722. * normalMapType: THREE.TangentSpaceNormalMap,
  18723. * normalScale: <Vector2>,
  18724. *
  18725. * displacementMap: new THREE.Texture( <Image> ),
  18726. * displacementScale: <float>,
  18727. * displacementBias: <float>,
  18728. *
  18729. * specularMap: new THREE.Texture( <Image> ),
  18730. *
  18731. * alphaMap: new THREE.Texture( <Image> ),
  18732. *
  18733. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  18734. * combine: THREE.MultiplyOperation,
  18735. * reflectivity: <float>,
  18736. * refractionRatio: <float>,
  18737. *
  18738. * wireframe: <boolean>,
  18739. * wireframeLinewidth: <float>,
  18740. *
  18741. * morphTargets: <bool>,
  18742. * morphNormals: <bool>,
  18743. *
  18744. * flatShading: <bool>
  18745. * }
  18746. */
  18747. class MeshPhongMaterial extends Material {
  18748. constructor( parameters ) {
  18749. super();
  18750. this.type = 'MeshPhongMaterial';
  18751. this.color = new Color( 0xffffff ); // diffuse
  18752. this.specular = new Color( 0x111111 );
  18753. this.shininess = 30;
  18754. this.map = null;
  18755. this.lightMap = null;
  18756. this.lightMapIntensity = 1.0;
  18757. this.aoMap = null;
  18758. this.aoMapIntensity = 1.0;
  18759. this.emissive = new Color( 0x000000 );
  18760. this.emissiveIntensity = 1.0;
  18761. this.emissiveMap = null;
  18762. this.bumpMap = null;
  18763. this.bumpScale = 1;
  18764. this.normalMap = null;
  18765. this.normalMapType = TangentSpaceNormalMap;
  18766. this.normalScale = new Vector2( 1, 1 );
  18767. this.displacementMap = null;
  18768. this.displacementScale = 1;
  18769. this.displacementBias = 0;
  18770. this.specularMap = null;
  18771. this.alphaMap = null;
  18772. this.envMap = null;
  18773. this.combine = MultiplyOperation;
  18774. this.reflectivity = 1;
  18775. this.refractionRatio = 0.98;
  18776. this.wireframe = false;
  18777. this.wireframeLinewidth = 1;
  18778. this.wireframeLinecap = 'round';
  18779. this.wireframeLinejoin = 'round';
  18780. this.morphTargets = false;
  18781. this.morphNormals = false;
  18782. this.flatShading = false;
  18783. this.setValues( parameters );
  18784. }
  18785. copy( source ) {
  18786. super.copy( source );
  18787. this.color.copy( source.color );
  18788. this.specular.copy( source.specular );
  18789. this.shininess = source.shininess;
  18790. this.map = source.map;
  18791. this.lightMap = source.lightMap;
  18792. this.lightMapIntensity = source.lightMapIntensity;
  18793. this.aoMap = source.aoMap;
  18794. this.aoMapIntensity = source.aoMapIntensity;
  18795. this.emissive.copy( source.emissive );
  18796. this.emissiveMap = source.emissiveMap;
  18797. this.emissiveIntensity = source.emissiveIntensity;
  18798. this.bumpMap = source.bumpMap;
  18799. this.bumpScale = source.bumpScale;
  18800. this.normalMap = source.normalMap;
  18801. this.normalMapType = source.normalMapType;
  18802. this.normalScale.copy( source.normalScale );
  18803. this.displacementMap = source.displacementMap;
  18804. this.displacementScale = source.displacementScale;
  18805. this.displacementBias = source.displacementBias;
  18806. this.specularMap = source.specularMap;
  18807. this.alphaMap = source.alphaMap;
  18808. this.envMap = source.envMap;
  18809. this.combine = source.combine;
  18810. this.reflectivity = source.reflectivity;
  18811. this.refractionRatio = source.refractionRatio;
  18812. this.wireframe = source.wireframe;
  18813. this.wireframeLinewidth = source.wireframeLinewidth;
  18814. this.wireframeLinecap = source.wireframeLinecap;
  18815. this.wireframeLinejoin = source.wireframeLinejoin;
  18816. this.morphTargets = source.morphTargets;
  18817. this.morphNormals = source.morphNormals;
  18818. this.flatShading = source.flatShading;
  18819. return this;
  18820. }
  18821. }
  18822. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  18823. /**
  18824. * parameters = {
  18825. * color: <hex>,
  18826. *
  18827. * map: new THREE.Texture( <Image> ),
  18828. * gradientMap: new THREE.Texture( <Image> ),
  18829. *
  18830. * lightMap: new THREE.Texture( <Image> ),
  18831. * lightMapIntensity: <float>
  18832. *
  18833. * aoMap: new THREE.Texture( <Image> ),
  18834. * aoMapIntensity: <float>
  18835. *
  18836. * emissive: <hex>,
  18837. * emissiveIntensity: <float>
  18838. * emissiveMap: new THREE.Texture( <Image> ),
  18839. *
  18840. * bumpMap: new THREE.Texture( <Image> ),
  18841. * bumpScale: <float>,
  18842. *
  18843. * normalMap: new THREE.Texture( <Image> ),
  18844. * normalMapType: THREE.TangentSpaceNormalMap,
  18845. * normalScale: <Vector2>,
  18846. *
  18847. * displacementMap: new THREE.Texture( <Image> ),
  18848. * displacementScale: <float>,
  18849. * displacementBias: <float>,
  18850. *
  18851. * alphaMap: new THREE.Texture( <Image> ),
  18852. *
  18853. * wireframe: <boolean>,
  18854. * wireframeLinewidth: <float>,
  18855. *
  18856. * morphTargets: <bool>,
  18857. * morphNormals: <bool>
  18858. * }
  18859. */
  18860. class MeshToonMaterial extends Material {
  18861. constructor( parameters ) {
  18862. super();
  18863. this.defines = { 'TOON': '' };
  18864. this.type = 'MeshToonMaterial';
  18865. this.color = new Color( 0xffffff );
  18866. this.map = null;
  18867. this.gradientMap = null;
  18868. this.lightMap = null;
  18869. this.lightMapIntensity = 1.0;
  18870. this.aoMap = null;
  18871. this.aoMapIntensity = 1.0;
  18872. this.emissive = new Color( 0x000000 );
  18873. this.emissiveIntensity = 1.0;
  18874. this.emissiveMap = null;
  18875. this.bumpMap = null;
  18876. this.bumpScale = 1;
  18877. this.normalMap = null;
  18878. this.normalMapType = TangentSpaceNormalMap;
  18879. this.normalScale = new Vector2( 1, 1 );
  18880. this.displacementMap = null;
  18881. this.displacementScale = 1;
  18882. this.displacementBias = 0;
  18883. this.alphaMap = null;
  18884. this.wireframe = false;
  18885. this.wireframeLinewidth = 1;
  18886. this.wireframeLinecap = 'round';
  18887. this.wireframeLinejoin = 'round';
  18888. this.morphTargets = false;
  18889. this.morphNormals = false;
  18890. this.setValues( parameters );
  18891. }
  18892. copy( source ) {
  18893. super.copy( source );
  18894. this.color.copy( source.color );
  18895. this.map = source.map;
  18896. this.gradientMap = source.gradientMap;
  18897. this.lightMap = source.lightMap;
  18898. this.lightMapIntensity = source.lightMapIntensity;
  18899. this.aoMap = source.aoMap;
  18900. this.aoMapIntensity = source.aoMapIntensity;
  18901. this.emissive.copy( source.emissive );
  18902. this.emissiveMap = source.emissiveMap;
  18903. this.emissiveIntensity = source.emissiveIntensity;
  18904. this.bumpMap = source.bumpMap;
  18905. this.bumpScale = source.bumpScale;
  18906. this.normalMap = source.normalMap;
  18907. this.normalMapType = source.normalMapType;
  18908. this.normalScale.copy( source.normalScale );
  18909. this.displacementMap = source.displacementMap;
  18910. this.displacementScale = source.displacementScale;
  18911. this.displacementBias = source.displacementBias;
  18912. this.alphaMap = source.alphaMap;
  18913. this.wireframe = source.wireframe;
  18914. this.wireframeLinewidth = source.wireframeLinewidth;
  18915. this.wireframeLinecap = source.wireframeLinecap;
  18916. this.wireframeLinejoin = source.wireframeLinejoin;
  18917. this.morphTargets = source.morphTargets;
  18918. this.morphNormals = source.morphNormals;
  18919. return this;
  18920. }
  18921. }
  18922. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  18923. /**
  18924. * parameters = {
  18925. * opacity: <float>,
  18926. *
  18927. * bumpMap: new THREE.Texture( <Image> ),
  18928. * bumpScale: <float>,
  18929. *
  18930. * normalMap: new THREE.Texture( <Image> ),
  18931. * normalMapType: THREE.TangentSpaceNormalMap,
  18932. * normalScale: <Vector2>,
  18933. *
  18934. * displacementMap: new THREE.Texture( <Image> ),
  18935. * displacementScale: <float>,
  18936. * displacementBias: <float>,
  18937. *
  18938. * wireframe: <boolean>,
  18939. * wireframeLinewidth: <float>
  18940. *
  18941. * morphTargets: <bool>,
  18942. * morphNormals: <bool>,
  18943. *
  18944. * flatShading: <bool>
  18945. * }
  18946. */
  18947. class MeshNormalMaterial extends Material {
  18948. constructor( parameters ) {
  18949. super();
  18950. this.type = 'MeshNormalMaterial';
  18951. this.bumpMap = null;
  18952. this.bumpScale = 1;
  18953. this.normalMap = null;
  18954. this.normalMapType = TangentSpaceNormalMap;
  18955. this.normalScale = new Vector2( 1, 1 );
  18956. this.displacementMap = null;
  18957. this.displacementScale = 1;
  18958. this.displacementBias = 0;
  18959. this.wireframe = false;
  18960. this.wireframeLinewidth = 1;
  18961. this.fog = false;
  18962. this.morphTargets = false;
  18963. this.morphNormals = false;
  18964. this.flatShading = false;
  18965. this.setValues( parameters );
  18966. }
  18967. copy( source ) {
  18968. super.copy( source );
  18969. this.bumpMap = source.bumpMap;
  18970. this.bumpScale = source.bumpScale;
  18971. this.normalMap = source.normalMap;
  18972. this.normalMapType = source.normalMapType;
  18973. this.normalScale.copy( source.normalScale );
  18974. this.displacementMap = source.displacementMap;
  18975. this.displacementScale = source.displacementScale;
  18976. this.displacementBias = source.displacementBias;
  18977. this.wireframe = source.wireframe;
  18978. this.wireframeLinewidth = source.wireframeLinewidth;
  18979. this.morphTargets = source.morphTargets;
  18980. this.morphNormals = source.morphNormals;
  18981. this.flatShading = source.flatShading;
  18982. return this;
  18983. }
  18984. }
  18985. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  18986. /**
  18987. * parameters = {
  18988. * color: <hex>,
  18989. * opacity: <float>,
  18990. *
  18991. * map: new THREE.Texture( <Image> ),
  18992. *
  18993. * lightMap: new THREE.Texture( <Image> ),
  18994. * lightMapIntensity: <float>
  18995. *
  18996. * aoMap: new THREE.Texture( <Image> ),
  18997. * aoMapIntensity: <float>
  18998. *
  18999. * emissive: <hex>,
  19000. * emissiveIntensity: <float>
  19001. * emissiveMap: new THREE.Texture( <Image> ),
  19002. *
  19003. * specularMap: new THREE.Texture( <Image> ),
  19004. *
  19005. * alphaMap: new THREE.Texture( <Image> ),
  19006. *
  19007. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  19008. * combine: THREE.Multiply,
  19009. * reflectivity: <float>,
  19010. * refractionRatio: <float>,
  19011. *
  19012. * wireframe: <boolean>,
  19013. * wireframeLinewidth: <float>,
  19014. *
  19015. * morphTargets: <bool>,
  19016. * morphNormals: <bool>
  19017. * }
  19018. */
  19019. class MeshLambertMaterial extends Material {
  19020. constructor( parameters ) {
  19021. super();
  19022. this.type = 'MeshLambertMaterial';
  19023. this.color = new Color( 0xffffff ); // diffuse
  19024. this.map = null;
  19025. this.lightMap = null;
  19026. this.lightMapIntensity = 1.0;
  19027. this.aoMap = null;
  19028. this.aoMapIntensity = 1.0;
  19029. this.emissive = new Color( 0x000000 );
  19030. this.emissiveIntensity = 1.0;
  19031. this.emissiveMap = null;
  19032. this.specularMap = null;
  19033. this.alphaMap = null;
  19034. this.envMap = null;
  19035. this.combine = MultiplyOperation;
  19036. this.reflectivity = 1;
  19037. this.refractionRatio = 0.98;
  19038. this.wireframe = false;
  19039. this.wireframeLinewidth = 1;
  19040. this.wireframeLinecap = 'round';
  19041. this.wireframeLinejoin = 'round';
  19042. this.morphTargets = false;
  19043. this.morphNormals = false;
  19044. this.setValues( parameters );
  19045. }
  19046. copy( source ) {
  19047. super.copy( source );
  19048. this.color.copy( source.color );
  19049. this.map = source.map;
  19050. this.lightMap = source.lightMap;
  19051. this.lightMapIntensity = source.lightMapIntensity;
  19052. this.aoMap = source.aoMap;
  19053. this.aoMapIntensity = source.aoMapIntensity;
  19054. this.emissive.copy( source.emissive );
  19055. this.emissiveMap = source.emissiveMap;
  19056. this.emissiveIntensity = source.emissiveIntensity;
  19057. this.specularMap = source.specularMap;
  19058. this.alphaMap = source.alphaMap;
  19059. this.envMap = source.envMap;
  19060. this.combine = source.combine;
  19061. this.reflectivity = source.reflectivity;
  19062. this.refractionRatio = source.refractionRatio;
  19063. this.wireframe = source.wireframe;
  19064. this.wireframeLinewidth = source.wireframeLinewidth;
  19065. this.wireframeLinecap = source.wireframeLinecap;
  19066. this.wireframeLinejoin = source.wireframeLinejoin;
  19067. this.morphTargets = source.morphTargets;
  19068. this.morphNormals = source.morphNormals;
  19069. return this;
  19070. }
  19071. }
  19072. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  19073. /**
  19074. * parameters = {
  19075. * color: <hex>,
  19076. * opacity: <float>,
  19077. *
  19078. * matcap: new THREE.Texture( <Image> ),
  19079. *
  19080. * map: new THREE.Texture( <Image> ),
  19081. *
  19082. * bumpMap: new THREE.Texture( <Image> ),
  19083. * bumpScale: <float>,
  19084. *
  19085. * normalMap: new THREE.Texture( <Image> ),
  19086. * normalMapType: THREE.TangentSpaceNormalMap,
  19087. * normalScale: <Vector2>,
  19088. *
  19089. * displacementMap: new THREE.Texture( <Image> ),
  19090. * displacementScale: <float>,
  19091. * displacementBias: <float>,
  19092. *
  19093. * alphaMap: new THREE.Texture( <Image> ),
  19094. *
  19095. * morphTargets: <bool>,
  19096. * morphNormals: <bool>
  19097. *
  19098. * flatShading: <bool>
  19099. * }
  19100. */
  19101. class MeshMatcapMaterial extends Material {
  19102. constructor( parameters ) {
  19103. super();
  19104. this.defines = { 'MATCAP': '' };
  19105. this.type = 'MeshMatcapMaterial';
  19106. this.color = new Color( 0xffffff ); // diffuse
  19107. this.matcap = null;
  19108. this.map = null;
  19109. this.bumpMap = null;
  19110. this.bumpScale = 1;
  19111. this.normalMap = null;
  19112. this.normalMapType = TangentSpaceNormalMap;
  19113. this.normalScale = new Vector2( 1, 1 );
  19114. this.displacementMap = null;
  19115. this.displacementScale = 1;
  19116. this.displacementBias = 0;
  19117. this.alphaMap = null;
  19118. this.morphTargets = false;
  19119. this.morphNormals = false;
  19120. this.flatShading = false;
  19121. this.setValues( parameters );
  19122. }
  19123. copy( source ) {
  19124. super.copy( source );
  19125. this.defines = { 'MATCAP': '' };
  19126. this.color.copy( source.color );
  19127. this.matcap = source.matcap;
  19128. this.map = source.map;
  19129. this.bumpMap = source.bumpMap;
  19130. this.bumpScale = source.bumpScale;
  19131. this.normalMap = source.normalMap;
  19132. this.normalMapType = source.normalMapType;
  19133. this.normalScale.copy( source.normalScale );
  19134. this.displacementMap = source.displacementMap;
  19135. this.displacementScale = source.displacementScale;
  19136. this.displacementBias = source.displacementBias;
  19137. this.alphaMap = source.alphaMap;
  19138. this.morphTargets = source.morphTargets;
  19139. this.morphNormals = source.morphNormals;
  19140. this.flatShading = source.flatShading;
  19141. return this;
  19142. }
  19143. }
  19144. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  19145. /**
  19146. * parameters = {
  19147. * color: <hex>,
  19148. * opacity: <float>,
  19149. *
  19150. * linewidth: <float>,
  19151. *
  19152. * scale: <float>,
  19153. * dashSize: <float>,
  19154. * gapSize: <float>
  19155. * }
  19156. */
  19157. class LineDashedMaterial extends LineBasicMaterial {
  19158. constructor( parameters ) {
  19159. super();
  19160. this.type = 'LineDashedMaterial';
  19161. this.scale = 1;
  19162. this.dashSize = 3;
  19163. this.gapSize = 1;
  19164. this.setValues( parameters );
  19165. }
  19166. copy( source ) {
  19167. super.copy( source );
  19168. this.scale = source.scale;
  19169. this.dashSize = source.dashSize;
  19170. this.gapSize = source.gapSize;
  19171. return this;
  19172. }
  19173. }
  19174. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  19175. const AnimationUtils = {
  19176. // same as Array.prototype.slice, but also works on typed arrays
  19177. arraySlice: function ( array, from, to ) {
  19178. if ( AnimationUtils.isTypedArray( array ) ) {
  19179. // in ios9 array.subarray(from, undefined) will return empty array
  19180. // but array.subarray(from) or array.subarray(from, len) is correct
  19181. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  19182. }
  19183. return array.slice( from, to );
  19184. },
  19185. // converts an array to a specific type
  19186. convertArray: function ( array, type, forceClone ) {
  19187. if ( ! array || // let 'undefined' and 'null' pass
  19188. ! forceClone && array.constructor === type ) return array;
  19189. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  19190. return new type( array ); // create typed array
  19191. }
  19192. return Array.prototype.slice.call( array ); // create Array
  19193. },
  19194. isTypedArray: function ( object ) {
  19195. return ArrayBuffer.isView( object ) &&
  19196. ! ( object instanceof DataView );
  19197. },
  19198. // returns an array by which times and values can be sorted
  19199. getKeyframeOrder: function ( times ) {
  19200. function compareTime( i, j ) {
  19201. return times[ i ] - times[ j ];
  19202. }
  19203. const n = times.length;
  19204. const result = new Array( n );
  19205. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  19206. result.sort( compareTime );
  19207. return result;
  19208. },
  19209. // uses the array previously returned by 'getKeyframeOrder' to sort data
  19210. sortedArray: function ( values, stride, order ) {
  19211. const nValues = values.length;
  19212. const result = new values.constructor( nValues );
  19213. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  19214. const srcOffset = order[ i ] * stride;
  19215. for ( let j = 0; j !== stride; ++ j ) {
  19216. result[ dstOffset ++ ] = values[ srcOffset + j ];
  19217. }
  19218. }
  19219. return result;
  19220. },
  19221. // function for parsing AOS keyframe formats
  19222. flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) {
  19223. let i = 1, key = jsonKeys[ 0 ];
  19224. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  19225. key = jsonKeys[ i ++ ];
  19226. }
  19227. if ( key === undefined ) return; // no data
  19228. let value = key[ valuePropertyName ];
  19229. if ( value === undefined ) return; // no data
  19230. if ( Array.isArray( value ) ) {
  19231. do {
  19232. value = key[ valuePropertyName ];
  19233. if ( value !== undefined ) {
  19234. times.push( key.time );
  19235. values.push.apply( values, value ); // push all elements
  19236. }
  19237. key = jsonKeys[ i ++ ];
  19238. } while ( key !== undefined );
  19239. } else if ( value.toArray !== undefined ) {
  19240. // ...assume THREE.Math-ish
  19241. do {
  19242. value = key[ valuePropertyName ];
  19243. if ( value !== undefined ) {
  19244. times.push( key.time );
  19245. value.toArray( values, values.length );
  19246. }
  19247. key = jsonKeys[ i ++ ];
  19248. } while ( key !== undefined );
  19249. } else {
  19250. // otherwise push as-is
  19251. do {
  19252. value = key[ valuePropertyName ];
  19253. if ( value !== undefined ) {
  19254. times.push( key.time );
  19255. values.push( value );
  19256. }
  19257. key = jsonKeys[ i ++ ];
  19258. } while ( key !== undefined );
  19259. }
  19260. },
  19261. subclip: function ( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  19262. const clip = sourceClip.clone();
  19263. clip.name = name;
  19264. const tracks = [];
  19265. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  19266. const track = clip.tracks[ i ];
  19267. const valueSize = track.getValueSize();
  19268. const times = [];
  19269. const values = [];
  19270. for ( let j = 0; j < track.times.length; ++ j ) {
  19271. const frame = track.times[ j ] * fps;
  19272. if ( frame < startFrame || frame >= endFrame ) continue;
  19273. times.push( track.times[ j ] );
  19274. for ( let k = 0; k < valueSize; ++ k ) {
  19275. values.push( track.values[ j * valueSize + k ] );
  19276. }
  19277. }
  19278. if ( times.length === 0 ) continue;
  19279. track.times = AnimationUtils.convertArray( times, track.times.constructor );
  19280. track.values = AnimationUtils.convertArray( values, track.values.constructor );
  19281. tracks.push( track );
  19282. }
  19283. clip.tracks = tracks;
  19284. // find minimum .times value across all tracks in the trimmed clip
  19285. let minStartTime = Infinity;
  19286. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  19287. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  19288. minStartTime = clip.tracks[ i ].times[ 0 ];
  19289. }
  19290. }
  19291. // shift all tracks such that clip begins at t=0
  19292. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  19293. clip.tracks[ i ].shift( - 1 * minStartTime );
  19294. }
  19295. clip.resetDuration();
  19296. return clip;
  19297. },
  19298. makeClipAdditive: function ( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  19299. if ( fps <= 0 ) fps = 30;
  19300. const numTracks = referenceClip.tracks.length;
  19301. const referenceTime = referenceFrame / fps;
  19302. // Make each track's values relative to the values at the reference frame
  19303. for ( let i = 0; i < numTracks; ++ i ) {
  19304. const referenceTrack = referenceClip.tracks[ i ];
  19305. const referenceTrackType = referenceTrack.ValueTypeName;
  19306. // Skip this track if it's non-numeric
  19307. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  19308. // Find the track in the target clip whose name and type matches the reference track
  19309. const targetTrack = targetClip.tracks.find( function ( track ) {
  19310. return track.name === referenceTrack.name
  19311. && track.ValueTypeName === referenceTrackType;
  19312. } );
  19313. if ( targetTrack === undefined ) continue;
  19314. let referenceOffset = 0;
  19315. const referenceValueSize = referenceTrack.getValueSize();
  19316. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  19317. referenceOffset = referenceValueSize / 3;
  19318. }
  19319. let targetOffset = 0;
  19320. const targetValueSize = targetTrack.getValueSize();
  19321. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  19322. targetOffset = targetValueSize / 3;
  19323. }
  19324. const lastIndex = referenceTrack.times.length - 1;
  19325. let referenceValue;
  19326. // Find the value to subtract out of the track
  19327. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  19328. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  19329. const startIndex = referenceOffset;
  19330. const endIndex = referenceValueSize - referenceOffset;
  19331. referenceValue = AnimationUtils.arraySlice( referenceTrack.values, startIndex, endIndex );
  19332. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  19333. // Reference frame is after the last keyframe, so just use the last keyframe
  19334. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  19335. const endIndex = startIndex + referenceValueSize - referenceOffset;
  19336. referenceValue = AnimationUtils.arraySlice( referenceTrack.values, startIndex, endIndex );
  19337. } else {
  19338. // Interpolate to the reference value
  19339. const interpolant = referenceTrack.createInterpolant();
  19340. const startIndex = referenceOffset;
  19341. const endIndex = referenceValueSize - referenceOffset;
  19342. interpolant.evaluate( referenceTime );
  19343. referenceValue = AnimationUtils.arraySlice( interpolant.resultBuffer, startIndex, endIndex );
  19344. }
  19345. // Conjugate the quaternion
  19346. if ( referenceTrackType === 'quaternion' ) {
  19347. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  19348. referenceQuat.toArray( referenceValue );
  19349. }
  19350. // Subtract the reference value from all of the track values
  19351. const numTimes = targetTrack.times.length;
  19352. for ( let j = 0; j < numTimes; ++ j ) {
  19353. const valueStart = j * targetValueSize + targetOffset;
  19354. if ( referenceTrackType === 'quaternion' ) {
  19355. // Multiply the conjugate for quaternion track types
  19356. Quaternion.multiplyQuaternionsFlat(
  19357. targetTrack.values,
  19358. valueStart,
  19359. referenceValue,
  19360. 0,
  19361. targetTrack.values,
  19362. valueStart
  19363. );
  19364. } else {
  19365. const valueEnd = targetValueSize - targetOffset * 2;
  19366. // Subtract each value for all other numeric track types
  19367. for ( let k = 0; k < valueEnd; ++ k ) {
  19368. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  19369. }
  19370. }
  19371. }
  19372. }
  19373. targetClip.blendMode = AdditiveAnimationBlendMode;
  19374. return targetClip;
  19375. }
  19376. };
  19377. /**
  19378. * Abstract base class of interpolants over parametric samples.
  19379. *
  19380. * The parameter domain is one dimensional, typically the time or a path
  19381. * along a curve defined by the data.
  19382. *
  19383. * The sample values can have any dimensionality and derived classes may
  19384. * apply special interpretations to the data.
  19385. *
  19386. * This class provides the interval seek in a Template Method, deferring
  19387. * the actual interpolation to derived classes.
  19388. *
  19389. * Time complexity is O(1) for linear access crossing at most two points
  19390. * and O(log N) for random access, where N is the number of positions.
  19391. *
  19392. * References:
  19393. *
  19394. * http://www.oodesign.com/template-method-pattern.html
  19395. *
  19396. */
  19397. class Interpolant {
  19398. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  19399. this.parameterPositions = parameterPositions;
  19400. this._cachedIndex = 0;
  19401. this.resultBuffer = resultBuffer !== undefined ?
  19402. resultBuffer : new sampleValues.constructor( sampleSize );
  19403. this.sampleValues = sampleValues;
  19404. this.valueSize = sampleSize;
  19405. this.settings = null;
  19406. this.DefaultSettings_ = {};
  19407. }
  19408. evaluate( t ) {
  19409. const pp = this.parameterPositions;
  19410. let i1 = this._cachedIndex,
  19411. t1 = pp[ i1 ],
  19412. t0 = pp[ i1 - 1 ];
  19413. validate_interval: {
  19414. seek: {
  19415. let right;
  19416. linear_scan: {
  19417. //- See http://jsperf.com/comparison-to-undefined/3
  19418. //- slower code:
  19419. //-
  19420. //- if ( t >= t1 || t1 === undefined ) {
  19421. forward_scan: if ( ! ( t < t1 ) ) {
  19422. for ( let giveUpAt = i1 + 2; ; ) {
  19423. if ( t1 === undefined ) {
  19424. if ( t < t0 ) break forward_scan;
  19425. // after end
  19426. i1 = pp.length;
  19427. this._cachedIndex = i1;
  19428. return this.afterEnd_( i1 - 1, t, t0 );
  19429. }
  19430. if ( i1 === giveUpAt ) break; // this loop
  19431. t0 = t1;
  19432. t1 = pp[ ++ i1 ];
  19433. if ( t < t1 ) {
  19434. // we have arrived at the sought interval
  19435. break seek;
  19436. }
  19437. }
  19438. // prepare binary search on the right side of the index
  19439. right = pp.length;
  19440. break linear_scan;
  19441. }
  19442. //- slower code:
  19443. //- if ( t < t0 || t0 === undefined ) {
  19444. if ( ! ( t >= t0 ) ) {
  19445. // looping?
  19446. const t1global = pp[ 1 ];
  19447. if ( t < t1global ) {
  19448. i1 = 2; // + 1, using the scan for the details
  19449. t0 = t1global;
  19450. }
  19451. // linear reverse scan
  19452. for ( let giveUpAt = i1 - 2; ; ) {
  19453. if ( t0 === undefined ) {
  19454. // before start
  19455. this._cachedIndex = 0;
  19456. return this.beforeStart_( 0, t, t1 );
  19457. }
  19458. if ( i1 === giveUpAt ) break; // this loop
  19459. t1 = t0;
  19460. t0 = pp[ -- i1 - 1 ];
  19461. if ( t >= t0 ) {
  19462. // we have arrived at the sought interval
  19463. break seek;
  19464. }
  19465. }
  19466. // prepare binary search on the left side of the index
  19467. right = i1;
  19468. i1 = 0;
  19469. break linear_scan;
  19470. }
  19471. // the interval is valid
  19472. break validate_interval;
  19473. } // linear scan
  19474. // binary search
  19475. while ( i1 < right ) {
  19476. const mid = ( i1 + right ) >>> 1;
  19477. if ( t < pp[ mid ] ) {
  19478. right = mid;
  19479. } else {
  19480. i1 = mid + 1;
  19481. }
  19482. }
  19483. t1 = pp[ i1 ];
  19484. t0 = pp[ i1 - 1 ];
  19485. // check boundary cases, again
  19486. if ( t0 === undefined ) {
  19487. this._cachedIndex = 0;
  19488. return this.beforeStart_( 0, t, t1 );
  19489. }
  19490. if ( t1 === undefined ) {
  19491. i1 = pp.length;
  19492. this._cachedIndex = i1;
  19493. return this.afterEnd_( i1 - 1, t0, t );
  19494. }
  19495. } // seek
  19496. this._cachedIndex = i1;
  19497. this.intervalChanged_( i1, t0, t1 );
  19498. } // validate_interval
  19499. return this.interpolate_( i1, t0, t, t1 );
  19500. }
  19501. getSettings_() {
  19502. return this.settings || this.DefaultSettings_;
  19503. }
  19504. copySampleValue_( index ) {
  19505. // copies a sample value to the result buffer
  19506. const result = this.resultBuffer,
  19507. values = this.sampleValues,
  19508. stride = this.valueSize,
  19509. offset = index * stride;
  19510. for ( let i = 0; i !== stride; ++ i ) {
  19511. result[ i ] = values[ offset + i ];
  19512. }
  19513. return result;
  19514. }
  19515. // Template methods for derived classes:
  19516. interpolate_( /* i1, t0, t, t1 */ ) {
  19517. throw new Error( 'call to abstract method' );
  19518. // implementations shall return this.resultBuffer
  19519. }
  19520. intervalChanged_( /* i1, t0, t1 */ ) {
  19521. // empty
  19522. }
  19523. }
  19524. // ALIAS DEFINITIONS
  19525. Interpolant.prototype.beforeStart_ = Interpolant.prototype.copySampleValue_;
  19526. Interpolant.prototype.afterEnd_ = Interpolant.prototype.copySampleValue_;
  19527. /**
  19528. * Fast and simple cubic spline interpolant.
  19529. *
  19530. * It was derived from a Hermitian construction setting the first derivative
  19531. * at each sample position to the linear slope between neighboring positions
  19532. * over their parameter interval.
  19533. */
  19534. class CubicInterpolant extends Interpolant {
  19535. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  19536. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  19537. this._weightPrev = - 0;
  19538. this._offsetPrev = - 0;
  19539. this._weightNext = - 0;
  19540. this._offsetNext = - 0;
  19541. this.DefaultSettings_ = {
  19542. endingStart: ZeroCurvatureEnding,
  19543. endingEnd: ZeroCurvatureEnding
  19544. };
  19545. }
  19546. intervalChanged_( i1, t0, t1 ) {
  19547. const pp = this.parameterPositions;
  19548. let iPrev = i1 - 2,
  19549. iNext = i1 + 1,
  19550. tPrev = pp[ iPrev ],
  19551. tNext = pp[ iNext ];
  19552. if ( tPrev === undefined ) {
  19553. switch ( this.getSettings_().endingStart ) {
  19554. case ZeroSlopeEnding:
  19555. // f'(t0) = 0
  19556. iPrev = i1;
  19557. tPrev = 2 * t0 - t1;
  19558. break;
  19559. case WrapAroundEnding:
  19560. // use the other end of the curve
  19561. iPrev = pp.length - 2;
  19562. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  19563. break;
  19564. default: // ZeroCurvatureEnding
  19565. // f''(t0) = 0 a.k.a. Natural Spline
  19566. iPrev = i1;
  19567. tPrev = t1;
  19568. }
  19569. }
  19570. if ( tNext === undefined ) {
  19571. switch ( this.getSettings_().endingEnd ) {
  19572. case ZeroSlopeEnding:
  19573. // f'(tN) = 0
  19574. iNext = i1;
  19575. tNext = 2 * t1 - t0;
  19576. break;
  19577. case WrapAroundEnding:
  19578. // use the other end of the curve
  19579. iNext = 1;
  19580. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  19581. break;
  19582. default: // ZeroCurvatureEnding
  19583. // f''(tN) = 0, a.k.a. Natural Spline
  19584. iNext = i1 - 1;
  19585. tNext = t0;
  19586. }
  19587. }
  19588. const halfDt = ( t1 - t0 ) * 0.5,
  19589. stride = this.valueSize;
  19590. this._weightPrev = halfDt / ( t0 - tPrev );
  19591. this._weightNext = halfDt / ( tNext - t1 );
  19592. this._offsetPrev = iPrev * stride;
  19593. this._offsetNext = iNext * stride;
  19594. }
  19595. interpolate_( i1, t0, t, t1 ) {
  19596. const result = this.resultBuffer,
  19597. values = this.sampleValues,
  19598. stride = this.valueSize,
  19599. o1 = i1 * stride, o0 = o1 - stride,
  19600. oP = this._offsetPrev, oN = this._offsetNext,
  19601. wP = this._weightPrev, wN = this._weightNext,
  19602. p = ( t - t0 ) / ( t1 - t0 ),
  19603. pp = p * p,
  19604. ppp = pp * p;
  19605. // evaluate polynomials
  19606. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  19607. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  19608. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  19609. const sN = wN * ppp - wN * pp;
  19610. // combine data linearly
  19611. for ( let i = 0; i !== stride; ++ i ) {
  19612. result[ i ] =
  19613. sP * values[ oP + i ] +
  19614. s0 * values[ o0 + i ] +
  19615. s1 * values[ o1 + i ] +
  19616. sN * values[ oN + i ];
  19617. }
  19618. return result;
  19619. }
  19620. }
  19621. class LinearInterpolant extends Interpolant {
  19622. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  19623. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  19624. }
  19625. interpolate_( i1, t0, t, t1 ) {
  19626. const result = this.resultBuffer,
  19627. values = this.sampleValues,
  19628. stride = this.valueSize,
  19629. offset1 = i1 * stride,
  19630. offset0 = offset1 - stride,
  19631. weight1 = ( t - t0 ) / ( t1 - t0 ),
  19632. weight0 = 1 - weight1;
  19633. for ( let i = 0; i !== stride; ++ i ) {
  19634. result[ i ] =
  19635. values[ offset0 + i ] * weight0 +
  19636. values[ offset1 + i ] * weight1;
  19637. }
  19638. return result;
  19639. }
  19640. }
  19641. /**
  19642. *
  19643. * Interpolant that evaluates to the sample value at the position preceeding
  19644. * the parameter.
  19645. */
  19646. class DiscreteInterpolant extends Interpolant {
  19647. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  19648. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  19649. }
  19650. interpolate_( i1 /*, t0, t, t1 */ ) {
  19651. return this.copySampleValue_( i1 - 1 );
  19652. }
  19653. }
  19654. class KeyframeTrack {
  19655. constructor( name, times, values, interpolation ) {
  19656. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  19657. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  19658. this.name = name;
  19659. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  19660. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  19661. this.setInterpolation( interpolation || this.DefaultInterpolation );
  19662. }
  19663. // Serialization (in static context, because of constructor invocation
  19664. // and automatic invocation of .toJSON):
  19665. static toJSON( track ) {
  19666. const trackType = track.constructor;
  19667. let json;
  19668. // derived classes can define a static toJSON method
  19669. if ( trackType.toJSON !== this.toJSON ) {
  19670. json = trackType.toJSON( track );
  19671. } else {
  19672. // by default, we assume the data can be serialized as-is
  19673. json = {
  19674. 'name': track.name,
  19675. 'times': AnimationUtils.convertArray( track.times, Array ),
  19676. 'values': AnimationUtils.convertArray( track.values, Array )
  19677. };
  19678. const interpolation = track.getInterpolation();
  19679. if ( interpolation !== track.DefaultInterpolation ) {
  19680. json.interpolation = interpolation;
  19681. }
  19682. }
  19683. json.type = track.ValueTypeName; // mandatory
  19684. return json;
  19685. }
  19686. InterpolantFactoryMethodDiscrete( result ) {
  19687. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  19688. }
  19689. InterpolantFactoryMethodLinear( result ) {
  19690. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  19691. }
  19692. InterpolantFactoryMethodSmooth( result ) {
  19693. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  19694. }
  19695. setInterpolation( interpolation ) {
  19696. let factoryMethod;
  19697. switch ( interpolation ) {
  19698. case InterpolateDiscrete:
  19699. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  19700. break;
  19701. case InterpolateLinear:
  19702. factoryMethod = this.InterpolantFactoryMethodLinear;
  19703. break;
  19704. case InterpolateSmooth:
  19705. factoryMethod = this.InterpolantFactoryMethodSmooth;
  19706. break;
  19707. }
  19708. if ( factoryMethod === undefined ) {
  19709. const message = 'unsupported interpolation for ' +
  19710. this.ValueTypeName + ' keyframe track named ' + this.name;
  19711. if ( this.createInterpolant === undefined ) {
  19712. // fall back to default, unless the default itself is messed up
  19713. if ( interpolation !== this.DefaultInterpolation ) {
  19714. this.setInterpolation( this.DefaultInterpolation );
  19715. } else {
  19716. throw new Error( message ); // fatal, in this case
  19717. }
  19718. }
  19719. console.warn( 'THREE.KeyframeTrack:', message );
  19720. return this;
  19721. }
  19722. this.createInterpolant = factoryMethod;
  19723. return this;
  19724. }
  19725. getInterpolation() {
  19726. switch ( this.createInterpolant ) {
  19727. case this.InterpolantFactoryMethodDiscrete:
  19728. return InterpolateDiscrete;
  19729. case this.InterpolantFactoryMethodLinear:
  19730. return InterpolateLinear;
  19731. case this.InterpolantFactoryMethodSmooth:
  19732. return InterpolateSmooth;
  19733. }
  19734. }
  19735. getValueSize() {
  19736. return this.values.length / this.times.length;
  19737. }
  19738. // move all keyframes either forwards or backwards in time
  19739. shift( timeOffset ) {
  19740. if ( timeOffset !== 0.0 ) {
  19741. const times = this.times;
  19742. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  19743. times[ i ] += timeOffset;
  19744. }
  19745. }
  19746. return this;
  19747. }
  19748. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  19749. scale( timeScale ) {
  19750. if ( timeScale !== 1.0 ) {
  19751. const times = this.times;
  19752. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  19753. times[ i ] *= timeScale;
  19754. }
  19755. }
  19756. return this;
  19757. }
  19758. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  19759. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  19760. trim( startTime, endTime ) {
  19761. const times = this.times,
  19762. nKeys = times.length;
  19763. let from = 0,
  19764. to = nKeys - 1;
  19765. while ( from !== nKeys && times[ from ] < startTime ) {
  19766. ++ from;
  19767. }
  19768. while ( to !== - 1 && times[ to ] > endTime ) {
  19769. -- to;
  19770. }
  19771. ++ to; // inclusive -> exclusive bound
  19772. if ( from !== 0 || to !== nKeys ) {
  19773. // empty tracks are forbidden, so keep at least one keyframe
  19774. if ( from >= to ) {
  19775. to = Math.max( to, 1 );
  19776. from = to - 1;
  19777. }
  19778. const stride = this.getValueSize();
  19779. this.times = AnimationUtils.arraySlice( times, from, to );
  19780. this.values = AnimationUtils.arraySlice( this.values, from * stride, to * stride );
  19781. }
  19782. return this;
  19783. }
  19784. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  19785. validate() {
  19786. let valid = true;
  19787. const valueSize = this.getValueSize();
  19788. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  19789. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  19790. valid = false;
  19791. }
  19792. const times = this.times,
  19793. values = this.values,
  19794. nKeys = times.length;
  19795. if ( nKeys === 0 ) {
  19796. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  19797. valid = false;
  19798. }
  19799. let prevTime = null;
  19800. for ( let i = 0; i !== nKeys; i ++ ) {
  19801. const currTime = times[ i ];
  19802. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  19803. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  19804. valid = false;
  19805. break;
  19806. }
  19807. if ( prevTime !== null && prevTime > currTime ) {
  19808. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  19809. valid = false;
  19810. break;
  19811. }
  19812. prevTime = currTime;
  19813. }
  19814. if ( values !== undefined ) {
  19815. if ( AnimationUtils.isTypedArray( values ) ) {
  19816. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  19817. const value = values[ i ];
  19818. if ( isNaN( value ) ) {
  19819. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  19820. valid = false;
  19821. break;
  19822. }
  19823. }
  19824. }
  19825. }
  19826. return valid;
  19827. }
  19828. // removes equivalent sequential keys as common in morph target sequences
  19829. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  19830. optimize() {
  19831. // times or values may be shared with other tracks, so overwriting is unsafe
  19832. const times = AnimationUtils.arraySlice( this.times ),
  19833. values = AnimationUtils.arraySlice( this.values ),
  19834. stride = this.getValueSize(),
  19835. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  19836. lastIndex = times.length - 1;
  19837. let writeIndex = 1;
  19838. for ( let i = 1; i < lastIndex; ++ i ) {
  19839. let keep = false;
  19840. const time = times[ i ];
  19841. const timeNext = times[ i + 1 ];
  19842. // remove adjacent keyframes scheduled at the same time
  19843. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  19844. if ( ! smoothInterpolation ) {
  19845. // remove unnecessary keyframes same as their neighbors
  19846. const offset = i * stride,
  19847. offsetP = offset - stride,
  19848. offsetN = offset + stride;
  19849. for ( let j = 0; j !== stride; ++ j ) {
  19850. const value = values[ offset + j ];
  19851. if ( value !== values[ offsetP + j ] ||
  19852. value !== values[ offsetN + j ] ) {
  19853. keep = true;
  19854. break;
  19855. }
  19856. }
  19857. } else {
  19858. keep = true;
  19859. }
  19860. }
  19861. // in-place compaction
  19862. if ( keep ) {
  19863. if ( i !== writeIndex ) {
  19864. times[ writeIndex ] = times[ i ];
  19865. const readOffset = i * stride,
  19866. writeOffset = writeIndex * stride;
  19867. for ( let j = 0; j !== stride; ++ j ) {
  19868. values[ writeOffset + j ] = values[ readOffset + j ];
  19869. }
  19870. }
  19871. ++ writeIndex;
  19872. }
  19873. }
  19874. // flush last keyframe (compaction looks ahead)
  19875. if ( lastIndex > 0 ) {
  19876. times[ writeIndex ] = times[ lastIndex ];
  19877. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  19878. values[ writeOffset + j ] = values[ readOffset + j ];
  19879. }
  19880. ++ writeIndex;
  19881. }
  19882. if ( writeIndex !== times.length ) {
  19883. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  19884. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  19885. } else {
  19886. this.times = times;
  19887. this.values = values;
  19888. }
  19889. return this;
  19890. }
  19891. clone() {
  19892. const times = AnimationUtils.arraySlice( this.times, 0 );
  19893. const values = AnimationUtils.arraySlice( this.values, 0 );
  19894. const TypedKeyframeTrack = this.constructor;
  19895. const track = new TypedKeyframeTrack( this.name, times, values );
  19896. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  19897. track.createInterpolant = this.createInterpolant;
  19898. return track;
  19899. }
  19900. }
  19901. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  19902. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  19903. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  19904. /**
  19905. * A Track of Boolean keyframe values.
  19906. */
  19907. class BooleanKeyframeTrack extends KeyframeTrack {}
  19908. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  19909. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  19910. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  19911. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  19912. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  19913. /**
  19914. * A Track of keyframe values that represent color.
  19915. */
  19916. class ColorKeyframeTrack extends KeyframeTrack {}
  19917. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  19918. /**
  19919. * A Track of numeric keyframe values.
  19920. */
  19921. class NumberKeyframeTrack extends KeyframeTrack {}
  19922. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  19923. /**
  19924. * Spherical linear unit quaternion interpolant.
  19925. */
  19926. class QuaternionLinearInterpolant extends Interpolant {
  19927. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  19928. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  19929. }
  19930. interpolate_( i1, t0, t, t1 ) {
  19931. const result = this.resultBuffer,
  19932. values = this.sampleValues,
  19933. stride = this.valueSize,
  19934. alpha = ( t - t0 ) / ( t1 - t0 );
  19935. let offset = i1 * stride;
  19936. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  19937. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  19938. }
  19939. return result;
  19940. }
  19941. }
  19942. /**
  19943. * A Track of quaternion keyframe values.
  19944. */
  19945. class QuaternionKeyframeTrack extends KeyframeTrack {
  19946. InterpolantFactoryMethodLinear( result ) {
  19947. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  19948. }
  19949. }
  19950. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  19951. // ValueBufferType is inherited
  19952. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  19953. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  19954. /**
  19955. * A Track that interpolates Strings
  19956. */
  19957. class StringKeyframeTrack extends KeyframeTrack {}
  19958. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  19959. StringKeyframeTrack.prototype.ValueBufferType = Array;
  19960. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  19961. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  19962. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  19963. /**
  19964. * A Track of vectored keyframe values.
  19965. */
  19966. class VectorKeyframeTrack extends KeyframeTrack {}
  19967. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  19968. class AnimationClip {
  19969. constructor( name, duration = - 1, tracks, blendMode = NormalAnimationBlendMode ) {
  19970. this.name = name;
  19971. this.tracks = tracks;
  19972. this.duration = duration;
  19973. this.blendMode = blendMode;
  19974. this.uuid = generateUUID();
  19975. // this means it should figure out its duration by scanning the tracks
  19976. if ( this.duration < 0 ) {
  19977. this.resetDuration();
  19978. }
  19979. }
  19980. static parse( json ) {
  19981. const tracks = [],
  19982. jsonTracks = json.tracks,
  19983. frameTime = 1.0 / ( json.fps || 1.0 );
  19984. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  19985. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  19986. }
  19987. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  19988. clip.uuid = json.uuid;
  19989. return clip;
  19990. }
  19991. static toJSON( clip ) {
  19992. const tracks = [],
  19993. clipTracks = clip.tracks;
  19994. const json = {
  19995. 'name': clip.name,
  19996. 'duration': clip.duration,
  19997. 'tracks': tracks,
  19998. 'uuid': clip.uuid,
  19999. 'blendMode': clip.blendMode
  20000. };
  20001. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  20002. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  20003. }
  20004. return json;
  20005. }
  20006. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  20007. const numMorphTargets = morphTargetSequence.length;
  20008. const tracks = [];
  20009. for ( let i = 0; i < numMorphTargets; i ++ ) {
  20010. let times = [];
  20011. let values = [];
  20012. times.push(
  20013. ( i + numMorphTargets - 1 ) % numMorphTargets,
  20014. i,
  20015. ( i + 1 ) % numMorphTargets );
  20016. values.push( 0, 1, 0 );
  20017. const order = AnimationUtils.getKeyframeOrder( times );
  20018. times = AnimationUtils.sortedArray( times, 1, order );
  20019. values = AnimationUtils.sortedArray( values, 1, order );
  20020. // if there is a key at the first frame, duplicate it as the
  20021. // last frame as well for perfect loop.
  20022. if ( ! noLoop && times[ 0 ] === 0 ) {
  20023. times.push( numMorphTargets );
  20024. values.push( values[ 0 ] );
  20025. }
  20026. tracks.push(
  20027. new NumberKeyframeTrack(
  20028. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  20029. times, values
  20030. ).scale( 1.0 / fps ) );
  20031. }
  20032. return new this( name, - 1, tracks );
  20033. }
  20034. static findByName( objectOrClipArray, name ) {
  20035. let clipArray = objectOrClipArray;
  20036. if ( ! Array.isArray( objectOrClipArray ) ) {
  20037. const o = objectOrClipArray;
  20038. clipArray = o.geometry && o.geometry.animations || o.animations;
  20039. }
  20040. for ( let i = 0; i < clipArray.length; i ++ ) {
  20041. if ( clipArray[ i ].name === name ) {
  20042. return clipArray[ i ];
  20043. }
  20044. }
  20045. return null;
  20046. }
  20047. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  20048. const animationToMorphTargets = {};
  20049. // tested with https://regex101.com/ on trick sequences
  20050. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  20051. const pattern = /^([\w-]*?)([\d]+)$/;
  20052. // sort morph target names into animation groups based
  20053. // patterns like Walk_001, Walk_002, Run_001, Run_002
  20054. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  20055. const morphTarget = morphTargets[ i ];
  20056. const parts = morphTarget.name.match( pattern );
  20057. if ( parts && parts.length > 1 ) {
  20058. const name = parts[ 1 ];
  20059. let animationMorphTargets = animationToMorphTargets[ name ];
  20060. if ( ! animationMorphTargets ) {
  20061. animationToMorphTargets[ name ] = animationMorphTargets = [];
  20062. }
  20063. animationMorphTargets.push( morphTarget );
  20064. }
  20065. }
  20066. const clips = [];
  20067. for ( const name in animationToMorphTargets ) {
  20068. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  20069. }
  20070. return clips;
  20071. }
  20072. // parse the animation.hierarchy format
  20073. static parseAnimation( animation, bones ) {
  20074. if ( ! animation ) {
  20075. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  20076. return null;
  20077. }
  20078. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  20079. // only return track if there are actually keys.
  20080. if ( animationKeys.length !== 0 ) {
  20081. const times = [];
  20082. const values = [];
  20083. AnimationUtils.flattenJSON( animationKeys, times, values, propertyName );
  20084. // empty keys are filtered out, so check again
  20085. if ( times.length !== 0 ) {
  20086. destTracks.push( new trackType( trackName, times, values ) );
  20087. }
  20088. }
  20089. };
  20090. const tracks = [];
  20091. const clipName = animation.name || 'default';
  20092. const fps = animation.fps || 30;
  20093. const blendMode = animation.blendMode;
  20094. // automatic length determination in AnimationClip.
  20095. let duration = animation.length || - 1;
  20096. const hierarchyTracks = animation.hierarchy || [];
  20097. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  20098. const animationKeys = hierarchyTracks[ h ].keys;
  20099. // skip empty tracks
  20100. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  20101. // process morph targets
  20102. if ( animationKeys[ 0 ].morphTargets ) {
  20103. // figure out all morph targets used in this track
  20104. const morphTargetNames = {};
  20105. let k;
  20106. for ( k = 0; k < animationKeys.length; k ++ ) {
  20107. if ( animationKeys[ k ].morphTargets ) {
  20108. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  20109. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  20110. }
  20111. }
  20112. }
  20113. // create a track for each morph target with all zero
  20114. // morphTargetInfluences except for the keys in which
  20115. // the morphTarget is named.
  20116. for ( const morphTargetName in morphTargetNames ) {
  20117. const times = [];
  20118. const values = [];
  20119. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  20120. const animationKey = animationKeys[ k ];
  20121. times.push( animationKey.time );
  20122. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  20123. }
  20124. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  20125. }
  20126. duration = morphTargetNames.length * ( fps || 1.0 );
  20127. } else {
  20128. // ...assume skeletal animation
  20129. const boneName = '.bones[' + bones[ h ].name + ']';
  20130. addNonemptyTrack(
  20131. VectorKeyframeTrack, boneName + '.position',
  20132. animationKeys, 'pos', tracks );
  20133. addNonemptyTrack(
  20134. QuaternionKeyframeTrack, boneName + '.quaternion',
  20135. animationKeys, 'rot', tracks );
  20136. addNonemptyTrack(
  20137. VectorKeyframeTrack, boneName + '.scale',
  20138. animationKeys, 'scl', tracks );
  20139. }
  20140. }
  20141. if ( tracks.length === 0 ) {
  20142. return null;
  20143. }
  20144. const clip = new this( clipName, duration, tracks, blendMode );
  20145. return clip;
  20146. }
  20147. resetDuration() {
  20148. const tracks = this.tracks;
  20149. let duration = 0;
  20150. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  20151. const track = this.tracks[ i ];
  20152. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  20153. }
  20154. this.duration = duration;
  20155. return this;
  20156. }
  20157. trim() {
  20158. for ( let i = 0; i < this.tracks.length; i ++ ) {
  20159. this.tracks[ i ].trim( 0, this.duration );
  20160. }
  20161. return this;
  20162. }
  20163. validate() {
  20164. let valid = true;
  20165. for ( let i = 0; i < this.tracks.length; i ++ ) {
  20166. valid = valid && this.tracks[ i ].validate();
  20167. }
  20168. return valid;
  20169. }
  20170. optimize() {
  20171. for ( let i = 0; i < this.tracks.length; i ++ ) {
  20172. this.tracks[ i ].optimize();
  20173. }
  20174. return this;
  20175. }
  20176. clone() {
  20177. const tracks = [];
  20178. for ( let i = 0; i < this.tracks.length; i ++ ) {
  20179. tracks.push( this.tracks[ i ].clone() );
  20180. }
  20181. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  20182. }
  20183. toJSON() {
  20184. return this.constructor.toJSON( this );
  20185. }
  20186. }
  20187. function getTrackTypeForValueTypeName( typeName ) {
  20188. switch ( typeName.toLowerCase() ) {
  20189. case 'scalar':
  20190. case 'double':
  20191. case 'float':
  20192. case 'number':
  20193. case 'integer':
  20194. return NumberKeyframeTrack;
  20195. case 'vector':
  20196. case 'vector2':
  20197. case 'vector3':
  20198. case 'vector4':
  20199. return VectorKeyframeTrack;
  20200. case 'color':
  20201. return ColorKeyframeTrack;
  20202. case 'quaternion':
  20203. return QuaternionKeyframeTrack;
  20204. case 'bool':
  20205. case 'boolean':
  20206. return BooleanKeyframeTrack;
  20207. case 'string':
  20208. return StringKeyframeTrack;
  20209. }
  20210. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  20211. }
  20212. function parseKeyframeTrack( json ) {
  20213. if ( json.type === undefined ) {
  20214. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  20215. }
  20216. const trackType = getTrackTypeForValueTypeName( json.type );
  20217. if ( json.times === undefined ) {
  20218. const times = [], values = [];
  20219. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  20220. json.times = times;
  20221. json.values = values;
  20222. }
  20223. // derived classes can define a static parse method
  20224. if ( trackType.parse !== undefined ) {
  20225. return trackType.parse( json );
  20226. } else {
  20227. // by default, we assume a constructor compatible with the base
  20228. return new trackType( json.name, json.times, json.values, json.interpolation );
  20229. }
  20230. }
  20231. const Cache = {
  20232. enabled: false,
  20233. files: {},
  20234. add: function ( key, file ) {
  20235. if ( this.enabled === false ) return;
  20236. // console.log( 'THREE.Cache', 'Adding key:', key );
  20237. this.files[ key ] = file;
  20238. },
  20239. get: function ( key ) {
  20240. if ( this.enabled === false ) return;
  20241. // console.log( 'THREE.Cache', 'Checking key:', key );
  20242. return this.files[ key ];
  20243. },
  20244. remove: function ( key ) {
  20245. delete this.files[ key ];
  20246. },
  20247. clear: function () {
  20248. this.files = {};
  20249. }
  20250. };
  20251. class LoadingManager {
  20252. constructor( onLoad, onProgress, onError ) {
  20253. const scope = this;
  20254. let isLoading = false;
  20255. let itemsLoaded = 0;
  20256. let itemsTotal = 0;
  20257. let urlModifier = undefined;
  20258. const handlers = [];
  20259. // Refer to #5689 for the reason why we don't set .onStart
  20260. // in the constructor
  20261. this.onStart = undefined;
  20262. this.onLoad = onLoad;
  20263. this.onProgress = onProgress;
  20264. this.onError = onError;
  20265. this.itemStart = function ( url ) {
  20266. itemsTotal ++;
  20267. if ( isLoading === false ) {
  20268. if ( scope.onStart !== undefined ) {
  20269. scope.onStart( url, itemsLoaded, itemsTotal );
  20270. }
  20271. }
  20272. isLoading = true;
  20273. };
  20274. this.itemEnd = function ( url ) {
  20275. itemsLoaded ++;
  20276. if ( scope.onProgress !== undefined ) {
  20277. scope.onProgress( url, itemsLoaded, itemsTotal );
  20278. }
  20279. if ( itemsLoaded === itemsTotal ) {
  20280. isLoading = false;
  20281. if ( scope.onLoad !== undefined ) {
  20282. scope.onLoad();
  20283. }
  20284. }
  20285. };
  20286. this.itemError = function ( url ) {
  20287. if ( scope.onError !== undefined ) {
  20288. scope.onError( url );
  20289. }
  20290. };
  20291. this.resolveURL = function ( url ) {
  20292. if ( urlModifier ) {
  20293. return urlModifier( url );
  20294. }
  20295. return url;
  20296. };
  20297. this.setURLModifier = function ( transform ) {
  20298. urlModifier = transform;
  20299. return this;
  20300. };
  20301. this.addHandler = function ( regex, loader ) {
  20302. handlers.push( regex, loader );
  20303. return this;
  20304. };
  20305. this.removeHandler = function ( regex ) {
  20306. const index = handlers.indexOf( regex );
  20307. if ( index !== - 1 ) {
  20308. handlers.splice( index, 2 );
  20309. }
  20310. return this;
  20311. };
  20312. this.getHandler = function ( file ) {
  20313. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  20314. const regex = handlers[ i ];
  20315. const loader = handlers[ i + 1 ];
  20316. if ( regex.global ) regex.lastIndex = 0; // see #17920
  20317. if ( regex.test( file ) ) {
  20318. return loader;
  20319. }
  20320. }
  20321. return null;
  20322. };
  20323. }
  20324. }
  20325. const DefaultLoadingManager = new LoadingManager();
  20326. class Loader {
  20327. constructor( manager ) {
  20328. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  20329. this.crossOrigin = 'anonymous';
  20330. this.withCredentials = false;
  20331. this.path = '';
  20332. this.resourcePath = '';
  20333. this.requestHeader = {};
  20334. }
  20335. load( /* url, onLoad, onProgress, onError */ ) {}
  20336. loadAsync( url, onProgress ) {
  20337. const scope = this;
  20338. return new Promise( function ( resolve, reject ) {
  20339. scope.load( url, resolve, onProgress, reject );
  20340. } );
  20341. }
  20342. parse( /* data */ ) {}
  20343. setCrossOrigin( crossOrigin ) {
  20344. this.crossOrigin = crossOrigin;
  20345. return this;
  20346. }
  20347. setWithCredentials( value ) {
  20348. this.withCredentials = value;
  20349. return this;
  20350. }
  20351. setPath( path ) {
  20352. this.path = path;
  20353. return this;
  20354. }
  20355. setResourcePath( resourcePath ) {
  20356. this.resourcePath = resourcePath;
  20357. return this;
  20358. }
  20359. setRequestHeader( requestHeader ) {
  20360. this.requestHeader = requestHeader;
  20361. return this;
  20362. }
  20363. }
  20364. const loading = {};
  20365. class FileLoader extends Loader {
  20366. constructor( manager ) {
  20367. super( manager );
  20368. }
  20369. load( url, onLoad, onProgress, onError ) {
  20370. if ( url === undefined ) url = '';
  20371. if ( this.path !== undefined ) url = this.path + url;
  20372. url = this.manager.resolveURL( url );
  20373. const scope = this;
  20374. const cached = Cache.get( url );
  20375. if ( cached !== undefined ) {
  20376. scope.manager.itemStart( url );
  20377. setTimeout( function () {
  20378. if ( onLoad ) onLoad( cached );
  20379. scope.manager.itemEnd( url );
  20380. }, 0 );
  20381. return cached;
  20382. }
  20383. // Check if request is duplicate
  20384. if ( loading[ url ] !== undefined ) {
  20385. loading[ url ].push( {
  20386. onLoad: onLoad,
  20387. onProgress: onProgress,
  20388. onError: onError
  20389. } );
  20390. return;
  20391. }
  20392. // Check for data: URI
  20393. const dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  20394. const dataUriRegexResult = url.match( dataUriRegex );
  20395. let request;
  20396. // Safari can not handle Data URIs through XMLHttpRequest so process manually
  20397. if ( dataUriRegexResult ) {
  20398. const mimeType = dataUriRegexResult[ 1 ];
  20399. const isBase64 = !! dataUriRegexResult[ 2 ];
  20400. let data = dataUriRegexResult[ 3 ];
  20401. data = decodeURIComponent( data );
  20402. if ( isBase64 ) data = atob( data );
  20403. try {
  20404. let response;
  20405. const responseType = ( this.responseType || '' ).toLowerCase();
  20406. switch ( responseType ) {
  20407. case 'arraybuffer':
  20408. case 'blob':
  20409. const view = new Uint8Array( data.length );
  20410. for ( let i = 0; i < data.length; i ++ ) {
  20411. view[ i ] = data.charCodeAt( i );
  20412. }
  20413. if ( responseType === 'blob' ) {
  20414. response = new Blob( [ view.buffer ], { type: mimeType } );
  20415. } else {
  20416. response = view.buffer;
  20417. }
  20418. break;
  20419. case 'document':
  20420. const parser = new DOMParser();
  20421. response = parser.parseFromString( data, mimeType );
  20422. break;
  20423. case 'json':
  20424. response = JSON.parse( data );
  20425. break;
  20426. default: // 'text' or other
  20427. response = data;
  20428. break;
  20429. }
  20430. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  20431. setTimeout( function () {
  20432. if ( onLoad ) onLoad( response );
  20433. scope.manager.itemEnd( url );
  20434. }, 0 );
  20435. } catch ( error ) {
  20436. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  20437. setTimeout( function () {
  20438. if ( onError ) onError( error );
  20439. scope.manager.itemError( url );
  20440. scope.manager.itemEnd( url );
  20441. }, 0 );
  20442. }
  20443. } else {
  20444. // Initialise array for duplicate requests
  20445. loading[ url ] = [];
  20446. loading[ url ].push( {
  20447. onLoad: onLoad,
  20448. onProgress: onProgress,
  20449. onError: onError
  20450. } );
  20451. request = new XMLHttpRequest();
  20452. request.open( 'GET', url, true );
  20453. request.addEventListener( 'load', function ( event ) {
  20454. const response = this.response;
  20455. const callbacks = loading[ url ];
  20456. delete loading[ url ];
  20457. if ( this.status === 200 || this.status === 0 ) {
  20458. // Some browsers return HTTP Status 0 when using non-http protocol
  20459. // e.g. 'file://' or 'data://'. Handle as success.
  20460. if ( this.status === 0 ) console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  20461. // Add to cache only on HTTP success, so that we do not cache
  20462. // error response bodies as proper responses to requests.
  20463. Cache.add( url, response );
  20464. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  20465. const callback = callbacks[ i ];
  20466. if ( callback.onLoad ) callback.onLoad( response );
  20467. }
  20468. scope.manager.itemEnd( url );
  20469. } else {
  20470. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  20471. const callback = callbacks[ i ];
  20472. if ( callback.onError ) callback.onError( event );
  20473. }
  20474. scope.manager.itemError( url );
  20475. scope.manager.itemEnd( url );
  20476. }
  20477. }, false );
  20478. request.addEventListener( 'progress', function ( event ) {
  20479. const callbacks = loading[ url ];
  20480. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  20481. const callback = callbacks[ i ];
  20482. if ( callback.onProgress ) callback.onProgress( event );
  20483. }
  20484. }, false );
  20485. request.addEventListener( 'error', function ( event ) {
  20486. const callbacks = loading[ url ];
  20487. delete loading[ url ];
  20488. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  20489. const callback = callbacks[ i ];
  20490. if ( callback.onError ) callback.onError( event );
  20491. }
  20492. scope.manager.itemError( url );
  20493. scope.manager.itemEnd( url );
  20494. }, false );
  20495. request.addEventListener( 'abort', function ( event ) {
  20496. const callbacks = loading[ url ];
  20497. delete loading[ url ];
  20498. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  20499. const callback = callbacks[ i ];
  20500. if ( callback.onError ) callback.onError( event );
  20501. }
  20502. scope.manager.itemError( url );
  20503. scope.manager.itemEnd( url );
  20504. }, false );
  20505. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  20506. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  20507. if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' );
  20508. for ( const header in this.requestHeader ) {
  20509. request.setRequestHeader( header, this.requestHeader[ header ] );
  20510. }
  20511. request.send( null );
  20512. }
  20513. scope.manager.itemStart( url );
  20514. return request;
  20515. }
  20516. setResponseType( value ) {
  20517. this.responseType = value;
  20518. return this;
  20519. }
  20520. setMimeType( value ) {
  20521. this.mimeType = value;
  20522. return this;
  20523. }
  20524. }
  20525. class ImageLoader extends Loader {
  20526. constructor( manager ) {
  20527. super( manager );
  20528. }
  20529. load( url, onLoad, onProgress, onError ) {
  20530. if ( this.path !== undefined ) url = this.path + url;
  20531. url = this.manager.resolveURL( url );
  20532. const scope = this;
  20533. const cached = Cache.get( url );
  20534. if ( cached !== undefined ) {
  20535. scope.manager.itemStart( url );
  20536. setTimeout( function () {
  20537. if ( onLoad ) onLoad( cached );
  20538. scope.manager.itemEnd( url );
  20539. }, 0 );
  20540. return cached;
  20541. }
  20542. const image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  20543. function onImageLoad() {
  20544. image.removeEventListener( 'load', onImageLoad, false );
  20545. image.removeEventListener( 'error', onImageError, false );
  20546. Cache.add( url, this );
  20547. if ( onLoad ) onLoad( this );
  20548. scope.manager.itemEnd( url );
  20549. }
  20550. function onImageError( event ) {
  20551. image.removeEventListener( 'load', onImageLoad, false );
  20552. image.removeEventListener( 'error', onImageError, false );
  20553. if ( onError ) onError( event );
  20554. scope.manager.itemError( url );
  20555. scope.manager.itemEnd( url );
  20556. }
  20557. image.addEventListener( 'load', onImageLoad, false );
  20558. image.addEventListener( 'error', onImageError, false );
  20559. if ( url.substr( 0, 5 ) !== 'data:' ) {
  20560. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  20561. }
  20562. scope.manager.itemStart( url );
  20563. image.src = url;
  20564. return image;
  20565. }
  20566. }
  20567. class CubeTextureLoader extends Loader {
  20568. constructor( manager ) {
  20569. super( manager );
  20570. }
  20571. load( urls, onLoad, onProgress, onError ) {
  20572. const texture = new CubeTexture();
  20573. const loader = new ImageLoader( this.manager );
  20574. loader.setCrossOrigin( this.crossOrigin );
  20575. loader.setPath( this.path );
  20576. let loaded = 0;
  20577. function loadTexture( i ) {
  20578. loader.load( urls[ i ], function ( image ) {
  20579. texture.images[ i ] = image;
  20580. loaded ++;
  20581. if ( loaded === 6 ) {
  20582. texture.needsUpdate = true;
  20583. if ( onLoad ) onLoad( texture );
  20584. }
  20585. }, undefined, onError );
  20586. }
  20587. for ( let i = 0; i < urls.length; ++ i ) {
  20588. loadTexture( i );
  20589. }
  20590. return texture;
  20591. }
  20592. }
  20593. class TextureLoader extends Loader {
  20594. constructor( manager ) {
  20595. super( manager );
  20596. }
  20597. load( url, onLoad, onProgress, onError ) {
  20598. const texture = new Texture();
  20599. const loader = new ImageLoader( this.manager );
  20600. loader.setCrossOrigin( this.crossOrigin );
  20601. loader.setPath( this.path );
  20602. loader.load( url, function ( image ) {
  20603. texture.image = image;
  20604. // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  20605. const isJPEG = url.search( /\.jpe?g($|\?)/i ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
  20606. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  20607. texture.needsUpdate = true;
  20608. if ( onLoad !== undefined ) {
  20609. onLoad( texture );
  20610. }
  20611. }, onProgress, onError );
  20612. return texture;
  20613. }
  20614. }
  20615. /**************************************************************
  20616. * Curved Path - a curve path is simply a array of connected
  20617. * curves, but retains the api of a curve
  20618. **************************************************************/
  20619. class CurvePath extends Curve {
  20620. constructor() {
  20621. super();
  20622. this.type = 'CurvePath';
  20623. this.curves = [];
  20624. this.autoClose = false; // Automatically closes the path
  20625. }
  20626. add( curve ) {
  20627. this.curves.push( curve );
  20628. }
  20629. closePath() {
  20630. // Add a line curve if start and end of lines are not connected
  20631. const startPoint = this.curves[ 0 ].getPoint( 0 );
  20632. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  20633. if ( ! startPoint.equals( endPoint ) ) {
  20634. this.curves.push( new LineCurve( endPoint, startPoint ) );
  20635. }
  20636. }
  20637. // To get accurate point with reference to
  20638. // entire path distance at time t,
  20639. // following has to be done:
  20640. // 1. Length of each sub path have to be known
  20641. // 2. Locate and identify type of curve
  20642. // 3. Get t for the curve
  20643. // 4. Return curve.getPointAt(t')
  20644. getPoint( t ) {
  20645. const d = t * this.getLength();
  20646. const curveLengths = this.getCurveLengths();
  20647. let i = 0;
  20648. // To think about boundaries points.
  20649. while ( i < curveLengths.length ) {
  20650. if ( curveLengths[ i ] >= d ) {
  20651. const diff = curveLengths[ i ] - d;
  20652. const curve = this.curves[ i ];
  20653. const segmentLength = curve.getLength();
  20654. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  20655. return curve.getPointAt( u );
  20656. }
  20657. i ++;
  20658. }
  20659. return null;
  20660. // loop where sum != 0, sum > d , sum+1 <d
  20661. }
  20662. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  20663. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  20664. // getPoint() depends on getLength
  20665. getLength() {
  20666. const lens = this.getCurveLengths();
  20667. return lens[ lens.length - 1 ];
  20668. }
  20669. // cacheLengths must be recalculated.
  20670. updateArcLengths() {
  20671. this.needsUpdate = true;
  20672. this.cacheLengths = null;
  20673. this.getCurveLengths();
  20674. }
  20675. // Compute lengths and cache them
  20676. // We cannot overwrite getLengths() because UtoT mapping uses it.
  20677. getCurveLengths() {
  20678. // We use cache values if curves and cache array are same length
  20679. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  20680. return this.cacheLengths;
  20681. }
  20682. // Get length of sub-curve
  20683. // Push sums into cached array
  20684. const lengths = [];
  20685. let sums = 0;
  20686. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  20687. sums += this.curves[ i ].getLength();
  20688. lengths.push( sums );
  20689. }
  20690. this.cacheLengths = lengths;
  20691. return lengths;
  20692. }
  20693. getSpacedPoints( divisions = 40 ) {
  20694. const points = [];
  20695. for ( let i = 0; i <= divisions; i ++ ) {
  20696. points.push( this.getPoint( i / divisions ) );
  20697. }
  20698. if ( this.autoClose ) {
  20699. points.push( points[ 0 ] );
  20700. }
  20701. return points;
  20702. }
  20703. getPoints( divisions = 12 ) {
  20704. const points = [];
  20705. let last;
  20706. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  20707. const curve = curves[ i ];
  20708. const resolution = ( curve && curve.isEllipseCurve ) ? divisions * 2
  20709. : ( curve && ( curve.isLineCurve || curve.isLineCurve3 ) ) ? 1
  20710. : ( curve && curve.isSplineCurve ) ? divisions * curve.points.length
  20711. : divisions;
  20712. const pts = curve.getPoints( resolution );
  20713. for ( let j = 0; j < pts.length; j ++ ) {
  20714. const point = pts[ j ];
  20715. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  20716. points.push( point );
  20717. last = point;
  20718. }
  20719. }
  20720. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  20721. points.push( points[ 0 ] );
  20722. }
  20723. return points;
  20724. }
  20725. copy( source ) {
  20726. super.copy( source );
  20727. this.curves = [];
  20728. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  20729. const curve = source.curves[ i ];
  20730. this.curves.push( curve.clone() );
  20731. }
  20732. this.autoClose = source.autoClose;
  20733. return this;
  20734. }
  20735. toJSON() {
  20736. const data = super.toJSON();
  20737. data.autoClose = this.autoClose;
  20738. data.curves = [];
  20739. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  20740. const curve = this.curves[ i ];
  20741. data.curves.push( curve.toJSON() );
  20742. }
  20743. return data;
  20744. }
  20745. fromJSON( json ) {
  20746. super.fromJSON( json );
  20747. this.autoClose = json.autoClose;
  20748. this.curves = [];
  20749. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  20750. const curve = json.curves[ i ];
  20751. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  20752. }
  20753. return this;
  20754. }
  20755. }
  20756. class Path extends CurvePath {
  20757. constructor( points ) {
  20758. super();
  20759. this.type = 'Path';
  20760. this.currentPoint = new Vector2();
  20761. if ( points ) {
  20762. this.setFromPoints( points );
  20763. }
  20764. }
  20765. setFromPoints( points ) {
  20766. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  20767. for ( let i = 1, l = points.length; i < l; i ++ ) {
  20768. this.lineTo( points[ i ].x, points[ i ].y );
  20769. }
  20770. return this;
  20771. }
  20772. moveTo( x, y ) {
  20773. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  20774. return this;
  20775. }
  20776. lineTo( x, y ) {
  20777. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  20778. this.curves.push( curve );
  20779. this.currentPoint.set( x, y );
  20780. return this;
  20781. }
  20782. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  20783. const curve = new QuadraticBezierCurve(
  20784. this.currentPoint.clone(),
  20785. new Vector2( aCPx, aCPy ),
  20786. new Vector2( aX, aY )
  20787. );
  20788. this.curves.push( curve );
  20789. this.currentPoint.set( aX, aY );
  20790. return this;
  20791. }
  20792. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  20793. const curve = new CubicBezierCurve(
  20794. this.currentPoint.clone(),
  20795. new Vector2( aCP1x, aCP1y ),
  20796. new Vector2( aCP2x, aCP2y ),
  20797. new Vector2( aX, aY )
  20798. );
  20799. this.curves.push( curve );
  20800. this.currentPoint.set( aX, aY );
  20801. return this;
  20802. }
  20803. splineThru( pts /*Array of Vector*/ ) {
  20804. const npts = [ this.currentPoint.clone() ].concat( pts );
  20805. const curve = new SplineCurve( npts );
  20806. this.curves.push( curve );
  20807. this.currentPoint.copy( pts[ pts.length - 1 ] );
  20808. return this;
  20809. }
  20810. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20811. const x0 = this.currentPoint.x;
  20812. const y0 = this.currentPoint.y;
  20813. this.absarc( aX + x0, aY + y0, aRadius,
  20814. aStartAngle, aEndAngle, aClockwise );
  20815. return this;
  20816. }
  20817. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20818. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  20819. return this;
  20820. }
  20821. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20822. const x0 = this.currentPoint.x;
  20823. const y0 = this.currentPoint.y;
  20824. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  20825. return this;
  20826. }
  20827. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20828. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  20829. if ( this.curves.length > 0 ) {
  20830. // if a previous curve is present, attempt to join
  20831. const firstPoint = curve.getPoint( 0 );
  20832. if ( ! firstPoint.equals( this.currentPoint ) ) {
  20833. this.lineTo( firstPoint.x, firstPoint.y );
  20834. }
  20835. }
  20836. this.curves.push( curve );
  20837. const lastPoint = curve.getPoint( 1 );
  20838. this.currentPoint.copy( lastPoint );
  20839. return this;
  20840. }
  20841. copy( source ) {
  20842. super.copy( source );
  20843. this.currentPoint.copy( source.currentPoint );
  20844. return this;
  20845. }
  20846. toJSON() {
  20847. const data = super.toJSON();
  20848. data.currentPoint = this.currentPoint.toArray();
  20849. return data;
  20850. }
  20851. fromJSON( json ) {
  20852. super.fromJSON( json );
  20853. this.currentPoint.fromArray( json.currentPoint );
  20854. return this;
  20855. }
  20856. }
  20857. class Shape extends Path {
  20858. constructor( points ) {
  20859. super( points );
  20860. this.uuid = generateUUID();
  20861. this.type = 'Shape';
  20862. this.holes = [];
  20863. }
  20864. getPointsHoles( divisions ) {
  20865. const holesPts = [];
  20866. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  20867. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  20868. }
  20869. return holesPts;
  20870. }
  20871. // get points of shape and holes (keypoints based on segments parameter)
  20872. extractPoints( divisions ) {
  20873. return {
  20874. shape: this.getPoints( divisions ),
  20875. holes: this.getPointsHoles( divisions )
  20876. };
  20877. }
  20878. copy( source ) {
  20879. super.copy( source );
  20880. this.holes = [];
  20881. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  20882. const hole = source.holes[ i ];
  20883. this.holes.push( hole.clone() );
  20884. }
  20885. return this;
  20886. }
  20887. toJSON() {
  20888. const data = super.toJSON();
  20889. data.uuid = this.uuid;
  20890. data.holes = [];
  20891. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  20892. const hole = this.holes[ i ];
  20893. data.holes.push( hole.toJSON() );
  20894. }
  20895. return data;
  20896. }
  20897. fromJSON( json ) {
  20898. super.fromJSON( json );
  20899. this.uuid = json.uuid;
  20900. this.holes = [];
  20901. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  20902. const hole = json.holes[ i ];
  20903. this.holes.push( new Path().fromJSON( hole ) );
  20904. }
  20905. return this;
  20906. }
  20907. }
  20908. class Light extends Object3D {
  20909. constructor( color, intensity = 1 ) {
  20910. super();
  20911. this.type = 'Light';
  20912. this.color = new Color( color );
  20913. this.intensity = intensity;
  20914. }
  20915. dispose() {
  20916. // Empty here in base class; some subclasses override.
  20917. }
  20918. copy( source ) {
  20919. super.copy( source );
  20920. this.color.copy( source.color );
  20921. this.intensity = source.intensity;
  20922. return this;
  20923. }
  20924. toJSON( meta ) {
  20925. const data = super.toJSON( meta );
  20926. data.object.color = this.color.getHex();
  20927. data.object.intensity = this.intensity;
  20928. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  20929. if ( this.distance !== undefined ) data.object.distance = this.distance;
  20930. if ( this.angle !== undefined ) data.object.angle = this.angle;
  20931. if ( this.decay !== undefined ) data.object.decay = this.decay;
  20932. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  20933. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  20934. return data;
  20935. }
  20936. }
  20937. Light.prototype.isLight = true;
  20938. class HemisphereLight extends Light {
  20939. constructor( skyColor, groundColor, intensity ) {
  20940. super( skyColor, intensity );
  20941. this.type = 'HemisphereLight';
  20942. this.position.copy( Object3D.DefaultUp );
  20943. this.updateMatrix();
  20944. this.groundColor = new Color( groundColor );
  20945. }
  20946. copy( source ) {
  20947. Light.prototype.copy.call( this, source );
  20948. this.groundColor.copy( source.groundColor );
  20949. return this;
  20950. }
  20951. }
  20952. HemisphereLight.prototype.isHemisphereLight = true;
  20953. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  20954. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  20955. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  20956. class LightShadow {
  20957. constructor( camera ) {
  20958. this.camera = camera;
  20959. this.bias = 0;
  20960. this.normalBias = 0;
  20961. this.radius = 1;
  20962. this.mapSize = new Vector2( 512, 512 );
  20963. this.map = null;
  20964. this.mapPass = null;
  20965. this.matrix = new Matrix4();
  20966. this.autoUpdate = true;
  20967. this.needsUpdate = false;
  20968. this._frustum = new Frustum();
  20969. this._frameExtents = new Vector2( 1, 1 );
  20970. this._viewportCount = 1;
  20971. this._viewports = [
  20972. new Vector4( 0, 0, 1, 1 )
  20973. ];
  20974. }
  20975. getViewportCount() {
  20976. return this._viewportCount;
  20977. }
  20978. getFrustum() {
  20979. return this._frustum;
  20980. }
  20981. updateMatrices( light ) {
  20982. const shadowCamera = this.camera;
  20983. const shadowMatrix = this.matrix;
  20984. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  20985. shadowCamera.position.copy( _lightPositionWorld$1 );
  20986. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  20987. shadowCamera.lookAt( _lookTarget$1 );
  20988. shadowCamera.updateMatrixWorld();
  20989. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  20990. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  20991. shadowMatrix.set(
  20992. 0.5, 0.0, 0.0, 0.5,
  20993. 0.0, 0.5, 0.0, 0.5,
  20994. 0.0, 0.0, 0.5, 0.5,
  20995. 0.0, 0.0, 0.0, 1.0
  20996. );
  20997. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  20998. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  20999. }
  21000. getViewport( viewportIndex ) {
  21001. return this._viewports[ viewportIndex ];
  21002. }
  21003. getFrameExtents() {
  21004. return this._frameExtents;
  21005. }
  21006. dispose() {
  21007. if ( this.map ) {
  21008. this.map.dispose();
  21009. }
  21010. if ( this.mapPass ) {
  21011. this.mapPass.dispose();
  21012. }
  21013. }
  21014. copy( source ) {
  21015. this.camera = source.camera.clone();
  21016. this.bias = source.bias;
  21017. this.radius = source.radius;
  21018. this.mapSize.copy( source.mapSize );
  21019. return this;
  21020. }
  21021. clone() {
  21022. return new this.constructor().copy( this );
  21023. }
  21024. toJSON() {
  21025. const object = {};
  21026. if ( this.bias !== 0 ) object.bias = this.bias;
  21027. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  21028. if ( this.radius !== 1 ) object.radius = this.radius;
  21029. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  21030. object.camera = this.camera.toJSON( false ).object;
  21031. delete object.camera.matrix;
  21032. return object;
  21033. }
  21034. }
  21035. class SpotLightShadow extends LightShadow {
  21036. constructor() {
  21037. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  21038. this.focus = 1;
  21039. }
  21040. updateMatrices( light ) {
  21041. const camera = this.camera;
  21042. const fov = RAD2DEG * 2 * light.angle * this.focus;
  21043. const aspect = this.mapSize.width / this.mapSize.height;
  21044. const far = light.distance || camera.far;
  21045. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  21046. camera.fov = fov;
  21047. camera.aspect = aspect;
  21048. camera.far = far;
  21049. camera.updateProjectionMatrix();
  21050. }
  21051. super.updateMatrices( light );
  21052. }
  21053. copy( source ) {
  21054. super.copy( source );
  21055. this.focus = source.focus;
  21056. return this;
  21057. }
  21058. }
  21059. SpotLightShadow.prototype.isSpotLightShadow = true;
  21060. class SpotLight extends Light {
  21061. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 1 ) {
  21062. super( color, intensity );
  21063. this.type = 'SpotLight';
  21064. this.position.copy( Object3D.DefaultUp );
  21065. this.updateMatrix();
  21066. this.target = new Object3D();
  21067. this.distance = distance;
  21068. this.angle = angle;
  21069. this.penumbra = penumbra;
  21070. this.decay = decay; // for physically correct lights, should be 2.
  21071. this.shadow = new SpotLightShadow();
  21072. }
  21073. get power() {
  21074. // intensity = power per solid angle.
  21075. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  21076. return this.intensity * Math.PI;
  21077. }
  21078. set power( power ) {
  21079. // intensity = power per solid angle.
  21080. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  21081. this.intensity = power / Math.PI;
  21082. }
  21083. dispose() {
  21084. this.shadow.dispose();
  21085. }
  21086. copy( source ) {
  21087. super.copy( source );
  21088. this.distance = source.distance;
  21089. this.angle = source.angle;
  21090. this.penumbra = source.penumbra;
  21091. this.decay = source.decay;
  21092. this.target = source.target.clone();
  21093. this.shadow = source.shadow.clone();
  21094. return this;
  21095. }
  21096. }
  21097. SpotLight.prototype.isSpotLight = true;
  21098. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  21099. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  21100. const _lookTarget = /*@__PURE__*/ new Vector3();
  21101. class PointLightShadow extends LightShadow {
  21102. constructor() {
  21103. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  21104. this._frameExtents = new Vector2( 4, 2 );
  21105. this._viewportCount = 6;
  21106. this._viewports = [
  21107. // These viewports map a cube-map onto a 2D texture with the
  21108. // following orientation:
  21109. //
  21110. // xzXZ
  21111. // y Y
  21112. //
  21113. // X - Positive x direction
  21114. // x - Negative x direction
  21115. // Y - Positive y direction
  21116. // y - Negative y direction
  21117. // Z - Positive z direction
  21118. // z - Negative z direction
  21119. // positive X
  21120. new Vector4( 2, 1, 1, 1 ),
  21121. // negative X
  21122. new Vector4( 0, 1, 1, 1 ),
  21123. // positive Z
  21124. new Vector4( 3, 1, 1, 1 ),
  21125. // negative Z
  21126. new Vector4( 1, 1, 1, 1 ),
  21127. // positive Y
  21128. new Vector4( 3, 0, 1, 1 ),
  21129. // negative Y
  21130. new Vector4( 1, 0, 1, 1 )
  21131. ];
  21132. this._cubeDirections = [
  21133. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  21134. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  21135. ];
  21136. this._cubeUps = [
  21137. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  21138. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  21139. ];
  21140. }
  21141. updateMatrices( light, viewportIndex = 0 ) {
  21142. const camera = this.camera;
  21143. const shadowMatrix = this.matrix;
  21144. const far = light.distance || camera.far;
  21145. if ( far !== camera.far ) {
  21146. camera.far = far;
  21147. camera.updateProjectionMatrix();
  21148. }
  21149. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  21150. camera.position.copy( _lightPositionWorld );
  21151. _lookTarget.copy( camera.position );
  21152. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  21153. camera.up.copy( this._cubeUps[ viewportIndex ] );
  21154. camera.lookAt( _lookTarget );
  21155. camera.updateMatrixWorld();
  21156. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  21157. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  21158. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  21159. }
  21160. }
  21161. PointLightShadow.prototype.isPointLightShadow = true;
  21162. class PointLight extends Light {
  21163. constructor( color, intensity, distance = 0, decay = 1 ) {
  21164. super( color, intensity );
  21165. this.type = 'PointLight';
  21166. this.distance = distance;
  21167. this.decay = decay; // for physically correct lights, should be 2.
  21168. this.shadow = new PointLightShadow();
  21169. }
  21170. get power() {
  21171. // intensity = power per solid angle.
  21172. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  21173. return this.intensity * 4 * Math.PI;
  21174. }
  21175. set power( power ) {
  21176. // intensity = power per solid angle.
  21177. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  21178. this.intensity = power / ( 4 * Math.PI );
  21179. }
  21180. dispose() {
  21181. this.shadow.dispose();
  21182. }
  21183. copy( source ) {
  21184. super.copy( source );
  21185. this.distance = source.distance;
  21186. this.decay = source.decay;
  21187. this.shadow = source.shadow.clone();
  21188. return this;
  21189. }
  21190. }
  21191. PointLight.prototype.isPointLight = true;
  21192. class OrthographicCamera extends Camera {
  21193. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  21194. super();
  21195. this.type = 'OrthographicCamera';
  21196. this.zoom = 1;
  21197. this.view = null;
  21198. this.left = left;
  21199. this.right = right;
  21200. this.top = top;
  21201. this.bottom = bottom;
  21202. this.near = near;
  21203. this.far = far;
  21204. this.updateProjectionMatrix();
  21205. }
  21206. copy( source, recursive ) {
  21207. super.copy( source, recursive );
  21208. this.left = source.left;
  21209. this.right = source.right;
  21210. this.top = source.top;
  21211. this.bottom = source.bottom;
  21212. this.near = source.near;
  21213. this.far = source.far;
  21214. this.zoom = source.zoom;
  21215. this.view = source.view === null ? null : Object.assign( {}, source.view );
  21216. return this;
  21217. }
  21218. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  21219. if ( this.view === null ) {
  21220. this.view = {
  21221. enabled: true,
  21222. fullWidth: 1,
  21223. fullHeight: 1,
  21224. offsetX: 0,
  21225. offsetY: 0,
  21226. width: 1,
  21227. height: 1
  21228. };
  21229. }
  21230. this.view.enabled = true;
  21231. this.view.fullWidth = fullWidth;
  21232. this.view.fullHeight = fullHeight;
  21233. this.view.offsetX = x;
  21234. this.view.offsetY = y;
  21235. this.view.width = width;
  21236. this.view.height = height;
  21237. this.updateProjectionMatrix();
  21238. }
  21239. clearViewOffset() {
  21240. if ( this.view !== null ) {
  21241. this.view.enabled = false;
  21242. }
  21243. this.updateProjectionMatrix();
  21244. }
  21245. updateProjectionMatrix() {
  21246. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  21247. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  21248. const cx = ( this.right + this.left ) / 2;
  21249. const cy = ( this.top + this.bottom ) / 2;
  21250. let left = cx - dx;
  21251. let right = cx + dx;
  21252. let top = cy + dy;
  21253. let bottom = cy - dy;
  21254. if ( this.view !== null && this.view.enabled ) {
  21255. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  21256. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  21257. left += scaleW * this.view.offsetX;
  21258. right = left + scaleW * this.view.width;
  21259. top -= scaleH * this.view.offsetY;
  21260. bottom = top - scaleH * this.view.height;
  21261. }
  21262. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  21263. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  21264. }
  21265. toJSON( meta ) {
  21266. const data = super.toJSON( meta );
  21267. data.object.zoom = this.zoom;
  21268. data.object.left = this.left;
  21269. data.object.right = this.right;
  21270. data.object.top = this.top;
  21271. data.object.bottom = this.bottom;
  21272. data.object.near = this.near;
  21273. data.object.far = this.far;
  21274. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  21275. return data;
  21276. }
  21277. }
  21278. OrthographicCamera.prototype.isOrthographicCamera = true;
  21279. class DirectionalLightShadow extends LightShadow {
  21280. constructor() {
  21281. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  21282. }
  21283. }
  21284. DirectionalLightShadow.prototype.isDirectionalLightShadow = true;
  21285. class DirectionalLight extends Light {
  21286. constructor( color, intensity ) {
  21287. super( color, intensity );
  21288. this.type = 'DirectionalLight';
  21289. this.position.copy( Object3D.DefaultUp );
  21290. this.updateMatrix();
  21291. this.target = new Object3D();
  21292. this.shadow = new DirectionalLightShadow();
  21293. }
  21294. dispose() {
  21295. this.shadow.dispose();
  21296. }
  21297. copy( source ) {
  21298. super.copy( source );
  21299. this.target = source.target.clone();
  21300. this.shadow = source.shadow.clone();
  21301. return this;
  21302. }
  21303. }
  21304. DirectionalLight.prototype.isDirectionalLight = true;
  21305. class AmbientLight extends Light {
  21306. constructor( color, intensity ) {
  21307. super( color, intensity );
  21308. this.type = 'AmbientLight';
  21309. }
  21310. }
  21311. AmbientLight.prototype.isAmbientLight = true;
  21312. class RectAreaLight extends Light {
  21313. constructor( color, intensity, width = 10, height = 10 ) {
  21314. super( color, intensity );
  21315. this.type = 'RectAreaLight';
  21316. this.width = width;
  21317. this.height = height;
  21318. }
  21319. copy( source ) {
  21320. super.copy( source );
  21321. this.width = source.width;
  21322. this.height = source.height;
  21323. return this;
  21324. }
  21325. toJSON( meta ) {
  21326. const data = super.toJSON( meta );
  21327. data.object.width = this.width;
  21328. data.object.height = this.height;
  21329. return data;
  21330. }
  21331. }
  21332. RectAreaLight.prototype.isRectAreaLight = true;
  21333. /**
  21334. * Primary reference:
  21335. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  21336. *
  21337. * Secondary reference:
  21338. * https://www.ppsloan.org/publications/StupidSH36.pdf
  21339. */
  21340. // 3-band SH defined by 9 coefficients
  21341. class SphericalHarmonics3 {
  21342. constructor() {
  21343. this.coefficients = [];
  21344. for ( let i = 0; i < 9; i ++ ) {
  21345. this.coefficients.push( new Vector3() );
  21346. }
  21347. }
  21348. set( coefficients ) {
  21349. for ( let i = 0; i < 9; i ++ ) {
  21350. this.coefficients[ i ].copy( coefficients[ i ] );
  21351. }
  21352. return this;
  21353. }
  21354. zero() {
  21355. for ( let i = 0; i < 9; i ++ ) {
  21356. this.coefficients[ i ].set( 0, 0, 0 );
  21357. }
  21358. return this;
  21359. }
  21360. // get the radiance in the direction of the normal
  21361. // target is a Vector3
  21362. getAt( normal, target ) {
  21363. // normal is assumed to be unit length
  21364. const x = normal.x, y = normal.y, z = normal.z;
  21365. const coeff = this.coefficients;
  21366. // band 0
  21367. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  21368. // band 1
  21369. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  21370. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  21371. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  21372. // band 2
  21373. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  21374. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  21375. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  21376. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  21377. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  21378. return target;
  21379. }
  21380. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  21381. // target is a Vector3
  21382. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  21383. getIrradianceAt( normal, target ) {
  21384. // normal is assumed to be unit length
  21385. const x = normal.x, y = normal.y, z = normal.z;
  21386. const coeff = this.coefficients;
  21387. // band 0
  21388. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  21389. // band 1
  21390. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  21391. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  21392. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  21393. // band 2
  21394. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  21395. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  21396. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  21397. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  21398. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  21399. return target;
  21400. }
  21401. add( sh ) {
  21402. for ( let i = 0; i < 9; i ++ ) {
  21403. this.coefficients[ i ].add( sh.coefficients[ i ] );
  21404. }
  21405. return this;
  21406. }
  21407. addScaledSH( sh, s ) {
  21408. for ( let i = 0; i < 9; i ++ ) {
  21409. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  21410. }
  21411. return this;
  21412. }
  21413. scale( s ) {
  21414. for ( let i = 0; i < 9; i ++ ) {
  21415. this.coefficients[ i ].multiplyScalar( s );
  21416. }
  21417. return this;
  21418. }
  21419. lerp( sh, alpha ) {
  21420. for ( let i = 0; i < 9; i ++ ) {
  21421. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  21422. }
  21423. return this;
  21424. }
  21425. equals( sh ) {
  21426. for ( let i = 0; i < 9; i ++ ) {
  21427. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  21428. return false;
  21429. }
  21430. }
  21431. return true;
  21432. }
  21433. copy( sh ) {
  21434. return this.set( sh.coefficients );
  21435. }
  21436. clone() {
  21437. return new this.constructor().copy( this );
  21438. }
  21439. fromArray( array, offset = 0 ) {
  21440. const coefficients = this.coefficients;
  21441. for ( let i = 0; i < 9; i ++ ) {
  21442. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  21443. }
  21444. return this;
  21445. }
  21446. toArray( array = [], offset = 0 ) {
  21447. const coefficients = this.coefficients;
  21448. for ( let i = 0; i < 9; i ++ ) {
  21449. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  21450. }
  21451. return array;
  21452. }
  21453. // evaluate the basis functions
  21454. // shBasis is an Array[ 9 ]
  21455. static getBasisAt( normal, shBasis ) {
  21456. // normal is assumed to be unit length
  21457. const x = normal.x, y = normal.y, z = normal.z;
  21458. // band 0
  21459. shBasis[ 0 ] = 0.282095;
  21460. // band 1
  21461. shBasis[ 1 ] = 0.488603 * y;
  21462. shBasis[ 2 ] = 0.488603 * z;
  21463. shBasis[ 3 ] = 0.488603 * x;
  21464. // band 2
  21465. shBasis[ 4 ] = 1.092548 * x * y;
  21466. shBasis[ 5 ] = 1.092548 * y * z;
  21467. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  21468. shBasis[ 7 ] = 1.092548 * x * z;
  21469. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  21470. }
  21471. }
  21472. SphericalHarmonics3.prototype.isSphericalHarmonics3 = true;
  21473. class LightProbe extends Light {
  21474. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  21475. super( undefined, intensity );
  21476. this.sh = sh;
  21477. }
  21478. copy( source ) {
  21479. super.copy( source );
  21480. this.sh.copy( source.sh );
  21481. return this;
  21482. }
  21483. fromJSON( json ) {
  21484. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  21485. this.sh.fromArray( json.sh );
  21486. return this;
  21487. }
  21488. toJSON( meta ) {
  21489. const data = super.toJSON( meta );
  21490. data.object.sh = this.sh.toArray();
  21491. return data;
  21492. }
  21493. }
  21494. LightProbe.prototype.isLightProbe = true;
  21495. class LoaderUtils {
  21496. static decodeText( array ) {
  21497. if ( typeof TextDecoder !== 'undefined' ) {
  21498. return new TextDecoder().decode( array );
  21499. }
  21500. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  21501. // throws a "maximum call stack size exceeded" error for large arrays.
  21502. let s = '';
  21503. for ( let i = 0, il = array.length; i < il; i ++ ) {
  21504. // Implicitly assumes little-endian.
  21505. s += String.fromCharCode( array[ i ] );
  21506. }
  21507. try {
  21508. // merges multi-byte utf-8 characters.
  21509. return decodeURIComponent( escape( s ) );
  21510. } catch ( e ) { // see #16358
  21511. return s;
  21512. }
  21513. }
  21514. static extractUrlBase( url ) {
  21515. const index = url.lastIndexOf( '/' );
  21516. if ( index === - 1 ) return './';
  21517. return url.substr( 0, index + 1 );
  21518. }
  21519. }
  21520. class InstancedBufferGeometry extends BufferGeometry {
  21521. constructor() {
  21522. super();
  21523. this.type = 'InstancedBufferGeometry';
  21524. this.instanceCount = Infinity;
  21525. }
  21526. copy( source ) {
  21527. super.copy( source );
  21528. this.instanceCount = source.instanceCount;
  21529. return this;
  21530. }
  21531. clone() {
  21532. return new this.constructor().copy( this );
  21533. }
  21534. toJSON() {
  21535. const data = super.toJSON( this );
  21536. data.instanceCount = this.instanceCount;
  21537. data.isInstancedBufferGeometry = true;
  21538. return data;
  21539. }
  21540. }
  21541. InstancedBufferGeometry.prototype.isInstancedBufferGeometry = true;
  21542. class InstancedBufferAttribute extends BufferAttribute {
  21543. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  21544. if ( typeof normalized === 'number' ) {
  21545. meshPerAttribute = normalized;
  21546. normalized = false;
  21547. console.error( 'THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.' );
  21548. }
  21549. super( array, itemSize, normalized );
  21550. this.meshPerAttribute = meshPerAttribute;
  21551. }
  21552. copy( source ) {
  21553. super.copy( source );
  21554. this.meshPerAttribute = source.meshPerAttribute;
  21555. return this;
  21556. }
  21557. toJSON() {
  21558. const data = super.toJSON();
  21559. data.meshPerAttribute = this.meshPerAttribute;
  21560. data.isInstancedBufferAttribute = true;
  21561. return data;
  21562. }
  21563. }
  21564. InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true;
  21565. class ImageBitmapLoader extends Loader {
  21566. constructor( manager ) {
  21567. super( manager );
  21568. if ( typeof createImageBitmap === 'undefined' ) {
  21569. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  21570. }
  21571. if ( typeof fetch === 'undefined' ) {
  21572. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  21573. }
  21574. this.options = { premultiplyAlpha: 'none' };
  21575. }
  21576. setOptions( options ) {
  21577. this.options = options;
  21578. return this;
  21579. }
  21580. load( url, onLoad, onProgress, onError ) {
  21581. if ( url === undefined ) url = '';
  21582. if ( this.path !== undefined ) url = this.path + url;
  21583. url = this.manager.resolveURL( url );
  21584. const scope = this;
  21585. const cached = Cache.get( url );
  21586. if ( cached !== undefined ) {
  21587. scope.manager.itemStart( url );
  21588. setTimeout( function () {
  21589. if ( onLoad ) onLoad( cached );
  21590. scope.manager.itemEnd( url );
  21591. }, 0 );
  21592. return cached;
  21593. }
  21594. const fetchOptions = {};
  21595. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  21596. fetchOptions.headers = this.requestHeader;
  21597. fetch( url, fetchOptions ).then( function ( res ) {
  21598. return res.blob();
  21599. } ).then( function ( blob ) {
  21600. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  21601. } ).then( function ( imageBitmap ) {
  21602. Cache.add( url, imageBitmap );
  21603. if ( onLoad ) onLoad( imageBitmap );
  21604. scope.manager.itemEnd( url );
  21605. } ).catch( function ( e ) {
  21606. if ( onError ) onError( e );
  21607. scope.manager.itemError( url );
  21608. scope.manager.itemEnd( url );
  21609. } );
  21610. scope.manager.itemStart( url );
  21611. }
  21612. }
  21613. ImageBitmapLoader.prototype.isImageBitmapLoader = true;
  21614. let _context;
  21615. const AudioContext = {
  21616. getContext: function () {
  21617. if ( _context === undefined ) {
  21618. _context = new ( window.AudioContext || window.webkitAudioContext )();
  21619. }
  21620. return _context;
  21621. },
  21622. setContext: function ( value ) {
  21623. _context = value;
  21624. }
  21625. };
  21626. class AudioLoader extends Loader {
  21627. constructor( manager ) {
  21628. super( manager );
  21629. }
  21630. load( url, onLoad, onProgress, onError ) {
  21631. const scope = this;
  21632. const loader = new FileLoader( this.manager );
  21633. loader.setResponseType( 'arraybuffer' );
  21634. loader.setPath( this.path );
  21635. loader.setRequestHeader( this.requestHeader );
  21636. loader.setWithCredentials( this.withCredentials );
  21637. loader.load( url, function ( buffer ) {
  21638. try {
  21639. // Create a copy of the buffer. The `decodeAudioData` method
  21640. // detaches the buffer when complete, preventing reuse.
  21641. const bufferCopy = buffer.slice( 0 );
  21642. const context = AudioContext.getContext();
  21643. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  21644. onLoad( audioBuffer );
  21645. } );
  21646. } catch ( e ) {
  21647. if ( onError ) {
  21648. onError( e );
  21649. } else {
  21650. console.error( e );
  21651. }
  21652. scope.manager.itemError( url );
  21653. }
  21654. }, onProgress, onError );
  21655. }
  21656. }
  21657. class HemisphereLightProbe extends LightProbe {
  21658. constructor( skyColor, groundColor, intensity = 1 ) {
  21659. super( undefined, intensity );
  21660. const color1 = new Color().set( skyColor );
  21661. const color2 = new Color().set( groundColor );
  21662. const sky = new Vector3( color1.r, color1.g, color1.b );
  21663. const ground = new Vector3( color2.r, color2.g, color2.b );
  21664. // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  21665. const c0 = Math.sqrt( Math.PI );
  21666. const c1 = c0 * Math.sqrt( 0.75 );
  21667. this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 );
  21668. this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 );
  21669. }
  21670. }
  21671. HemisphereLightProbe.prototype.isHemisphereLightProbe = true;
  21672. class AmbientLightProbe extends LightProbe {
  21673. constructor( color, intensity = 1 ) {
  21674. super( undefined, intensity );
  21675. const color1 = new Color().set( color );
  21676. // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  21677. this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) );
  21678. }
  21679. }
  21680. AmbientLightProbe.prototype.isAmbientLightProbe = true;
  21681. class Clock {
  21682. constructor( autoStart = true ) {
  21683. this.autoStart = autoStart;
  21684. this.startTime = 0;
  21685. this.oldTime = 0;
  21686. this.elapsedTime = 0;
  21687. this.running = false;
  21688. }
  21689. start() {
  21690. this.startTime = now$3();
  21691. this.oldTime = this.startTime;
  21692. this.elapsedTime = 0;
  21693. this.running = true;
  21694. }
  21695. stop() {
  21696. this.getElapsedTime();
  21697. this.running = false;
  21698. this.autoStart = false;
  21699. }
  21700. getElapsedTime() {
  21701. this.getDelta();
  21702. return this.elapsedTime;
  21703. }
  21704. getDelta() {
  21705. let diff = 0;
  21706. if ( this.autoStart && ! this.running ) {
  21707. this.start();
  21708. return 0;
  21709. }
  21710. if ( this.running ) {
  21711. const newTime = now$3();
  21712. diff = ( newTime - this.oldTime ) / 1000;
  21713. this.oldTime = newTime;
  21714. this.elapsedTime += diff;
  21715. }
  21716. return diff;
  21717. }
  21718. }
  21719. function now$3() {
  21720. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  21721. }
  21722. class Audio extends Object3D {
  21723. constructor( listener ) {
  21724. super();
  21725. this.type = 'Audio';
  21726. this.listener = listener;
  21727. this.context = listener.context;
  21728. this.gain = this.context.createGain();
  21729. this.gain.connect( listener.getInput() );
  21730. this.autoplay = false;
  21731. this.buffer = null;
  21732. this.detune = 0;
  21733. this.loop = false;
  21734. this.loopStart = 0;
  21735. this.loopEnd = 0;
  21736. this.offset = 0;
  21737. this.duration = undefined;
  21738. this.playbackRate = 1;
  21739. this.isPlaying = false;
  21740. this.hasPlaybackControl = true;
  21741. this.source = null;
  21742. this.sourceType = 'empty';
  21743. this._startedAt = 0;
  21744. this._progress = 0;
  21745. this._connected = false;
  21746. this.filters = [];
  21747. }
  21748. getOutput() {
  21749. return this.gain;
  21750. }
  21751. setNodeSource( audioNode ) {
  21752. this.hasPlaybackControl = false;
  21753. this.sourceType = 'audioNode';
  21754. this.source = audioNode;
  21755. this.connect();
  21756. return this;
  21757. }
  21758. setMediaElementSource( mediaElement ) {
  21759. this.hasPlaybackControl = false;
  21760. this.sourceType = 'mediaNode';
  21761. this.source = this.context.createMediaElementSource( mediaElement );
  21762. this.connect();
  21763. return this;
  21764. }
  21765. setMediaStreamSource( mediaStream ) {
  21766. this.hasPlaybackControl = false;
  21767. this.sourceType = 'mediaStreamNode';
  21768. this.source = this.context.createMediaStreamSource( mediaStream );
  21769. this.connect();
  21770. return this;
  21771. }
  21772. setBuffer( audioBuffer ) {
  21773. this.buffer = audioBuffer;
  21774. this.sourceType = 'buffer';
  21775. if ( this.autoplay ) this.play();
  21776. return this;
  21777. }
  21778. play( delay = 0 ) {
  21779. if ( this.isPlaying === true ) {
  21780. console.warn( 'THREE.Audio: Audio is already playing.' );
  21781. return;
  21782. }
  21783. if ( this.hasPlaybackControl === false ) {
  21784. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21785. return;
  21786. }
  21787. this._startedAt = this.context.currentTime + delay;
  21788. const source = this.context.createBufferSource();
  21789. source.buffer = this.buffer;
  21790. source.loop = this.loop;
  21791. source.loopStart = this.loopStart;
  21792. source.loopEnd = this.loopEnd;
  21793. source.onended = this.onEnded.bind( this );
  21794. source.start( this._startedAt, this._progress + this.offset, this.duration );
  21795. this.isPlaying = true;
  21796. this.source = source;
  21797. this.setDetune( this.detune );
  21798. this.setPlaybackRate( this.playbackRate );
  21799. return this.connect();
  21800. }
  21801. pause() {
  21802. if ( this.hasPlaybackControl === false ) {
  21803. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21804. return;
  21805. }
  21806. if ( this.isPlaying === true ) {
  21807. // update current progress
  21808. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  21809. if ( this.loop === true ) {
  21810. // ensure _progress does not exceed duration with looped audios
  21811. this._progress = this._progress % ( this.duration || this.buffer.duration );
  21812. }
  21813. this.source.stop();
  21814. this.source.onended = null;
  21815. this.isPlaying = false;
  21816. }
  21817. return this;
  21818. }
  21819. stop() {
  21820. if ( this.hasPlaybackControl === false ) {
  21821. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21822. return;
  21823. }
  21824. this._progress = 0;
  21825. this.source.stop();
  21826. this.source.onended = null;
  21827. this.isPlaying = false;
  21828. return this;
  21829. }
  21830. connect() {
  21831. if ( this.filters.length > 0 ) {
  21832. this.source.connect( this.filters[ 0 ] );
  21833. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  21834. this.filters[ i - 1 ].connect( this.filters[ i ] );
  21835. }
  21836. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  21837. } else {
  21838. this.source.connect( this.getOutput() );
  21839. }
  21840. this._connected = true;
  21841. return this;
  21842. }
  21843. disconnect() {
  21844. if ( this.filters.length > 0 ) {
  21845. this.source.disconnect( this.filters[ 0 ] );
  21846. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  21847. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  21848. }
  21849. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  21850. } else {
  21851. this.source.disconnect( this.getOutput() );
  21852. }
  21853. this._connected = false;
  21854. return this;
  21855. }
  21856. getFilters() {
  21857. return this.filters;
  21858. }
  21859. setFilters( value ) {
  21860. if ( ! value ) value = [];
  21861. if ( this._connected === true ) {
  21862. this.disconnect();
  21863. this.filters = value.slice();
  21864. this.connect();
  21865. } else {
  21866. this.filters = value.slice();
  21867. }
  21868. return this;
  21869. }
  21870. setDetune( value ) {
  21871. this.detune = value;
  21872. if ( this.source.detune === undefined ) return; // only set detune when available
  21873. if ( this.isPlaying === true ) {
  21874. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  21875. }
  21876. return this;
  21877. }
  21878. getDetune() {
  21879. return this.detune;
  21880. }
  21881. getFilter() {
  21882. return this.getFilters()[ 0 ];
  21883. }
  21884. setFilter( filter ) {
  21885. return this.setFilters( filter ? [ filter ] : [] );
  21886. }
  21887. setPlaybackRate( value ) {
  21888. if ( this.hasPlaybackControl === false ) {
  21889. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21890. return;
  21891. }
  21892. this.playbackRate = value;
  21893. if ( this.isPlaying === true ) {
  21894. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  21895. }
  21896. return this;
  21897. }
  21898. getPlaybackRate() {
  21899. return this.playbackRate;
  21900. }
  21901. onEnded() {
  21902. this.isPlaying = false;
  21903. }
  21904. getLoop() {
  21905. if ( this.hasPlaybackControl === false ) {
  21906. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21907. return false;
  21908. }
  21909. return this.loop;
  21910. }
  21911. setLoop( value ) {
  21912. if ( this.hasPlaybackControl === false ) {
  21913. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  21914. return;
  21915. }
  21916. this.loop = value;
  21917. if ( this.isPlaying === true ) {
  21918. this.source.loop = this.loop;
  21919. }
  21920. return this;
  21921. }
  21922. setLoopStart( value ) {
  21923. this.loopStart = value;
  21924. return this;
  21925. }
  21926. setLoopEnd( value ) {
  21927. this.loopEnd = value;
  21928. return this;
  21929. }
  21930. getVolume() {
  21931. return this.gain.gain.value;
  21932. }
  21933. setVolume( value ) {
  21934. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  21935. return this;
  21936. }
  21937. }
  21938. class PropertyMixer {
  21939. constructor( binding, typeName, valueSize ) {
  21940. this.binding = binding;
  21941. this.valueSize = valueSize;
  21942. let mixFunction,
  21943. mixFunctionAdditive,
  21944. setIdentity;
  21945. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  21946. //
  21947. // interpolators can use .buffer as their .result
  21948. // the data then goes to 'incoming'
  21949. //
  21950. // 'accu0' and 'accu1' are used frame-interleaved for
  21951. // the cumulative result and are compared to detect
  21952. // changes
  21953. //
  21954. // 'orig' stores the original state of the property
  21955. //
  21956. // 'add' is used for additive cumulative results
  21957. //
  21958. // 'work' is optional and is only present for quaternion types. It is used
  21959. // to store intermediate quaternion multiplication results
  21960. switch ( typeName ) {
  21961. case 'quaternion':
  21962. mixFunction = this._slerp;
  21963. mixFunctionAdditive = this._slerpAdditive;
  21964. setIdentity = this._setAdditiveIdentityQuaternion;
  21965. this.buffer = new Float64Array( valueSize * 6 );
  21966. this._workIndex = 5;
  21967. break;
  21968. case 'string':
  21969. case 'bool':
  21970. mixFunction = this._select;
  21971. // Use the regular mix function and for additive on these types,
  21972. // additive is not relevant for non-numeric types
  21973. mixFunctionAdditive = this._select;
  21974. setIdentity = this._setAdditiveIdentityOther;
  21975. this.buffer = new Array( valueSize * 5 );
  21976. break;
  21977. default:
  21978. mixFunction = this._lerp;
  21979. mixFunctionAdditive = this._lerpAdditive;
  21980. setIdentity = this._setAdditiveIdentityNumeric;
  21981. this.buffer = new Float64Array( valueSize * 5 );
  21982. }
  21983. this._mixBufferRegion = mixFunction;
  21984. this._mixBufferRegionAdditive = mixFunctionAdditive;
  21985. this._setIdentity = setIdentity;
  21986. this._origIndex = 3;
  21987. this._addIndex = 4;
  21988. this.cumulativeWeight = 0;
  21989. this.cumulativeWeightAdditive = 0;
  21990. this.useCount = 0;
  21991. this.referenceCount = 0;
  21992. }
  21993. // accumulate data in the 'incoming' region into 'accu<i>'
  21994. accumulate( accuIndex, weight ) {
  21995. // note: happily accumulating nothing when weight = 0, the caller knows
  21996. // the weight and shouldn't have made the call in the first place
  21997. const buffer = this.buffer,
  21998. stride = this.valueSize,
  21999. offset = accuIndex * stride + stride;
  22000. let currentWeight = this.cumulativeWeight;
  22001. if ( currentWeight === 0 ) {
  22002. // accuN := incoming * weight
  22003. for ( let i = 0; i !== stride; ++ i ) {
  22004. buffer[ offset + i ] = buffer[ i ];
  22005. }
  22006. currentWeight = weight;
  22007. } else {
  22008. // accuN := accuN + incoming * weight
  22009. currentWeight += weight;
  22010. const mix = weight / currentWeight;
  22011. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  22012. }
  22013. this.cumulativeWeight = currentWeight;
  22014. }
  22015. // accumulate data in the 'incoming' region into 'add'
  22016. accumulateAdditive( weight ) {
  22017. const buffer = this.buffer,
  22018. stride = this.valueSize,
  22019. offset = stride * this._addIndex;
  22020. if ( this.cumulativeWeightAdditive === 0 ) {
  22021. // add = identity
  22022. this._setIdentity();
  22023. }
  22024. // add := add + incoming * weight
  22025. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  22026. this.cumulativeWeightAdditive += weight;
  22027. }
  22028. // apply the state of 'accu<i>' to the binding when accus differ
  22029. apply( accuIndex ) {
  22030. const stride = this.valueSize,
  22031. buffer = this.buffer,
  22032. offset = accuIndex * stride + stride,
  22033. weight = this.cumulativeWeight,
  22034. weightAdditive = this.cumulativeWeightAdditive,
  22035. binding = this.binding;
  22036. this.cumulativeWeight = 0;
  22037. this.cumulativeWeightAdditive = 0;
  22038. if ( weight < 1 ) {
  22039. // accuN := accuN + original * ( 1 - cumulativeWeight )
  22040. const originalValueOffset = stride * this._origIndex;
  22041. this._mixBufferRegion(
  22042. buffer, offset, originalValueOffset, 1 - weight, stride );
  22043. }
  22044. if ( weightAdditive > 0 ) {
  22045. // accuN := accuN + additive accuN
  22046. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  22047. }
  22048. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  22049. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  22050. // value has changed -> update scene graph
  22051. binding.setValue( buffer, offset );
  22052. break;
  22053. }
  22054. }
  22055. }
  22056. // remember the state of the bound property and copy it to both accus
  22057. saveOriginalState() {
  22058. const binding = this.binding;
  22059. const buffer = this.buffer,
  22060. stride = this.valueSize,
  22061. originalValueOffset = stride * this._origIndex;
  22062. binding.getValue( buffer, originalValueOffset );
  22063. // accu[0..1] := orig -- initially detect changes against the original
  22064. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  22065. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  22066. }
  22067. // Add to identity for additive
  22068. this._setIdentity();
  22069. this.cumulativeWeight = 0;
  22070. this.cumulativeWeightAdditive = 0;
  22071. }
  22072. // apply the state previously taken via 'saveOriginalState' to the binding
  22073. restoreOriginalState() {
  22074. const originalValueOffset = this.valueSize * 3;
  22075. this.binding.setValue( this.buffer, originalValueOffset );
  22076. }
  22077. _setAdditiveIdentityNumeric() {
  22078. const startIndex = this._addIndex * this.valueSize;
  22079. const endIndex = startIndex + this.valueSize;
  22080. for ( let i = startIndex; i < endIndex; i ++ ) {
  22081. this.buffer[ i ] = 0;
  22082. }
  22083. }
  22084. _setAdditiveIdentityQuaternion() {
  22085. this._setAdditiveIdentityNumeric();
  22086. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  22087. }
  22088. _setAdditiveIdentityOther() {
  22089. const startIndex = this._origIndex * this.valueSize;
  22090. const targetIndex = this._addIndex * this.valueSize;
  22091. for ( let i = 0; i < this.valueSize; i ++ ) {
  22092. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  22093. }
  22094. }
  22095. // mix functions
  22096. _select( buffer, dstOffset, srcOffset, t, stride ) {
  22097. if ( t >= 0.5 ) {
  22098. for ( let i = 0; i !== stride; ++ i ) {
  22099. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  22100. }
  22101. }
  22102. }
  22103. _slerp( buffer, dstOffset, srcOffset, t ) {
  22104. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  22105. }
  22106. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  22107. const workOffset = this._workIndex * stride;
  22108. // Store result in intermediate buffer offset
  22109. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  22110. // Slerp to the intermediate result
  22111. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  22112. }
  22113. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  22114. const s = 1 - t;
  22115. for ( let i = 0; i !== stride; ++ i ) {
  22116. const j = dstOffset + i;
  22117. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  22118. }
  22119. }
  22120. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  22121. for ( let i = 0; i !== stride; ++ i ) {
  22122. const j = dstOffset + i;
  22123. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  22124. }
  22125. }
  22126. }
  22127. // Characters [].:/ are reserved for track binding syntax.
  22128. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  22129. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  22130. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  22131. // only latin characters, and the unicode \p{L} is not yet supported. So
  22132. // instead, we exclude reserved characters and match everything else.
  22133. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  22134. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  22135. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  22136. // be matched to parse the rest of the track name.
  22137. const _directoryRe = /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  22138. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  22139. const _nodeRe = /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  22140. // Object on target node, and accessor. May not contain reserved
  22141. // characters. Accessor may contain any character except closing bracket.
  22142. const _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  22143. // Property and accessor. May not contain reserved characters. Accessor may
  22144. // contain any non-bracket characters.
  22145. const _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  22146. const _trackRe = new RegExp( ''
  22147. + '^'
  22148. + _directoryRe
  22149. + _nodeRe
  22150. + _objectRe
  22151. + _propertyRe
  22152. + '$'
  22153. );
  22154. const _supportedObjectNames = [ 'material', 'materials', 'bones' ];
  22155. class Composite {
  22156. constructor( targetGroup, path, optionalParsedPath ) {
  22157. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  22158. this._targetGroup = targetGroup;
  22159. this._bindings = targetGroup.subscribe_( path, parsedPath );
  22160. }
  22161. getValue( array, offset ) {
  22162. this.bind(); // bind all binding
  22163. const firstValidIndex = this._targetGroup.nCachedObjects_,
  22164. binding = this._bindings[ firstValidIndex ];
  22165. // and only call .getValue on the first
  22166. if ( binding !== undefined ) binding.getValue( array, offset );
  22167. }
  22168. setValue( array, offset ) {
  22169. const bindings = this._bindings;
  22170. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  22171. bindings[ i ].setValue( array, offset );
  22172. }
  22173. }
  22174. bind() {
  22175. const bindings = this._bindings;
  22176. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  22177. bindings[ i ].bind();
  22178. }
  22179. }
  22180. unbind() {
  22181. const bindings = this._bindings;
  22182. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  22183. bindings[ i ].unbind();
  22184. }
  22185. }
  22186. }
  22187. // Note: This class uses a State pattern on a per-method basis:
  22188. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  22189. // prototype version of these methods with one that represents
  22190. // the bound state. When the property is not found, the methods
  22191. // become no-ops.
  22192. class PropertyBinding {
  22193. constructor( rootNode, path, parsedPath ) {
  22194. this.path = path;
  22195. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  22196. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
  22197. this.rootNode = rootNode;
  22198. // initial state of these methods that calls 'bind'
  22199. this.getValue = this._getValue_unbound;
  22200. this.setValue = this._setValue_unbound;
  22201. }
  22202. static create( root, path, parsedPath ) {
  22203. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  22204. return new PropertyBinding( root, path, parsedPath );
  22205. } else {
  22206. return new PropertyBinding.Composite( root, path, parsedPath );
  22207. }
  22208. }
  22209. /**
  22210. * Replaces spaces with underscores and removes unsupported characters from
  22211. * node names, to ensure compatibility with parseTrackName().
  22212. *
  22213. * @param {string} name Node name to be sanitized.
  22214. * @return {string}
  22215. */
  22216. static sanitizeNodeName( name ) {
  22217. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  22218. }
  22219. static parseTrackName( trackName ) {
  22220. const matches = _trackRe.exec( trackName );
  22221. if ( ! matches ) {
  22222. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  22223. }
  22224. const results = {
  22225. // directoryName: matches[ 1 ], // (tschw) currently unused
  22226. nodeName: matches[ 2 ],
  22227. objectName: matches[ 3 ],
  22228. objectIndex: matches[ 4 ],
  22229. propertyName: matches[ 5 ], // required
  22230. propertyIndex: matches[ 6 ]
  22231. };
  22232. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  22233. if ( lastDot !== undefined && lastDot !== - 1 ) {
  22234. const objectName = results.nodeName.substring( lastDot + 1 );
  22235. // Object names must be checked against an allowlist. Otherwise, there
  22236. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  22237. // 'bar' could be the objectName, or part of a nodeName (which can
  22238. // include '.' characters).
  22239. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  22240. results.nodeName = results.nodeName.substring( 0, lastDot );
  22241. results.objectName = objectName;
  22242. }
  22243. }
  22244. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  22245. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  22246. }
  22247. return results;
  22248. }
  22249. static findNode( root, nodeName ) {
  22250. if ( ! nodeName || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  22251. return root;
  22252. }
  22253. // search into skeleton bones.
  22254. if ( root.skeleton ) {
  22255. const bone = root.skeleton.getBoneByName( nodeName );
  22256. if ( bone !== undefined ) {
  22257. return bone;
  22258. }
  22259. }
  22260. // search into node subtree.
  22261. if ( root.children ) {
  22262. const searchNodeSubtree = function ( children ) {
  22263. for ( let i = 0; i < children.length; i ++ ) {
  22264. const childNode = children[ i ];
  22265. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  22266. return childNode;
  22267. }
  22268. const result = searchNodeSubtree( childNode.children );
  22269. if ( result ) return result;
  22270. }
  22271. return null;
  22272. };
  22273. const subTreeNode = searchNodeSubtree( root.children );
  22274. if ( subTreeNode ) {
  22275. return subTreeNode;
  22276. }
  22277. }
  22278. return null;
  22279. }
  22280. // these are used to "bind" a nonexistent property
  22281. _getValue_unavailable() {}
  22282. _setValue_unavailable() {}
  22283. // Getters
  22284. _getValue_direct( buffer, offset ) {
  22285. buffer[ offset ] = this.node[ this.propertyName ];
  22286. }
  22287. _getValue_array( buffer, offset ) {
  22288. const source = this.resolvedProperty;
  22289. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  22290. buffer[ offset ++ ] = source[ i ];
  22291. }
  22292. }
  22293. _getValue_arrayElement( buffer, offset ) {
  22294. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  22295. }
  22296. _getValue_toArray( buffer, offset ) {
  22297. this.resolvedProperty.toArray( buffer, offset );
  22298. }
  22299. // Direct
  22300. _setValue_direct( buffer, offset ) {
  22301. this.targetObject[ this.propertyName ] = buffer[ offset ];
  22302. }
  22303. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  22304. this.targetObject[ this.propertyName ] = buffer[ offset ];
  22305. this.targetObject.needsUpdate = true;
  22306. }
  22307. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22308. this.targetObject[ this.propertyName ] = buffer[ offset ];
  22309. this.targetObject.matrixWorldNeedsUpdate = true;
  22310. }
  22311. // EntireArray
  22312. _setValue_array( buffer, offset ) {
  22313. const dest = this.resolvedProperty;
  22314. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  22315. dest[ i ] = buffer[ offset ++ ];
  22316. }
  22317. }
  22318. _setValue_array_setNeedsUpdate( buffer, offset ) {
  22319. const dest = this.resolvedProperty;
  22320. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  22321. dest[ i ] = buffer[ offset ++ ];
  22322. }
  22323. this.targetObject.needsUpdate = true;
  22324. }
  22325. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22326. const dest = this.resolvedProperty;
  22327. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  22328. dest[ i ] = buffer[ offset ++ ];
  22329. }
  22330. this.targetObject.matrixWorldNeedsUpdate = true;
  22331. }
  22332. // ArrayElement
  22333. _setValue_arrayElement( buffer, offset ) {
  22334. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  22335. }
  22336. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  22337. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  22338. this.targetObject.needsUpdate = true;
  22339. }
  22340. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22341. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  22342. this.targetObject.matrixWorldNeedsUpdate = true;
  22343. }
  22344. // HasToFromArray
  22345. _setValue_fromArray( buffer, offset ) {
  22346. this.resolvedProperty.fromArray( buffer, offset );
  22347. }
  22348. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  22349. this.resolvedProperty.fromArray( buffer, offset );
  22350. this.targetObject.needsUpdate = true;
  22351. }
  22352. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  22353. this.resolvedProperty.fromArray( buffer, offset );
  22354. this.targetObject.matrixWorldNeedsUpdate = true;
  22355. }
  22356. _getValue_unbound( targetArray, offset ) {
  22357. this.bind();
  22358. this.getValue( targetArray, offset );
  22359. }
  22360. _setValue_unbound( sourceArray, offset ) {
  22361. this.bind();
  22362. this.setValue( sourceArray, offset );
  22363. }
  22364. // create getter / setter pair for a property in the scene graph
  22365. bind() {
  22366. let targetObject = this.node;
  22367. const parsedPath = this.parsedPath;
  22368. const objectName = parsedPath.objectName;
  22369. const propertyName = parsedPath.propertyName;
  22370. let propertyIndex = parsedPath.propertyIndex;
  22371. if ( ! targetObject ) {
  22372. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode;
  22373. this.node = targetObject;
  22374. }
  22375. // set fail state so we can just 'return' on error
  22376. this.getValue = this._getValue_unavailable;
  22377. this.setValue = this._setValue_unavailable;
  22378. // ensure there is a value node
  22379. if ( ! targetObject ) {
  22380. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  22381. return;
  22382. }
  22383. if ( objectName ) {
  22384. let objectIndex = parsedPath.objectIndex;
  22385. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  22386. switch ( objectName ) {
  22387. case 'materials':
  22388. if ( ! targetObject.material ) {
  22389. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  22390. return;
  22391. }
  22392. if ( ! targetObject.material.materials ) {
  22393. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  22394. return;
  22395. }
  22396. targetObject = targetObject.material.materials;
  22397. break;
  22398. case 'bones':
  22399. if ( ! targetObject.skeleton ) {
  22400. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  22401. return;
  22402. }
  22403. // potential future optimization: skip this if propertyIndex is already an integer
  22404. // and convert the integer string to a true integer.
  22405. targetObject = targetObject.skeleton.bones;
  22406. // support resolving morphTarget names into indices.
  22407. for ( let i = 0; i < targetObject.length; i ++ ) {
  22408. if ( targetObject[ i ].name === objectIndex ) {
  22409. objectIndex = i;
  22410. break;
  22411. }
  22412. }
  22413. break;
  22414. default:
  22415. if ( targetObject[ objectName ] === undefined ) {
  22416. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  22417. return;
  22418. }
  22419. targetObject = targetObject[ objectName ];
  22420. }
  22421. if ( objectIndex !== undefined ) {
  22422. if ( targetObject[ objectIndex ] === undefined ) {
  22423. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  22424. return;
  22425. }
  22426. targetObject = targetObject[ objectIndex ];
  22427. }
  22428. }
  22429. // resolve property
  22430. const nodeProperty = targetObject[ propertyName ];
  22431. if ( nodeProperty === undefined ) {
  22432. const nodeName = parsedPath.nodeName;
  22433. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  22434. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  22435. return;
  22436. }
  22437. // determine versioning scheme
  22438. let versioning = this.Versioning.None;
  22439. this.targetObject = targetObject;
  22440. if ( targetObject.needsUpdate !== undefined ) { // material
  22441. versioning = this.Versioning.NeedsUpdate;
  22442. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  22443. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  22444. }
  22445. // determine how the property gets bound
  22446. let bindingType = this.BindingType.Direct;
  22447. if ( propertyIndex !== undefined ) {
  22448. // access a sub element of the property array (only primitives are supported right now)
  22449. if ( propertyName === 'morphTargetInfluences' ) {
  22450. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  22451. // support resolving morphTarget names into indices.
  22452. if ( ! targetObject.geometry ) {
  22453. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  22454. return;
  22455. }
  22456. if ( targetObject.geometry.isBufferGeometry ) {
  22457. if ( ! targetObject.geometry.morphAttributes ) {
  22458. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  22459. return;
  22460. }
  22461. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  22462. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  22463. }
  22464. } else {
  22465. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this );
  22466. return;
  22467. }
  22468. }
  22469. bindingType = this.BindingType.ArrayElement;
  22470. this.resolvedProperty = nodeProperty;
  22471. this.propertyIndex = propertyIndex;
  22472. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  22473. // must use copy for Object3D.Euler/Quaternion
  22474. bindingType = this.BindingType.HasFromToArray;
  22475. this.resolvedProperty = nodeProperty;
  22476. } else if ( Array.isArray( nodeProperty ) ) {
  22477. bindingType = this.BindingType.EntireArray;
  22478. this.resolvedProperty = nodeProperty;
  22479. } else {
  22480. this.propertyName = propertyName;
  22481. }
  22482. // select getter / setter
  22483. this.getValue = this.GetterByBindingType[ bindingType ];
  22484. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  22485. }
  22486. unbind() {
  22487. this.node = null;
  22488. // back to the prototype version of getValue / setValue
  22489. // note: avoiding to mutate the shape of 'this' via 'delete'
  22490. this.getValue = this._getValue_unbound;
  22491. this.setValue = this._setValue_unbound;
  22492. }
  22493. }
  22494. PropertyBinding.Composite = Composite;
  22495. PropertyBinding.prototype.BindingType = {
  22496. Direct: 0,
  22497. EntireArray: 1,
  22498. ArrayElement: 2,
  22499. HasFromToArray: 3
  22500. };
  22501. PropertyBinding.prototype.Versioning = {
  22502. None: 0,
  22503. NeedsUpdate: 1,
  22504. MatrixWorldNeedsUpdate: 2
  22505. };
  22506. PropertyBinding.prototype.GetterByBindingType = [
  22507. PropertyBinding.prototype._getValue_direct,
  22508. PropertyBinding.prototype._getValue_array,
  22509. PropertyBinding.prototype._getValue_arrayElement,
  22510. PropertyBinding.prototype._getValue_toArray,
  22511. ];
  22512. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  22513. [
  22514. // Direct
  22515. PropertyBinding.prototype._setValue_direct,
  22516. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  22517. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  22518. ], [
  22519. // EntireArray
  22520. PropertyBinding.prototype._setValue_array,
  22521. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  22522. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  22523. ], [
  22524. // ArrayElement
  22525. PropertyBinding.prototype._setValue_arrayElement,
  22526. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  22527. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  22528. ], [
  22529. // HasToFromArray
  22530. PropertyBinding.prototype._setValue_fromArray,
  22531. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  22532. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  22533. ]
  22534. ];
  22535. class AnimationAction {
  22536. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  22537. this._mixer = mixer;
  22538. this._clip = clip;
  22539. this._localRoot = localRoot;
  22540. this.blendMode = blendMode;
  22541. const tracks = clip.tracks,
  22542. nTracks = tracks.length,
  22543. interpolants = new Array( nTracks );
  22544. const interpolantSettings = {
  22545. endingStart: ZeroCurvatureEnding,
  22546. endingEnd: ZeroCurvatureEnding
  22547. };
  22548. for ( let i = 0; i !== nTracks; ++ i ) {
  22549. const interpolant = tracks[ i ].createInterpolant( null );
  22550. interpolants[ i ] = interpolant;
  22551. interpolant.settings = interpolantSettings;
  22552. }
  22553. this._interpolantSettings = interpolantSettings;
  22554. this._interpolants = interpolants; // bound by the mixer
  22555. // inside: PropertyMixer (managed by the mixer)
  22556. this._propertyBindings = new Array( nTracks );
  22557. this._cacheIndex = null; // for the memory manager
  22558. this._byClipCacheIndex = null; // for the memory manager
  22559. this._timeScaleInterpolant = null;
  22560. this._weightInterpolant = null;
  22561. this.loop = LoopRepeat;
  22562. this._loopCount = - 1;
  22563. // global mixer time when the action is to be started
  22564. // it's set back to 'null' upon start of the action
  22565. this._startTime = null;
  22566. // scaled local time of the action
  22567. // gets clamped or wrapped to 0..clip.duration according to loop
  22568. this.time = 0;
  22569. this.timeScale = 1;
  22570. this._effectiveTimeScale = 1;
  22571. this.weight = 1;
  22572. this._effectiveWeight = 1;
  22573. this.repetitions = Infinity; // no. of repetitions when looping
  22574. this.paused = false; // true -> zero effective time scale
  22575. this.enabled = true; // false -> zero effective weight
  22576. this.clampWhenFinished = false;// keep feeding the last frame?
  22577. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  22578. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  22579. }
  22580. // State & Scheduling
  22581. play() {
  22582. this._mixer._activateAction( this );
  22583. return this;
  22584. }
  22585. stop() {
  22586. this._mixer._deactivateAction( this );
  22587. return this.reset();
  22588. }
  22589. reset() {
  22590. this.paused = false;
  22591. this.enabled = true;
  22592. this.time = 0; // restart clip
  22593. this._loopCount = - 1;// forget previous loops
  22594. this._startTime = null;// forget scheduling
  22595. return this.stopFading().stopWarping();
  22596. }
  22597. isRunning() {
  22598. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  22599. this._startTime === null && this._mixer._isActiveAction( this );
  22600. }
  22601. // return true when play has been called
  22602. isScheduled() {
  22603. return this._mixer._isActiveAction( this );
  22604. }
  22605. startAt( time ) {
  22606. this._startTime = time;
  22607. return this;
  22608. }
  22609. setLoop( mode, repetitions ) {
  22610. this.loop = mode;
  22611. this.repetitions = repetitions;
  22612. return this;
  22613. }
  22614. // Weight
  22615. // set the weight stopping any scheduled fading
  22616. // although .enabled = false yields an effective weight of zero, this
  22617. // method does *not* change .enabled, because it would be confusing
  22618. setEffectiveWeight( weight ) {
  22619. this.weight = weight;
  22620. // note: same logic as when updated at runtime
  22621. this._effectiveWeight = this.enabled ? weight : 0;
  22622. return this.stopFading();
  22623. }
  22624. // return the weight considering fading and .enabled
  22625. getEffectiveWeight() {
  22626. return this._effectiveWeight;
  22627. }
  22628. fadeIn( duration ) {
  22629. return this._scheduleFading( duration, 0, 1 );
  22630. }
  22631. fadeOut( duration ) {
  22632. return this._scheduleFading( duration, 1, 0 );
  22633. }
  22634. crossFadeFrom( fadeOutAction, duration, warp ) {
  22635. fadeOutAction.fadeOut( duration );
  22636. this.fadeIn( duration );
  22637. if ( warp ) {
  22638. const fadeInDuration = this._clip.duration,
  22639. fadeOutDuration = fadeOutAction._clip.duration,
  22640. startEndRatio = fadeOutDuration / fadeInDuration,
  22641. endStartRatio = fadeInDuration / fadeOutDuration;
  22642. fadeOutAction.warp( 1.0, startEndRatio, duration );
  22643. this.warp( endStartRatio, 1.0, duration );
  22644. }
  22645. return this;
  22646. }
  22647. crossFadeTo( fadeInAction, duration, warp ) {
  22648. return fadeInAction.crossFadeFrom( this, duration, warp );
  22649. }
  22650. stopFading() {
  22651. const weightInterpolant = this._weightInterpolant;
  22652. if ( weightInterpolant !== null ) {
  22653. this._weightInterpolant = null;
  22654. this._mixer._takeBackControlInterpolant( weightInterpolant );
  22655. }
  22656. return this;
  22657. }
  22658. // Time Scale Control
  22659. // set the time scale stopping any scheduled warping
  22660. // although .paused = true yields an effective time scale of zero, this
  22661. // method does *not* change .paused, because it would be confusing
  22662. setEffectiveTimeScale( timeScale ) {
  22663. this.timeScale = timeScale;
  22664. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  22665. return this.stopWarping();
  22666. }
  22667. // return the time scale considering warping and .paused
  22668. getEffectiveTimeScale() {
  22669. return this._effectiveTimeScale;
  22670. }
  22671. setDuration( duration ) {
  22672. this.timeScale = this._clip.duration / duration;
  22673. return this.stopWarping();
  22674. }
  22675. syncWith( action ) {
  22676. this.time = action.time;
  22677. this.timeScale = action.timeScale;
  22678. return this.stopWarping();
  22679. }
  22680. halt( duration ) {
  22681. return this.warp( this._effectiveTimeScale, 0, duration );
  22682. }
  22683. warp( startTimeScale, endTimeScale, duration ) {
  22684. const mixer = this._mixer,
  22685. now = mixer.time,
  22686. timeScale = this.timeScale;
  22687. let interpolant = this._timeScaleInterpolant;
  22688. if ( interpolant === null ) {
  22689. interpolant = mixer._lendControlInterpolant();
  22690. this._timeScaleInterpolant = interpolant;
  22691. }
  22692. const times = interpolant.parameterPositions,
  22693. values = interpolant.sampleValues;
  22694. times[ 0 ] = now;
  22695. times[ 1 ] = now + duration;
  22696. values[ 0 ] = startTimeScale / timeScale;
  22697. values[ 1 ] = endTimeScale / timeScale;
  22698. return this;
  22699. }
  22700. stopWarping() {
  22701. const timeScaleInterpolant = this._timeScaleInterpolant;
  22702. if ( timeScaleInterpolant !== null ) {
  22703. this._timeScaleInterpolant = null;
  22704. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  22705. }
  22706. return this;
  22707. }
  22708. // Object Accessors
  22709. getMixer() {
  22710. return this._mixer;
  22711. }
  22712. getClip() {
  22713. return this._clip;
  22714. }
  22715. getRoot() {
  22716. return this._localRoot || this._mixer._root;
  22717. }
  22718. // Interna
  22719. _update( time, deltaTime, timeDirection, accuIndex ) {
  22720. // called by the mixer
  22721. if ( ! this.enabled ) {
  22722. // call ._updateWeight() to update ._effectiveWeight
  22723. this._updateWeight( time );
  22724. return;
  22725. }
  22726. const startTime = this._startTime;
  22727. if ( startTime !== null ) {
  22728. // check for scheduled start of action
  22729. const timeRunning = ( time - startTime ) * timeDirection;
  22730. if ( timeRunning < 0 || timeDirection === 0 ) {
  22731. return; // yet to come / don't decide when delta = 0
  22732. }
  22733. // start
  22734. this._startTime = null; // unschedule
  22735. deltaTime = timeDirection * timeRunning;
  22736. }
  22737. // apply time scale and advance time
  22738. deltaTime *= this._updateTimeScale( time );
  22739. const clipTime = this._updateTime( deltaTime );
  22740. // note: _updateTime may disable the action resulting in
  22741. // an effective weight of 0
  22742. const weight = this._updateWeight( time );
  22743. if ( weight > 0 ) {
  22744. const interpolants = this._interpolants;
  22745. const propertyMixers = this._propertyBindings;
  22746. switch ( this.blendMode ) {
  22747. case AdditiveAnimationBlendMode:
  22748. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  22749. interpolants[ j ].evaluate( clipTime );
  22750. propertyMixers[ j ].accumulateAdditive( weight );
  22751. }
  22752. break;
  22753. case NormalAnimationBlendMode:
  22754. default:
  22755. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  22756. interpolants[ j ].evaluate( clipTime );
  22757. propertyMixers[ j ].accumulate( accuIndex, weight );
  22758. }
  22759. }
  22760. }
  22761. }
  22762. _updateWeight( time ) {
  22763. let weight = 0;
  22764. if ( this.enabled ) {
  22765. weight = this.weight;
  22766. const interpolant = this._weightInterpolant;
  22767. if ( interpolant !== null ) {
  22768. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  22769. weight *= interpolantValue;
  22770. if ( time > interpolant.parameterPositions[ 1 ] ) {
  22771. this.stopFading();
  22772. if ( interpolantValue === 0 ) {
  22773. // faded out, disable
  22774. this.enabled = false;
  22775. }
  22776. }
  22777. }
  22778. }
  22779. this._effectiveWeight = weight;
  22780. return weight;
  22781. }
  22782. _updateTimeScale( time ) {
  22783. let timeScale = 0;
  22784. if ( ! this.paused ) {
  22785. timeScale = this.timeScale;
  22786. const interpolant = this._timeScaleInterpolant;
  22787. if ( interpolant !== null ) {
  22788. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  22789. timeScale *= interpolantValue;
  22790. if ( time > interpolant.parameterPositions[ 1 ] ) {
  22791. this.stopWarping();
  22792. if ( timeScale === 0 ) {
  22793. // motion has halted, pause
  22794. this.paused = true;
  22795. } else {
  22796. // warp done - apply final time scale
  22797. this.timeScale = timeScale;
  22798. }
  22799. }
  22800. }
  22801. }
  22802. this._effectiveTimeScale = timeScale;
  22803. return timeScale;
  22804. }
  22805. _updateTime( deltaTime ) {
  22806. const duration = this._clip.duration;
  22807. const loop = this.loop;
  22808. let time = this.time + deltaTime;
  22809. let loopCount = this._loopCount;
  22810. const pingPong = ( loop === LoopPingPong );
  22811. if ( deltaTime === 0 ) {
  22812. if ( loopCount === - 1 ) return time;
  22813. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  22814. }
  22815. if ( loop === LoopOnce ) {
  22816. if ( loopCount === - 1 ) {
  22817. // just started
  22818. this._loopCount = 0;
  22819. this._setEndings( true, true, false );
  22820. }
  22821. handle_stop: {
  22822. if ( time >= duration ) {
  22823. time = duration;
  22824. } else if ( time < 0 ) {
  22825. time = 0;
  22826. } else {
  22827. this.time = time;
  22828. break handle_stop;
  22829. }
  22830. if ( this.clampWhenFinished ) this.paused = true;
  22831. else this.enabled = false;
  22832. this.time = time;
  22833. this._mixer.dispatchEvent( {
  22834. type: 'finished', action: this,
  22835. direction: deltaTime < 0 ? - 1 : 1
  22836. } );
  22837. }
  22838. } else { // repetitive Repeat or PingPong
  22839. if ( loopCount === - 1 ) {
  22840. // just started
  22841. if ( deltaTime >= 0 ) {
  22842. loopCount = 0;
  22843. this._setEndings( true, this.repetitions === 0, pingPong );
  22844. } else {
  22845. // when looping in reverse direction, the initial
  22846. // transition through zero counts as a repetition,
  22847. // so leave loopCount at -1
  22848. this._setEndings( this.repetitions === 0, true, pingPong );
  22849. }
  22850. }
  22851. if ( time >= duration || time < 0 ) {
  22852. // wrap around
  22853. const loopDelta = Math.floor( time / duration ); // signed
  22854. time -= duration * loopDelta;
  22855. loopCount += Math.abs( loopDelta );
  22856. const pending = this.repetitions - loopCount;
  22857. if ( pending <= 0 ) {
  22858. // have to stop (switch state, clamp time, fire event)
  22859. if ( this.clampWhenFinished ) this.paused = true;
  22860. else this.enabled = false;
  22861. time = deltaTime > 0 ? duration : 0;
  22862. this.time = time;
  22863. this._mixer.dispatchEvent( {
  22864. type: 'finished', action: this,
  22865. direction: deltaTime > 0 ? 1 : - 1
  22866. } );
  22867. } else {
  22868. // keep running
  22869. if ( pending === 1 ) {
  22870. // entering the last round
  22871. const atStart = deltaTime < 0;
  22872. this._setEndings( atStart, ! atStart, pingPong );
  22873. } else {
  22874. this._setEndings( false, false, pingPong );
  22875. }
  22876. this._loopCount = loopCount;
  22877. this.time = time;
  22878. this._mixer.dispatchEvent( {
  22879. type: 'loop', action: this, loopDelta: loopDelta
  22880. } );
  22881. }
  22882. } else {
  22883. this.time = time;
  22884. }
  22885. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  22886. // invert time for the "pong round"
  22887. return duration - time;
  22888. }
  22889. }
  22890. return time;
  22891. }
  22892. _setEndings( atStart, atEnd, pingPong ) {
  22893. const settings = this._interpolantSettings;
  22894. if ( pingPong ) {
  22895. settings.endingStart = ZeroSlopeEnding;
  22896. settings.endingEnd = ZeroSlopeEnding;
  22897. } else {
  22898. // assuming for LoopOnce atStart == atEnd == true
  22899. if ( atStart ) {
  22900. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  22901. } else {
  22902. settings.endingStart = WrapAroundEnding;
  22903. }
  22904. if ( atEnd ) {
  22905. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  22906. } else {
  22907. settings.endingEnd = WrapAroundEnding;
  22908. }
  22909. }
  22910. }
  22911. _scheduleFading( duration, weightNow, weightThen ) {
  22912. const mixer = this._mixer, now = mixer.time;
  22913. let interpolant = this._weightInterpolant;
  22914. if ( interpolant === null ) {
  22915. interpolant = mixer._lendControlInterpolant();
  22916. this._weightInterpolant = interpolant;
  22917. }
  22918. const times = interpolant.parameterPositions,
  22919. values = interpolant.sampleValues;
  22920. times[ 0 ] = now;
  22921. values[ 0 ] = weightNow;
  22922. times[ 1 ] = now + duration;
  22923. values[ 1 ] = weightThen;
  22924. return this;
  22925. }
  22926. }
  22927. class AnimationMixer extends EventDispatcher {
  22928. constructor( root ) {
  22929. super();
  22930. this._root = root;
  22931. this._initMemoryManager();
  22932. this._accuIndex = 0;
  22933. this.time = 0;
  22934. this.timeScale = 1.0;
  22935. }
  22936. _bindAction( action, prototypeAction ) {
  22937. const root = action._localRoot || this._root,
  22938. tracks = action._clip.tracks,
  22939. nTracks = tracks.length,
  22940. bindings = action._propertyBindings,
  22941. interpolants = action._interpolants,
  22942. rootUuid = root.uuid,
  22943. bindingsByRoot = this._bindingsByRootAndName;
  22944. let bindingsByName = bindingsByRoot[ rootUuid ];
  22945. if ( bindingsByName === undefined ) {
  22946. bindingsByName = {};
  22947. bindingsByRoot[ rootUuid ] = bindingsByName;
  22948. }
  22949. for ( let i = 0; i !== nTracks; ++ i ) {
  22950. const track = tracks[ i ],
  22951. trackName = track.name;
  22952. let binding = bindingsByName[ trackName ];
  22953. if ( binding !== undefined ) {
  22954. bindings[ i ] = binding;
  22955. } else {
  22956. binding = bindings[ i ];
  22957. if ( binding !== undefined ) {
  22958. // existing binding, make sure the cache knows
  22959. if ( binding._cacheIndex === null ) {
  22960. ++ binding.referenceCount;
  22961. this._addInactiveBinding( binding, rootUuid, trackName );
  22962. }
  22963. continue;
  22964. }
  22965. const path = prototypeAction && prototypeAction.
  22966. _propertyBindings[ i ].binding.parsedPath;
  22967. binding = new PropertyMixer(
  22968. PropertyBinding.create( root, trackName, path ),
  22969. track.ValueTypeName, track.getValueSize() );
  22970. ++ binding.referenceCount;
  22971. this._addInactiveBinding( binding, rootUuid, trackName );
  22972. bindings[ i ] = binding;
  22973. }
  22974. interpolants[ i ].resultBuffer = binding.buffer;
  22975. }
  22976. }
  22977. _activateAction( action ) {
  22978. if ( ! this._isActiveAction( action ) ) {
  22979. if ( action._cacheIndex === null ) {
  22980. // this action has been forgotten by the cache, but the user
  22981. // appears to be still using it -> rebind
  22982. const rootUuid = ( action._localRoot || this._root ).uuid,
  22983. clipUuid = action._clip.uuid,
  22984. actionsForClip = this._actionsByClip[ clipUuid ];
  22985. this._bindAction( action,
  22986. actionsForClip && actionsForClip.knownActions[ 0 ] );
  22987. this._addInactiveAction( action, clipUuid, rootUuid );
  22988. }
  22989. const bindings = action._propertyBindings;
  22990. // increment reference counts / sort out state
  22991. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  22992. const binding = bindings[ i ];
  22993. if ( binding.useCount ++ === 0 ) {
  22994. this._lendBinding( binding );
  22995. binding.saveOriginalState();
  22996. }
  22997. }
  22998. this._lendAction( action );
  22999. }
  23000. }
  23001. _deactivateAction( action ) {
  23002. if ( this._isActiveAction( action ) ) {
  23003. const bindings = action._propertyBindings;
  23004. // decrement reference counts / sort out state
  23005. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  23006. const binding = bindings[ i ];
  23007. if ( -- binding.useCount === 0 ) {
  23008. binding.restoreOriginalState();
  23009. this._takeBackBinding( binding );
  23010. }
  23011. }
  23012. this._takeBackAction( action );
  23013. }
  23014. }
  23015. // Memory manager
  23016. _initMemoryManager() {
  23017. this._actions = []; // 'nActiveActions' followed by inactive ones
  23018. this._nActiveActions = 0;
  23019. this._actionsByClip = {};
  23020. // inside:
  23021. // {
  23022. // knownActions: Array< AnimationAction > - used as prototypes
  23023. // actionByRoot: AnimationAction - lookup
  23024. // }
  23025. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  23026. this._nActiveBindings = 0;
  23027. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  23028. this._controlInterpolants = []; // same game as above
  23029. this._nActiveControlInterpolants = 0;
  23030. const scope = this;
  23031. this.stats = {
  23032. actions: {
  23033. get total() {
  23034. return scope._actions.length;
  23035. },
  23036. get inUse() {
  23037. return scope._nActiveActions;
  23038. }
  23039. },
  23040. bindings: {
  23041. get total() {
  23042. return scope._bindings.length;
  23043. },
  23044. get inUse() {
  23045. return scope._nActiveBindings;
  23046. }
  23047. },
  23048. controlInterpolants: {
  23049. get total() {
  23050. return scope._controlInterpolants.length;
  23051. },
  23052. get inUse() {
  23053. return scope._nActiveControlInterpolants;
  23054. }
  23055. }
  23056. };
  23057. }
  23058. // Memory management for AnimationAction objects
  23059. _isActiveAction( action ) {
  23060. const index = action._cacheIndex;
  23061. return index !== null && index < this._nActiveActions;
  23062. }
  23063. _addInactiveAction( action, clipUuid, rootUuid ) {
  23064. const actions = this._actions,
  23065. actionsByClip = this._actionsByClip;
  23066. let actionsForClip = actionsByClip[ clipUuid ];
  23067. if ( actionsForClip === undefined ) {
  23068. actionsForClip = {
  23069. knownActions: [ action ],
  23070. actionByRoot: {}
  23071. };
  23072. action._byClipCacheIndex = 0;
  23073. actionsByClip[ clipUuid ] = actionsForClip;
  23074. } else {
  23075. const knownActions = actionsForClip.knownActions;
  23076. action._byClipCacheIndex = knownActions.length;
  23077. knownActions.push( action );
  23078. }
  23079. action._cacheIndex = actions.length;
  23080. actions.push( action );
  23081. actionsForClip.actionByRoot[ rootUuid ] = action;
  23082. }
  23083. _removeInactiveAction( action ) {
  23084. const actions = this._actions,
  23085. lastInactiveAction = actions[ actions.length - 1 ],
  23086. cacheIndex = action._cacheIndex;
  23087. lastInactiveAction._cacheIndex = cacheIndex;
  23088. actions[ cacheIndex ] = lastInactiveAction;
  23089. actions.pop();
  23090. action._cacheIndex = null;
  23091. const clipUuid = action._clip.uuid,
  23092. actionsByClip = this._actionsByClip,
  23093. actionsForClip = actionsByClip[ clipUuid ],
  23094. knownActionsForClip = actionsForClip.knownActions,
  23095. lastKnownAction =
  23096. knownActionsForClip[ knownActionsForClip.length - 1 ],
  23097. byClipCacheIndex = action._byClipCacheIndex;
  23098. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  23099. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  23100. knownActionsForClip.pop();
  23101. action._byClipCacheIndex = null;
  23102. const actionByRoot = actionsForClip.actionByRoot,
  23103. rootUuid = ( action._localRoot || this._root ).uuid;
  23104. delete actionByRoot[ rootUuid ];
  23105. if ( knownActionsForClip.length === 0 ) {
  23106. delete actionsByClip[ clipUuid ];
  23107. }
  23108. this._removeInactiveBindingsForAction( action );
  23109. }
  23110. _removeInactiveBindingsForAction( action ) {
  23111. const bindings = action._propertyBindings;
  23112. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  23113. const binding = bindings[ i ];
  23114. if ( -- binding.referenceCount === 0 ) {
  23115. this._removeInactiveBinding( binding );
  23116. }
  23117. }
  23118. }
  23119. _lendAction( action ) {
  23120. // [ active actions | inactive actions ]
  23121. // [ active actions >| inactive actions ]
  23122. // s a
  23123. // <-swap->
  23124. // a s
  23125. const actions = this._actions,
  23126. prevIndex = action._cacheIndex,
  23127. lastActiveIndex = this._nActiveActions ++,
  23128. firstInactiveAction = actions[ lastActiveIndex ];
  23129. action._cacheIndex = lastActiveIndex;
  23130. actions[ lastActiveIndex ] = action;
  23131. firstInactiveAction._cacheIndex = prevIndex;
  23132. actions[ prevIndex ] = firstInactiveAction;
  23133. }
  23134. _takeBackAction( action ) {
  23135. // [ active actions | inactive actions ]
  23136. // [ active actions |< inactive actions ]
  23137. // a s
  23138. // <-swap->
  23139. // s a
  23140. const actions = this._actions,
  23141. prevIndex = action._cacheIndex,
  23142. firstInactiveIndex = -- this._nActiveActions,
  23143. lastActiveAction = actions[ firstInactiveIndex ];
  23144. action._cacheIndex = firstInactiveIndex;
  23145. actions[ firstInactiveIndex ] = action;
  23146. lastActiveAction._cacheIndex = prevIndex;
  23147. actions[ prevIndex ] = lastActiveAction;
  23148. }
  23149. // Memory management for PropertyMixer objects
  23150. _addInactiveBinding( binding, rootUuid, trackName ) {
  23151. const bindingsByRoot = this._bindingsByRootAndName,
  23152. bindings = this._bindings;
  23153. let bindingByName = bindingsByRoot[ rootUuid ];
  23154. if ( bindingByName === undefined ) {
  23155. bindingByName = {};
  23156. bindingsByRoot[ rootUuid ] = bindingByName;
  23157. }
  23158. bindingByName[ trackName ] = binding;
  23159. binding._cacheIndex = bindings.length;
  23160. bindings.push( binding );
  23161. }
  23162. _removeInactiveBinding( binding ) {
  23163. const bindings = this._bindings,
  23164. propBinding = binding.binding,
  23165. rootUuid = propBinding.rootNode.uuid,
  23166. trackName = propBinding.path,
  23167. bindingsByRoot = this._bindingsByRootAndName,
  23168. bindingByName = bindingsByRoot[ rootUuid ],
  23169. lastInactiveBinding = bindings[ bindings.length - 1 ],
  23170. cacheIndex = binding._cacheIndex;
  23171. lastInactiveBinding._cacheIndex = cacheIndex;
  23172. bindings[ cacheIndex ] = lastInactiveBinding;
  23173. bindings.pop();
  23174. delete bindingByName[ trackName ];
  23175. if ( Object.keys( bindingByName ).length === 0 ) {
  23176. delete bindingsByRoot[ rootUuid ];
  23177. }
  23178. }
  23179. _lendBinding( binding ) {
  23180. const bindings = this._bindings,
  23181. prevIndex = binding._cacheIndex,
  23182. lastActiveIndex = this._nActiveBindings ++,
  23183. firstInactiveBinding = bindings[ lastActiveIndex ];
  23184. binding._cacheIndex = lastActiveIndex;
  23185. bindings[ lastActiveIndex ] = binding;
  23186. firstInactiveBinding._cacheIndex = prevIndex;
  23187. bindings[ prevIndex ] = firstInactiveBinding;
  23188. }
  23189. _takeBackBinding( binding ) {
  23190. const bindings = this._bindings,
  23191. prevIndex = binding._cacheIndex,
  23192. firstInactiveIndex = -- this._nActiveBindings,
  23193. lastActiveBinding = bindings[ firstInactiveIndex ];
  23194. binding._cacheIndex = firstInactiveIndex;
  23195. bindings[ firstInactiveIndex ] = binding;
  23196. lastActiveBinding._cacheIndex = prevIndex;
  23197. bindings[ prevIndex ] = lastActiveBinding;
  23198. }
  23199. // Memory management of Interpolants for weight and time scale
  23200. _lendControlInterpolant() {
  23201. const interpolants = this._controlInterpolants,
  23202. lastActiveIndex = this._nActiveControlInterpolants ++;
  23203. let interpolant = interpolants[ lastActiveIndex ];
  23204. if ( interpolant === undefined ) {
  23205. interpolant = new LinearInterpolant(
  23206. new Float32Array( 2 ), new Float32Array( 2 ),
  23207. 1, this._controlInterpolantsResultBuffer );
  23208. interpolant.__cacheIndex = lastActiveIndex;
  23209. interpolants[ lastActiveIndex ] = interpolant;
  23210. }
  23211. return interpolant;
  23212. }
  23213. _takeBackControlInterpolant( interpolant ) {
  23214. const interpolants = this._controlInterpolants,
  23215. prevIndex = interpolant.__cacheIndex,
  23216. firstInactiveIndex = -- this._nActiveControlInterpolants,
  23217. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  23218. interpolant.__cacheIndex = firstInactiveIndex;
  23219. interpolants[ firstInactiveIndex ] = interpolant;
  23220. lastActiveInterpolant.__cacheIndex = prevIndex;
  23221. interpolants[ prevIndex ] = lastActiveInterpolant;
  23222. }
  23223. // return an action for a clip optionally using a custom root target
  23224. // object (this method allocates a lot of dynamic memory in case a
  23225. // previously unknown clip/root combination is specified)
  23226. clipAction( clip, optionalRoot, blendMode ) {
  23227. const root = optionalRoot || this._root,
  23228. rootUuid = root.uuid;
  23229. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  23230. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  23231. const actionsForClip = this._actionsByClip[ clipUuid ];
  23232. let prototypeAction = null;
  23233. if ( blendMode === undefined ) {
  23234. if ( clipObject !== null ) {
  23235. blendMode = clipObject.blendMode;
  23236. } else {
  23237. blendMode = NormalAnimationBlendMode;
  23238. }
  23239. }
  23240. if ( actionsForClip !== undefined ) {
  23241. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  23242. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  23243. return existingAction;
  23244. }
  23245. // we know the clip, so we don't have to parse all
  23246. // the bindings again but can just copy
  23247. prototypeAction = actionsForClip.knownActions[ 0 ];
  23248. // also, take the clip from the prototype action
  23249. if ( clipObject === null )
  23250. clipObject = prototypeAction._clip;
  23251. }
  23252. // clip must be known when specified via string
  23253. if ( clipObject === null ) return null;
  23254. // allocate all resources required to run it
  23255. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  23256. this._bindAction( newAction, prototypeAction );
  23257. // and make the action known to the memory manager
  23258. this._addInactiveAction( newAction, clipUuid, rootUuid );
  23259. return newAction;
  23260. }
  23261. // get an existing action
  23262. existingAction( clip, optionalRoot ) {
  23263. const root = optionalRoot || this._root,
  23264. rootUuid = root.uuid,
  23265. clipObject = typeof clip === 'string' ?
  23266. AnimationClip.findByName( root, clip ) : clip,
  23267. clipUuid = clipObject ? clipObject.uuid : clip,
  23268. actionsForClip = this._actionsByClip[ clipUuid ];
  23269. if ( actionsForClip !== undefined ) {
  23270. return actionsForClip.actionByRoot[ rootUuid ] || null;
  23271. }
  23272. return null;
  23273. }
  23274. // deactivates all previously scheduled actions
  23275. stopAllAction() {
  23276. const actions = this._actions,
  23277. nActions = this._nActiveActions;
  23278. for ( let i = nActions - 1; i >= 0; -- i ) {
  23279. actions[ i ].stop();
  23280. }
  23281. return this;
  23282. }
  23283. // advance the time and update apply the animation
  23284. update( deltaTime ) {
  23285. deltaTime *= this.timeScale;
  23286. const actions = this._actions,
  23287. nActions = this._nActiveActions,
  23288. time = this.time += deltaTime,
  23289. timeDirection = Math.sign( deltaTime ),
  23290. accuIndex = this._accuIndex ^= 1;
  23291. // run active actions
  23292. for ( let i = 0; i !== nActions; ++ i ) {
  23293. const action = actions[ i ];
  23294. action._update( time, deltaTime, timeDirection, accuIndex );
  23295. }
  23296. // update scene graph
  23297. const bindings = this._bindings,
  23298. nBindings = this._nActiveBindings;
  23299. for ( let i = 0; i !== nBindings; ++ i ) {
  23300. bindings[ i ].apply( accuIndex );
  23301. }
  23302. return this;
  23303. }
  23304. // Allows you to seek to a specific time in an animation.
  23305. setTime( timeInSeconds ) {
  23306. this.time = 0; // Zero out time attribute for AnimationMixer object;
  23307. for ( let i = 0; i < this._actions.length; i ++ ) {
  23308. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  23309. }
  23310. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  23311. }
  23312. // return this mixer's root target object
  23313. getRoot() {
  23314. return this._root;
  23315. }
  23316. // free all resources specific to a particular clip
  23317. uncacheClip( clip ) {
  23318. const actions = this._actions,
  23319. clipUuid = clip.uuid,
  23320. actionsByClip = this._actionsByClip,
  23321. actionsForClip = actionsByClip[ clipUuid ];
  23322. if ( actionsForClip !== undefined ) {
  23323. // note: just calling _removeInactiveAction would mess up the
  23324. // iteration state and also require updating the state we can
  23325. // just throw away
  23326. const actionsToRemove = actionsForClip.knownActions;
  23327. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  23328. const action = actionsToRemove[ i ];
  23329. this._deactivateAction( action );
  23330. const cacheIndex = action._cacheIndex,
  23331. lastInactiveAction = actions[ actions.length - 1 ];
  23332. action._cacheIndex = null;
  23333. action._byClipCacheIndex = null;
  23334. lastInactiveAction._cacheIndex = cacheIndex;
  23335. actions[ cacheIndex ] = lastInactiveAction;
  23336. actions.pop();
  23337. this._removeInactiveBindingsForAction( action );
  23338. }
  23339. delete actionsByClip[ clipUuid ];
  23340. }
  23341. }
  23342. // free all resources specific to a particular root target object
  23343. uncacheRoot( root ) {
  23344. const rootUuid = root.uuid,
  23345. actionsByClip = this._actionsByClip;
  23346. for ( const clipUuid in actionsByClip ) {
  23347. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  23348. action = actionByRoot[ rootUuid ];
  23349. if ( action !== undefined ) {
  23350. this._deactivateAction( action );
  23351. this._removeInactiveAction( action );
  23352. }
  23353. }
  23354. const bindingsByRoot = this._bindingsByRootAndName,
  23355. bindingByName = bindingsByRoot[ rootUuid ];
  23356. if ( bindingByName !== undefined ) {
  23357. for ( const trackName in bindingByName ) {
  23358. const binding = bindingByName[ trackName ];
  23359. binding.restoreOriginalState();
  23360. this._removeInactiveBinding( binding );
  23361. }
  23362. }
  23363. }
  23364. // remove a targeted clip from the cache
  23365. uncacheAction( clip, optionalRoot ) {
  23366. const action = this.existingAction( clip, optionalRoot );
  23367. if ( action !== null ) {
  23368. this._deactivateAction( action );
  23369. this._removeInactiveAction( action );
  23370. }
  23371. }
  23372. }
  23373. AnimationMixer.prototype._controlInterpolantsResultBuffer = new Float32Array( 1 );
  23374. class InstancedInterleavedBuffer extends InterleavedBuffer {
  23375. constructor( array, stride, meshPerAttribute = 1 ) {
  23376. super( array, stride );
  23377. this.meshPerAttribute = meshPerAttribute;
  23378. }
  23379. copy( source ) {
  23380. super.copy( source );
  23381. this.meshPerAttribute = source.meshPerAttribute;
  23382. return this;
  23383. }
  23384. clone( data ) {
  23385. const ib = super.clone( data );
  23386. ib.meshPerAttribute = this.meshPerAttribute;
  23387. return ib;
  23388. }
  23389. toJSON( data ) {
  23390. const json = super.toJSON( data );
  23391. json.isInstancedInterleavedBuffer = true;
  23392. json.meshPerAttribute = this.meshPerAttribute;
  23393. return json;
  23394. }
  23395. }
  23396. InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true;
  23397. class Raycaster {
  23398. constructor( origin, direction, near = 0, far = Infinity ) {
  23399. this.ray = new Ray( origin, direction );
  23400. // direction is assumed to be normalized (for accurate distance calculations)
  23401. this.near = near;
  23402. this.far = far;
  23403. this.camera = null;
  23404. this.layers = new Layers();
  23405. this.params = {
  23406. Mesh: {},
  23407. Line: { threshold: 1 },
  23408. LOD: {},
  23409. Points: { threshold: 1 },
  23410. Sprite: {}
  23411. };
  23412. }
  23413. set( origin, direction ) {
  23414. // direction is assumed to be normalized (for accurate distance calculations)
  23415. this.ray.set( origin, direction );
  23416. }
  23417. setFromCamera( coords, camera ) {
  23418. if ( camera && camera.isPerspectiveCamera ) {
  23419. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  23420. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  23421. this.camera = camera;
  23422. } else if ( camera && camera.isOrthographicCamera ) {
  23423. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  23424. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  23425. this.camera = camera;
  23426. } else {
  23427. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  23428. }
  23429. }
  23430. intersectObject( object, recursive = false, intersects = [] ) {
  23431. intersectObject( object, this, intersects, recursive );
  23432. intersects.sort( ascSort );
  23433. return intersects;
  23434. }
  23435. intersectObjects( objects, recursive = false, intersects = [] ) {
  23436. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  23437. intersectObject( objects[ i ], this, intersects, recursive );
  23438. }
  23439. intersects.sort( ascSort );
  23440. return intersects;
  23441. }
  23442. }
  23443. function ascSort( a, b ) {
  23444. return a.distance - b.distance;
  23445. }
  23446. function intersectObject( object, raycaster, intersects, recursive ) {
  23447. if ( object.layers.test( raycaster.layers ) ) {
  23448. object.raycast( raycaster, intersects );
  23449. }
  23450. if ( recursive === true ) {
  23451. const children = object.children;
  23452. for ( let i = 0, l = children.length; i < l; i ++ ) {
  23453. intersectObject( children[ i ], raycaster, intersects, true );
  23454. }
  23455. }
  23456. }
  23457. /**
  23458. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  23459. *
  23460. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  23461. * The azimuthal angle (theta) is measured from the positive z-axis.
  23462. */
  23463. class Spherical {
  23464. constructor( radius = 1, phi = 0, theta = 0 ) {
  23465. this.radius = radius;
  23466. this.phi = phi; // polar angle
  23467. this.theta = theta; // azimuthal angle
  23468. return this;
  23469. }
  23470. set( radius, phi, theta ) {
  23471. this.radius = radius;
  23472. this.phi = phi;
  23473. this.theta = theta;
  23474. return this;
  23475. }
  23476. copy( other ) {
  23477. this.radius = other.radius;
  23478. this.phi = other.phi;
  23479. this.theta = other.theta;
  23480. return this;
  23481. }
  23482. // restrict phi to be betwee EPS and PI-EPS
  23483. makeSafe() {
  23484. const EPS = 0.000001;
  23485. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  23486. return this;
  23487. }
  23488. setFromVector3( v ) {
  23489. return this.setFromCartesianCoords( v.x, v.y, v.z );
  23490. }
  23491. setFromCartesianCoords( x, y, z ) {
  23492. this.radius = Math.sqrt( x * x + y * y + z * z );
  23493. if ( this.radius === 0 ) {
  23494. this.theta = 0;
  23495. this.phi = 0;
  23496. } else {
  23497. this.theta = Math.atan2( x, z );
  23498. this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) );
  23499. }
  23500. return this;
  23501. }
  23502. clone() {
  23503. return new this.constructor().copy( this );
  23504. }
  23505. }
  23506. class ImmediateRenderObject extends Object3D {
  23507. constructor( material ) {
  23508. super();
  23509. this.material = material;
  23510. this.render = function ( /* renderCallback */ ) {};
  23511. this.hasPositions = false;
  23512. this.hasNormals = false;
  23513. this.hasColors = false;
  23514. this.hasUvs = false;
  23515. this.positionArray = null;
  23516. this.normalArray = null;
  23517. this.colorArray = null;
  23518. this.uvArray = null;
  23519. this.count = 0;
  23520. }
  23521. }
  23522. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  23523. const _vector$2 = /*@__PURE__*/ new Vector3();
  23524. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  23525. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  23526. class SkeletonHelper extends LineSegments {
  23527. constructor( object ) {
  23528. const bones = getBoneList( object );
  23529. const geometry = new BufferGeometry();
  23530. const vertices = [];
  23531. const colors = [];
  23532. const color1 = new Color( 0, 0, 1 );
  23533. const color2 = new Color( 0, 1, 0 );
  23534. for ( let i = 0; i < bones.length; i ++ ) {
  23535. const bone = bones[ i ];
  23536. if ( bone.parent && bone.parent.isBone ) {
  23537. vertices.push( 0, 0, 0 );
  23538. vertices.push( 0, 0, 0 );
  23539. colors.push( color1.r, color1.g, color1.b );
  23540. colors.push( color2.r, color2.g, color2.b );
  23541. }
  23542. }
  23543. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23544. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  23545. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  23546. super( geometry, material );
  23547. this.type = 'SkeletonHelper';
  23548. this.isSkeletonHelper = true;
  23549. this.root = object;
  23550. this.bones = bones;
  23551. this.matrix = object.matrixWorld;
  23552. this.matrixAutoUpdate = false;
  23553. }
  23554. updateMatrixWorld( force ) {
  23555. const bones = this.bones;
  23556. const geometry = this.geometry;
  23557. const position = geometry.getAttribute( 'position' );
  23558. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  23559. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  23560. const bone = bones[ i ];
  23561. if ( bone.parent && bone.parent.isBone ) {
  23562. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  23563. _vector$2.setFromMatrixPosition( _boneMatrix );
  23564. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  23565. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  23566. _vector$2.setFromMatrixPosition( _boneMatrix );
  23567. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  23568. j += 2;
  23569. }
  23570. }
  23571. geometry.getAttribute( 'position' ).needsUpdate = true;
  23572. super.updateMatrixWorld( force );
  23573. }
  23574. }
  23575. function getBoneList( object ) {
  23576. const boneList = [];
  23577. if ( object && object.isBone ) {
  23578. boneList.push( object );
  23579. }
  23580. for ( let i = 0; i < object.children.length; i ++ ) {
  23581. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  23582. }
  23583. return boneList;
  23584. }
  23585. class GridHelper extends LineSegments {
  23586. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  23587. color1 = new Color( color1 );
  23588. color2 = new Color( color2 );
  23589. const center = divisions / 2;
  23590. const step = size / divisions;
  23591. const halfSize = size / 2;
  23592. const vertices = [], colors = [];
  23593. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  23594. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  23595. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  23596. const color = i === center ? color1 : color2;
  23597. color.toArray( colors, j ); j += 3;
  23598. color.toArray( colors, j ); j += 3;
  23599. color.toArray( colors, j ); j += 3;
  23600. color.toArray( colors, j ); j += 3;
  23601. }
  23602. const geometry = new BufferGeometry();
  23603. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23604. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  23605. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  23606. super( geometry, material );
  23607. this.type = 'GridHelper';
  23608. }
  23609. }
  23610. const _floatView = new Float32Array( 1 );
  23611. new Int32Array( _floatView.buffer );
  23612. const backgroundMaterial = new MeshBasicMaterial( {
  23613. side: BackSide,
  23614. depthWrite: false,
  23615. depthTest: false,
  23616. } );
  23617. new Mesh( new BoxGeometry(), backgroundMaterial );
  23618. //
  23619. Curve.create = function ( construct, getPoint ) {
  23620. console.log( 'THREE.Curve.create() has been deprecated' );
  23621. construct.prototype = Object.create( Curve.prototype );
  23622. construct.prototype.constructor = construct;
  23623. construct.prototype.getPoint = getPoint;
  23624. return construct;
  23625. };
  23626. //
  23627. Path.prototype.fromPoints = function ( points ) {
  23628. console.warn( 'THREE.Path: .fromPoints() has been renamed to .setFromPoints().' );
  23629. return this.setFromPoints( points );
  23630. };
  23631. GridHelper.prototype.setColors = function () {
  23632. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  23633. };
  23634. SkeletonHelper.prototype.update = function () {
  23635. console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' );
  23636. };
  23637. //
  23638. Loader.prototype.extractUrlBase = function ( url ) {
  23639. console.warn( 'THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.' );
  23640. return LoaderUtils.extractUrlBase( url );
  23641. };
  23642. Loader.Handlers = {
  23643. add: function ( /* regex, loader */ ) {
  23644. console.error( 'THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.' );
  23645. },
  23646. get: function ( /* file */ ) {
  23647. console.error( 'THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.' );
  23648. }
  23649. };
  23650. //
  23651. Box3.prototype.center = function ( optionalTarget ) {
  23652. console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
  23653. return this.getCenter( optionalTarget );
  23654. };
  23655. Box3.prototype.empty = function () {
  23656. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  23657. return this.isEmpty();
  23658. };
  23659. Box3.prototype.isIntersectionBox = function ( box ) {
  23660. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  23661. return this.intersectsBox( box );
  23662. };
  23663. Box3.prototype.isIntersectionSphere = function ( sphere ) {
  23664. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  23665. return this.intersectsSphere( sphere );
  23666. };
  23667. Box3.prototype.size = function ( optionalTarget ) {
  23668. console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
  23669. return this.getSize( optionalTarget );
  23670. };
  23671. //
  23672. Sphere.prototype.empty = function () {
  23673. console.warn( 'THREE.Sphere: .empty() has been renamed to .isEmpty().' );
  23674. return this.isEmpty();
  23675. };
  23676. //
  23677. Frustum.prototype.setFromMatrix = function ( m ) {
  23678. console.warn( 'THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().' );
  23679. return this.setFromProjectionMatrix( m );
  23680. };
  23681. //
  23682. Matrix3.prototype.flattenToArrayOffset = function ( array, offset ) {
  23683. console.warn( 'THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.' );
  23684. return this.toArray( array, offset );
  23685. };
  23686. Matrix3.prototype.multiplyVector3 = function ( vector ) {
  23687. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  23688. return vector.applyMatrix3( this );
  23689. };
  23690. Matrix3.prototype.multiplyVector3Array = function ( /* a */ ) {
  23691. console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' );
  23692. };
  23693. Matrix3.prototype.applyToBufferAttribute = function ( attribute ) {
  23694. console.warn( 'THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.' );
  23695. return attribute.applyMatrix3( this );
  23696. };
  23697. Matrix3.prototype.applyToVector3Array = function ( /* array, offset, length */ ) {
  23698. console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' );
  23699. };
  23700. Matrix3.prototype.getInverse = function ( matrix ) {
  23701. console.warn( 'THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.' );
  23702. return this.copy( matrix ).invert();
  23703. };
  23704. //
  23705. Matrix4.prototype.extractPosition = function ( m ) {
  23706. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  23707. return this.copyPosition( m );
  23708. };
  23709. Matrix4.prototype.flattenToArrayOffset = function ( array, offset ) {
  23710. console.warn( 'THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.' );
  23711. return this.toArray( array, offset );
  23712. };
  23713. Matrix4.prototype.getPosition = function () {
  23714. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  23715. return new Vector3().setFromMatrixColumn( this, 3 );
  23716. };
  23717. Matrix4.prototype.setRotationFromQuaternion = function ( q ) {
  23718. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  23719. return this.makeRotationFromQuaternion( q );
  23720. };
  23721. Matrix4.prototype.multiplyToArray = function () {
  23722. console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' );
  23723. };
  23724. Matrix4.prototype.multiplyVector3 = function ( vector ) {
  23725. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  23726. return vector.applyMatrix4( this );
  23727. };
  23728. Matrix4.prototype.multiplyVector4 = function ( vector ) {
  23729. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  23730. return vector.applyMatrix4( this );
  23731. };
  23732. Matrix4.prototype.multiplyVector3Array = function ( /* a */ ) {
  23733. console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' );
  23734. };
  23735. Matrix4.prototype.rotateAxis = function ( v ) {
  23736. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  23737. v.transformDirection( this );
  23738. };
  23739. Matrix4.prototype.crossVector = function ( vector ) {
  23740. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  23741. return vector.applyMatrix4( this );
  23742. };
  23743. Matrix4.prototype.translate = function () {
  23744. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  23745. };
  23746. Matrix4.prototype.rotateX = function () {
  23747. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  23748. };
  23749. Matrix4.prototype.rotateY = function () {
  23750. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  23751. };
  23752. Matrix4.prototype.rotateZ = function () {
  23753. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  23754. };
  23755. Matrix4.prototype.rotateByAxis = function () {
  23756. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  23757. };
  23758. Matrix4.prototype.applyToBufferAttribute = function ( attribute ) {
  23759. console.warn( 'THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.' );
  23760. return attribute.applyMatrix4( this );
  23761. };
  23762. Matrix4.prototype.applyToVector3Array = function ( /* array, offset, length */ ) {
  23763. console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' );
  23764. };
  23765. Matrix4.prototype.makeFrustum = function ( left, right, bottom, top, near, far ) {
  23766. console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' );
  23767. return this.makePerspective( left, right, top, bottom, near, far );
  23768. };
  23769. Matrix4.prototype.getInverse = function ( matrix ) {
  23770. console.warn( 'THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.' );
  23771. return this.copy( matrix ).invert();
  23772. };
  23773. //
  23774. Plane.prototype.isIntersectionLine = function ( line ) {
  23775. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  23776. return this.intersectsLine( line );
  23777. };
  23778. //
  23779. Quaternion.prototype.multiplyVector3 = function ( vector ) {
  23780. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  23781. return vector.applyQuaternion( this );
  23782. };
  23783. Quaternion.prototype.inverse = function ( ) {
  23784. console.warn( 'THREE.Quaternion: .inverse() has been renamed to invert().' );
  23785. return this.invert();
  23786. };
  23787. //
  23788. Ray.prototype.isIntersectionBox = function ( box ) {
  23789. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  23790. return this.intersectsBox( box );
  23791. };
  23792. Ray.prototype.isIntersectionPlane = function ( plane ) {
  23793. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  23794. return this.intersectsPlane( plane );
  23795. };
  23796. Ray.prototype.isIntersectionSphere = function ( sphere ) {
  23797. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  23798. return this.intersectsSphere( sphere );
  23799. };
  23800. //
  23801. Triangle.prototype.area = function () {
  23802. console.warn( 'THREE.Triangle: .area() has been renamed to .getArea().' );
  23803. return this.getArea();
  23804. };
  23805. Triangle.prototype.barycoordFromPoint = function ( point, target ) {
  23806. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  23807. return this.getBarycoord( point, target );
  23808. };
  23809. Triangle.prototype.midpoint = function ( target ) {
  23810. console.warn( 'THREE.Triangle: .midpoint() has been renamed to .getMidpoint().' );
  23811. return this.getMidpoint( target );
  23812. };
  23813. Triangle.prototypenormal = function ( target ) {
  23814. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  23815. return this.getNormal( target );
  23816. };
  23817. Triangle.prototype.plane = function ( target ) {
  23818. console.warn( 'THREE.Triangle: .plane() has been renamed to .getPlane().' );
  23819. return this.getPlane( target );
  23820. };
  23821. Triangle.barycoordFromPoint = function ( point, a, b, c, target ) {
  23822. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  23823. return Triangle.getBarycoord( point, a, b, c, target );
  23824. };
  23825. Triangle.normal = function ( a, b, c, target ) {
  23826. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  23827. return Triangle.getNormal( a, b, c, target );
  23828. };
  23829. //
  23830. Shape.prototype.extractAllPoints = function ( divisions ) {
  23831. console.warn( 'THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.' );
  23832. return this.extractPoints( divisions );
  23833. };
  23834. Shape.prototype.extrude = function ( options ) {
  23835. console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
  23836. return new ExtrudeGeometry( this, options );
  23837. };
  23838. Shape.prototype.makeGeometry = function ( options ) {
  23839. console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
  23840. return new ShapeGeometry( this, options );
  23841. };
  23842. //
  23843. Vector2.prototype.fromAttribute = function ( attribute, index, offset ) {
  23844. console.warn( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  23845. return this.fromBufferAttribute( attribute, index, offset );
  23846. };
  23847. Vector2.prototype.distanceToManhattan = function ( v ) {
  23848. console.warn( 'THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  23849. return this.manhattanDistanceTo( v );
  23850. };
  23851. Vector2.prototype.lengthManhattan = function () {
  23852. console.warn( 'THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().' );
  23853. return this.manhattanLength();
  23854. };
  23855. //
  23856. Vector3.prototype.setEulerFromRotationMatrix = function () {
  23857. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  23858. };
  23859. Vector3.prototype.setEulerFromQuaternion = function () {
  23860. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  23861. };
  23862. Vector3.prototype.getPositionFromMatrix = function ( m ) {
  23863. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  23864. return this.setFromMatrixPosition( m );
  23865. };
  23866. Vector3.prototype.getScaleFromMatrix = function ( m ) {
  23867. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  23868. return this.setFromMatrixScale( m );
  23869. };
  23870. Vector3.prototype.getColumnFromMatrix = function ( index, matrix ) {
  23871. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  23872. return this.setFromMatrixColumn( matrix, index );
  23873. };
  23874. Vector3.prototype.applyProjection = function ( m ) {
  23875. console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' );
  23876. return this.applyMatrix4( m );
  23877. };
  23878. Vector3.prototype.fromAttribute = function ( attribute, index, offset ) {
  23879. console.warn( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  23880. return this.fromBufferAttribute( attribute, index, offset );
  23881. };
  23882. Vector3.prototype.distanceToManhattan = function ( v ) {
  23883. console.warn( 'THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  23884. return this.manhattanDistanceTo( v );
  23885. };
  23886. Vector3.prototype.lengthManhattan = function () {
  23887. console.warn( 'THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().' );
  23888. return this.manhattanLength();
  23889. };
  23890. //
  23891. Vector4.prototype.fromAttribute = function ( attribute, index, offset ) {
  23892. console.warn( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  23893. return this.fromBufferAttribute( attribute, index, offset );
  23894. };
  23895. Vector4.prototype.lengthManhattan = function () {
  23896. console.warn( 'THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().' );
  23897. return this.manhattanLength();
  23898. };
  23899. //
  23900. Object3D.prototype.getChildByName = function ( name ) {
  23901. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  23902. return this.getObjectByName( name );
  23903. };
  23904. Object3D.prototype.renderDepth = function () {
  23905. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  23906. };
  23907. Object3D.prototype.translate = function ( distance, axis ) {
  23908. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  23909. return this.translateOnAxis( axis, distance );
  23910. };
  23911. Object3D.prototype.getWorldRotation = function () {
  23912. console.error( 'THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.' );
  23913. };
  23914. Object3D.prototype.applyMatrix = function ( matrix ) {
  23915. console.warn( 'THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().' );
  23916. return this.applyMatrix4( matrix );
  23917. };
  23918. Object.defineProperties( Object3D.prototype, {
  23919. eulerOrder: {
  23920. get: function () {
  23921. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  23922. return this.rotation.order;
  23923. },
  23924. set: function ( value ) {
  23925. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  23926. this.rotation.order = value;
  23927. }
  23928. },
  23929. useQuaternion: {
  23930. get: function () {
  23931. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  23932. },
  23933. set: function () {
  23934. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  23935. }
  23936. }
  23937. } );
  23938. Mesh.prototype.setDrawMode = function () {
  23939. console.error( 'THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' );
  23940. };
  23941. Object.defineProperties( Mesh.prototype, {
  23942. drawMode: {
  23943. get: function () {
  23944. console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.' );
  23945. return TrianglesDrawMode;
  23946. },
  23947. set: function () {
  23948. console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' );
  23949. }
  23950. }
  23951. } );
  23952. SkinnedMesh.prototype.initBones = function () {
  23953. console.error( 'THREE.SkinnedMesh: initBones() has been removed.' );
  23954. };
  23955. //
  23956. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  23957. console.warn( 'THREE.PerspectiveCamera.setLens is deprecated. ' +
  23958. 'Use .setFocalLength and .filmGauge for a photographic setup.' );
  23959. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  23960. this.setFocalLength( focalLength );
  23961. };
  23962. //
  23963. Object.defineProperties( Light.prototype, {
  23964. onlyShadow: {
  23965. set: function () {
  23966. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  23967. }
  23968. },
  23969. shadowCameraFov: {
  23970. set: function ( value ) {
  23971. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  23972. this.shadow.camera.fov = value;
  23973. }
  23974. },
  23975. shadowCameraLeft: {
  23976. set: function ( value ) {
  23977. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  23978. this.shadow.camera.left = value;
  23979. }
  23980. },
  23981. shadowCameraRight: {
  23982. set: function ( value ) {
  23983. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  23984. this.shadow.camera.right = value;
  23985. }
  23986. },
  23987. shadowCameraTop: {
  23988. set: function ( value ) {
  23989. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  23990. this.shadow.camera.top = value;
  23991. }
  23992. },
  23993. shadowCameraBottom: {
  23994. set: function ( value ) {
  23995. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  23996. this.shadow.camera.bottom = value;
  23997. }
  23998. },
  23999. shadowCameraNear: {
  24000. set: function ( value ) {
  24001. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  24002. this.shadow.camera.near = value;
  24003. }
  24004. },
  24005. shadowCameraFar: {
  24006. set: function ( value ) {
  24007. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  24008. this.shadow.camera.far = value;
  24009. }
  24010. },
  24011. shadowCameraVisible: {
  24012. set: function () {
  24013. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  24014. }
  24015. },
  24016. shadowBias: {
  24017. set: function ( value ) {
  24018. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  24019. this.shadow.bias = value;
  24020. }
  24021. },
  24022. shadowDarkness: {
  24023. set: function () {
  24024. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  24025. }
  24026. },
  24027. shadowMapWidth: {
  24028. set: function ( value ) {
  24029. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  24030. this.shadow.mapSize.width = value;
  24031. }
  24032. },
  24033. shadowMapHeight: {
  24034. set: function ( value ) {
  24035. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  24036. this.shadow.mapSize.height = value;
  24037. }
  24038. }
  24039. } );
  24040. //
  24041. Object.defineProperties( BufferAttribute.prototype, {
  24042. length: {
  24043. get: function () {
  24044. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
  24045. return this.array.length;
  24046. }
  24047. },
  24048. dynamic: {
  24049. get: function () {
  24050. console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' );
  24051. return this.usage === DynamicDrawUsage;
  24052. },
  24053. set: function ( /* value */ ) {
  24054. console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' );
  24055. this.setUsage( DynamicDrawUsage );
  24056. }
  24057. }
  24058. } );
  24059. BufferAttribute.prototype.setDynamic = function ( value ) {
  24060. console.warn( 'THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.' );
  24061. this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage );
  24062. return this;
  24063. };
  24064. BufferAttribute.prototype.copyIndicesArray = function ( /* indices */ ) {
  24065. console.error( 'THREE.BufferAttribute: .copyIndicesArray() has been removed.' );
  24066. },
  24067. BufferAttribute.prototype.setArray = function ( /* array */ ) {
  24068. console.error( 'THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );
  24069. };
  24070. //
  24071. BufferGeometry.prototype.addIndex = function ( index ) {
  24072. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  24073. this.setIndex( index );
  24074. };
  24075. BufferGeometry.prototype.addAttribute = function ( name, attribute ) {
  24076. console.warn( 'THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().' );
  24077. if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) {
  24078. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  24079. return this.setAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  24080. }
  24081. if ( name === 'index' ) {
  24082. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  24083. this.setIndex( attribute );
  24084. return this;
  24085. }
  24086. return this.setAttribute( name, attribute );
  24087. };
  24088. BufferGeometry.prototype.addDrawCall = function ( start, count, indexOffset ) {
  24089. if ( indexOffset !== undefined ) {
  24090. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  24091. }
  24092. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  24093. this.addGroup( start, count );
  24094. };
  24095. BufferGeometry.prototype.clearDrawCalls = function () {
  24096. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  24097. this.clearGroups();
  24098. };
  24099. BufferGeometry.prototype.computeOffsets = function () {
  24100. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  24101. };
  24102. BufferGeometry.prototype.removeAttribute = function ( name ) {
  24103. console.warn( 'THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().' );
  24104. return this.deleteAttribute( name );
  24105. };
  24106. BufferGeometry.prototype.applyMatrix = function ( matrix ) {
  24107. console.warn( 'THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().' );
  24108. return this.applyMatrix4( matrix );
  24109. };
  24110. Object.defineProperties( BufferGeometry.prototype, {
  24111. drawcalls: {
  24112. get: function () {
  24113. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  24114. return this.groups;
  24115. }
  24116. },
  24117. offsets: {
  24118. get: function () {
  24119. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  24120. return this.groups;
  24121. }
  24122. }
  24123. } );
  24124. InterleavedBuffer.prototype.setDynamic = function ( value ) {
  24125. console.warn( 'THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.' );
  24126. this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage );
  24127. return this;
  24128. };
  24129. InterleavedBuffer.prototype.setArray = function ( /* array */ ) {
  24130. console.error( 'THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );
  24131. };
  24132. //
  24133. ExtrudeGeometry.prototype.getArrays = function () {
  24134. console.error( 'THREE.ExtrudeGeometry: .getArrays() has been removed.' );
  24135. };
  24136. ExtrudeGeometry.prototype.addShapeList = function () {
  24137. console.error( 'THREE.ExtrudeGeometry: .addShapeList() has been removed.' );
  24138. };
  24139. ExtrudeGeometry.prototype.addShape = function () {
  24140. console.error( 'THREE.ExtrudeGeometry: .addShape() has been removed.' );
  24141. };
  24142. //
  24143. Scene.prototype.dispose = function () {
  24144. console.error( 'THREE.Scene: .dispose() has been removed.' );
  24145. };
  24146. //
  24147. Object.defineProperties( Material.prototype, {
  24148. wrapAround: {
  24149. get: function () {
  24150. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  24151. },
  24152. set: function () {
  24153. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  24154. }
  24155. },
  24156. overdraw: {
  24157. get: function () {
  24158. console.warn( 'THREE.Material: .overdraw has been removed.' );
  24159. },
  24160. set: function () {
  24161. console.warn( 'THREE.Material: .overdraw has been removed.' );
  24162. }
  24163. },
  24164. wrapRGB: {
  24165. get: function () {
  24166. console.warn( 'THREE.Material: .wrapRGB has been removed.' );
  24167. return new Color();
  24168. }
  24169. },
  24170. shading: {
  24171. get: function () {
  24172. console.error( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  24173. },
  24174. set: function ( value ) {
  24175. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  24176. this.flatShading = ( value === FlatShading );
  24177. }
  24178. },
  24179. stencilMask: {
  24180. get: function () {
  24181. console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
  24182. return this.stencilFuncMask;
  24183. },
  24184. set: function ( value ) {
  24185. console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
  24186. this.stencilFuncMask = value;
  24187. }
  24188. }
  24189. } );
  24190. Object.defineProperties( ShaderMaterial.prototype, {
  24191. derivatives: {
  24192. get: function () {
  24193. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  24194. return this.extensions.derivatives;
  24195. },
  24196. set: function ( value ) {
  24197. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  24198. this.extensions.derivatives = value;
  24199. }
  24200. }
  24201. } );
  24202. //
  24203. WebGLRenderer.prototype.clearTarget = function ( renderTarget, color, depth, stencil ) {
  24204. console.warn( 'THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.' );
  24205. this.setRenderTarget( renderTarget );
  24206. this.clear( color, depth, stencil );
  24207. };
  24208. WebGLRenderer.prototype.animate = function ( callback ) {
  24209. console.warn( 'THREE.WebGLRenderer: .animate() is now .setAnimationLoop().' );
  24210. this.setAnimationLoop( callback );
  24211. };
  24212. WebGLRenderer.prototype.getCurrentRenderTarget = function () {
  24213. console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' );
  24214. return this.getRenderTarget();
  24215. };
  24216. WebGLRenderer.prototype.getMaxAnisotropy = function () {
  24217. console.warn( 'THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().' );
  24218. return this.capabilities.getMaxAnisotropy();
  24219. };
  24220. WebGLRenderer.prototype.getPrecision = function () {
  24221. console.warn( 'THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.' );
  24222. return this.capabilities.precision;
  24223. };
  24224. WebGLRenderer.prototype.resetGLState = function () {
  24225. console.warn( 'THREE.WebGLRenderer: .resetGLState() is now .state.reset().' );
  24226. return this.state.reset();
  24227. };
  24228. WebGLRenderer.prototype.supportsFloatTextures = function () {
  24229. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  24230. return this.extensions.get( 'OES_texture_float' );
  24231. };
  24232. WebGLRenderer.prototype.supportsHalfFloatTextures = function () {
  24233. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  24234. return this.extensions.get( 'OES_texture_half_float' );
  24235. };
  24236. WebGLRenderer.prototype.supportsStandardDerivatives = function () {
  24237. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  24238. return this.extensions.get( 'OES_standard_derivatives' );
  24239. };
  24240. WebGLRenderer.prototype.supportsCompressedTextureS3TC = function () {
  24241. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  24242. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  24243. };
  24244. WebGLRenderer.prototype.supportsCompressedTexturePVRTC = function () {
  24245. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  24246. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  24247. };
  24248. WebGLRenderer.prototype.supportsBlendMinMax = function () {
  24249. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  24250. return this.extensions.get( 'EXT_blend_minmax' );
  24251. };
  24252. WebGLRenderer.prototype.supportsVertexTextures = function () {
  24253. console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
  24254. return this.capabilities.vertexTextures;
  24255. };
  24256. WebGLRenderer.prototype.supportsInstancedArrays = function () {
  24257. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  24258. return this.extensions.get( 'ANGLE_instanced_arrays' );
  24259. };
  24260. WebGLRenderer.prototype.enableScissorTest = function ( boolean ) {
  24261. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  24262. this.setScissorTest( boolean );
  24263. };
  24264. WebGLRenderer.prototype.initMaterial = function () {
  24265. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  24266. };
  24267. WebGLRenderer.prototype.addPrePlugin = function () {
  24268. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  24269. };
  24270. WebGLRenderer.prototype.addPostPlugin = function () {
  24271. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  24272. };
  24273. WebGLRenderer.prototype.updateShadowMap = function () {
  24274. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  24275. };
  24276. WebGLRenderer.prototype.setFaceCulling = function () {
  24277. console.warn( 'THREE.WebGLRenderer: .setFaceCulling() has been removed.' );
  24278. };
  24279. WebGLRenderer.prototype.allocTextureUnit = function () {
  24280. console.warn( 'THREE.WebGLRenderer: .allocTextureUnit() has been removed.' );
  24281. };
  24282. WebGLRenderer.prototype.setTexture = function () {
  24283. console.warn( 'THREE.WebGLRenderer: .setTexture() has been removed.' );
  24284. };
  24285. WebGLRenderer.prototype.setTexture2D = function () {
  24286. console.warn( 'THREE.WebGLRenderer: .setTexture2D() has been removed.' );
  24287. };
  24288. WebGLRenderer.prototype.setTextureCube = function () {
  24289. console.warn( 'THREE.WebGLRenderer: .setTextureCube() has been removed.' );
  24290. };
  24291. WebGLRenderer.prototype.getActiveMipMapLevel = function () {
  24292. console.warn( 'THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().' );
  24293. return this.getActiveMipmapLevel();
  24294. };
  24295. Object.defineProperties( WebGLRenderer.prototype, {
  24296. shadowMapEnabled: {
  24297. get: function () {
  24298. return this.shadowMap.enabled;
  24299. },
  24300. set: function ( value ) {
  24301. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  24302. this.shadowMap.enabled = value;
  24303. }
  24304. },
  24305. shadowMapType: {
  24306. get: function () {
  24307. return this.shadowMap.type;
  24308. },
  24309. set: function ( value ) {
  24310. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  24311. this.shadowMap.type = value;
  24312. }
  24313. },
  24314. shadowMapCullFace: {
  24315. get: function () {
  24316. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  24317. return undefined;
  24318. },
  24319. set: function ( /* value */ ) {
  24320. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  24321. }
  24322. },
  24323. context: {
  24324. get: function () {
  24325. console.warn( 'THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.' );
  24326. return this.getContext();
  24327. }
  24328. },
  24329. vr: {
  24330. get: function () {
  24331. console.warn( 'THREE.WebGLRenderer: .vr has been renamed to .xr' );
  24332. return this.xr;
  24333. }
  24334. },
  24335. gammaInput: {
  24336. get: function () {
  24337. console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' );
  24338. return false;
  24339. },
  24340. set: function () {
  24341. console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' );
  24342. }
  24343. },
  24344. gammaOutput: {
  24345. get: function () {
  24346. console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' );
  24347. return false;
  24348. },
  24349. set: function ( value ) {
  24350. console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' );
  24351. this.outputEncoding = ( value === true ) ? sRGBEncoding : LinearEncoding;
  24352. }
  24353. },
  24354. toneMappingWhitePoint: {
  24355. get: function () {
  24356. console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' );
  24357. return 1.0;
  24358. },
  24359. set: function () {
  24360. console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' );
  24361. }
  24362. },
  24363. } );
  24364. Object.defineProperties( WebGLShadowMap.prototype, {
  24365. cullFace: {
  24366. get: function () {
  24367. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  24368. return undefined;
  24369. },
  24370. set: function ( /* cullFace */ ) {
  24371. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  24372. }
  24373. },
  24374. renderReverseSided: {
  24375. get: function () {
  24376. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  24377. return undefined;
  24378. },
  24379. set: function () {
  24380. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  24381. }
  24382. },
  24383. renderSingleSided: {
  24384. get: function () {
  24385. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  24386. return undefined;
  24387. },
  24388. set: function () {
  24389. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  24390. }
  24391. }
  24392. } );
  24393. //
  24394. Object.defineProperties( WebGLRenderTarget.prototype, {
  24395. wrapS: {
  24396. get: function () {
  24397. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  24398. return this.texture.wrapS;
  24399. },
  24400. set: function ( value ) {
  24401. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  24402. this.texture.wrapS = value;
  24403. }
  24404. },
  24405. wrapT: {
  24406. get: function () {
  24407. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  24408. return this.texture.wrapT;
  24409. },
  24410. set: function ( value ) {
  24411. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  24412. this.texture.wrapT = value;
  24413. }
  24414. },
  24415. magFilter: {
  24416. get: function () {
  24417. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  24418. return this.texture.magFilter;
  24419. },
  24420. set: function ( value ) {
  24421. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  24422. this.texture.magFilter = value;
  24423. }
  24424. },
  24425. minFilter: {
  24426. get: function () {
  24427. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  24428. return this.texture.minFilter;
  24429. },
  24430. set: function ( value ) {
  24431. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  24432. this.texture.minFilter = value;
  24433. }
  24434. },
  24435. anisotropy: {
  24436. get: function () {
  24437. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  24438. return this.texture.anisotropy;
  24439. },
  24440. set: function ( value ) {
  24441. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  24442. this.texture.anisotropy = value;
  24443. }
  24444. },
  24445. offset: {
  24446. get: function () {
  24447. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  24448. return this.texture.offset;
  24449. },
  24450. set: function ( value ) {
  24451. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  24452. this.texture.offset = value;
  24453. }
  24454. },
  24455. repeat: {
  24456. get: function () {
  24457. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  24458. return this.texture.repeat;
  24459. },
  24460. set: function ( value ) {
  24461. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  24462. this.texture.repeat = value;
  24463. }
  24464. },
  24465. format: {
  24466. get: function () {
  24467. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  24468. return this.texture.format;
  24469. },
  24470. set: function ( value ) {
  24471. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  24472. this.texture.format = value;
  24473. }
  24474. },
  24475. type: {
  24476. get: function () {
  24477. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  24478. return this.texture.type;
  24479. },
  24480. set: function ( value ) {
  24481. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  24482. this.texture.type = value;
  24483. }
  24484. },
  24485. generateMipmaps: {
  24486. get: function () {
  24487. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  24488. return this.texture.generateMipmaps;
  24489. },
  24490. set: function ( value ) {
  24491. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  24492. this.texture.generateMipmaps = value;
  24493. }
  24494. }
  24495. } );
  24496. //
  24497. Audio.prototype.load = function ( file ) {
  24498. console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
  24499. const scope = this;
  24500. const audioLoader = new AudioLoader();
  24501. audioLoader.load( file, function ( buffer ) {
  24502. scope.setBuffer( buffer );
  24503. } );
  24504. return this;
  24505. };
  24506. //
  24507. CubeCamera.prototype.updateCubeMap = function ( renderer, scene ) {
  24508. console.warn( 'THREE.CubeCamera: .updateCubeMap() is now .update().' );
  24509. return this.update( renderer, scene );
  24510. };
  24511. CubeCamera.prototype.clear = function ( renderer, color, depth, stencil ) {
  24512. console.warn( 'THREE.CubeCamera: .clear() is now .renderTarget.clear().' );
  24513. return this.renderTarget.clear( renderer, color, depth, stencil );
  24514. };
  24515. ImageUtils.crossOrigin = undefined;
  24516. ImageUtils.loadTexture = function ( url, mapping, onLoad, onError ) {
  24517. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  24518. const loader = new TextureLoader();
  24519. loader.setCrossOrigin( this.crossOrigin );
  24520. const texture = loader.load( url, onLoad, undefined, onError );
  24521. if ( mapping ) texture.mapping = mapping;
  24522. return texture;
  24523. };
  24524. ImageUtils.loadTextureCube = function ( urls, mapping, onLoad, onError ) {
  24525. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  24526. const loader = new CubeTextureLoader();
  24527. loader.setCrossOrigin( this.crossOrigin );
  24528. const texture = loader.load( urls, onLoad, undefined, onError );
  24529. if ( mapping ) texture.mapping = mapping;
  24530. return texture;
  24531. };
  24532. ImageUtils.loadCompressedTexture = function () {
  24533. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  24534. };
  24535. ImageUtils.loadCompressedTextureCube = function () {
  24536. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  24537. };
  24538. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  24539. /* eslint-disable no-undef */
  24540. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  24541. revision: REVISION,
  24542. } } ) );
  24543. /* eslint-enable no-undef */
  24544. }
  24545. if ( typeof window !== 'undefined' ) {
  24546. if ( window.__THREE__ ) {
  24547. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  24548. } else {
  24549. window.__THREE__ = REVISION;
  24550. }
  24551. }
  24552. const _plane = new Plane();
  24553. const _raycaster = new Raycaster();
  24554. const _pointer = new Vector2();
  24555. const _offset = new Vector3();
  24556. const _intersection = new Vector3();
  24557. const _worldPosition = new Vector3();
  24558. const _inverseMatrix = new Matrix4();
  24559. class DragControls extends EventDispatcher {
  24560. constructor( _objects, _camera, _domElement ) {
  24561. super();
  24562. _domElement.style.touchAction = 'none'; // disable touch scroll
  24563. let _selected = null, _hovered = null;
  24564. const _intersections = [];
  24565. //
  24566. const scope = this;
  24567. function activate() {
  24568. _domElement.addEventListener( 'pointermove', onPointerMove );
  24569. _domElement.addEventListener( 'pointerdown', onPointerDown );
  24570. _domElement.addEventListener( 'pointerup', onPointerCancel );
  24571. _domElement.addEventListener( 'pointerleave', onPointerCancel );
  24572. }
  24573. function deactivate() {
  24574. _domElement.removeEventListener( 'pointermove', onPointerMove );
  24575. _domElement.removeEventListener( 'pointerdown', onPointerDown );
  24576. _domElement.removeEventListener( 'pointerup', onPointerCancel );
  24577. _domElement.removeEventListener( 'pointerleave', onPointerCancel );
  24578. _domElement.style.cursor = '';
  24579. }
  24580. function dispose() {
  24581. deactivate();
  24582. }
  24583. function getObjects() {
  24584. return _objects;
  24585. }
  24586. function onPointerMove( event ) {
  24587. if ( scope.enabled === false ) return;
  24588. updatePointer( event );
  24589. _raycaster.setFromCamera( _pointer, _camera );
  24590. if ( _selected ) {
  24591. if ( _raycaster.ray.intersectPlane( _plane, _intersection ) ) {
  24592. _selected.position.copy( _intersection.sub( _offset ).applyMatrix4( _inverseMatrix ) );
  24593. }
  24594. scope.dispatchEvent( { type: 'drag', object: _selected } );
  24595. return;
  24596. }
  24597. // hover support
  24598. if ( event.pointerType === 'mouse' || event.pointerType === 'pen' ) {
  24599. _intersections.length = 0;
  24600. _raycaster.setFromCamera( _pointer, _camera );
  24601. _raycaster.intersectObjects( _objects, true, _intersections );
  24602. if ( _intersections.length > 0 ) {
  24603. const object = _intersections[ 0 ].object;
  24604. _plane.setFromNormalAndCoplanarPoint( _camera.getWorldDirection( _plane.normal ), _worldPosition.setFromMatrixPosition( object.matrixWorld ) );
  24605. if ( _hovered !== object && _hovered !== null ) {
  24606. scope.dispatchEvent( { type: 'hoveroff', object: _hovered } );
  24607. _domElement.style.cursor = 'auto';
  24608. _hovered = null;
  24609. }
  24610. if ( _hovered !== object ) {
  24611. scope.dispatchEvent( { type: 'hoveron', object: object } );
  24612. _domElement.style.cursor = 'pointer';
  24613. _hovered = object;
  24614. }
  24615. } else {
  24616. if ( _hovered !== null ) {
  24617. scope.dispatchEvent( { type: 'hoveroff', object: _hovered } );
  24618. _domElement.style.cursor = 'auto';
  24619. _hovered = null;
  24620. }
  24621. }
  24622. }
  24623. }
  24624. function onPointerDown( event ) {
  24625. if ( scope.enabled === false ) return;
  24626. updatePointer( event );
  24627. _intersections.length = 0;
  24628. _raycaster.setFromCamera( _pointer, _camera );
  24629. _raycaster.intersectObjects( _objects, true, _intersections );
  24630. if ( _intersections.length > 0 ) {
  24631. _selected = ( scope.transformGroup === true ) ? _objects[ 0 ] : _intersections[ 0 ].object;
  24632. _plane.setFromNormalAndCoplanarPoint( _camera.getWorldDirection( _plane.normal ), _worldPosition.setFromMatrixPosition( _selected.matrixWorld ) );
  24633. if ( _raycaster.ray.intersectPlane( _plane, _intersection ) ) {
  24634. _inverseMatrix.copy( _selected.parent.matrixWorld ).invert();
  24635. _offset.copy( _intersection ).sub( _worldPosition.setFromMatrixPosition( _selected.matrixWorld ) );
  24636. }
  24637. _domElement.style.cursor = 'move';
  24638. scope.dispatchEvent( { type: 'dragstart', object: _selected } );
  24639. }
  24640. }
  24641. function onPointerCancel() {
  24642. if ( scope.enabled === false ) return;
  24643. if ( _selected ) {
  24644. scope.dispatchEvent( { type: 'dragend', object: _selected } );
  24645. _selected = null;
  24646. }
  24647. _domElement.style.cursor = _hovered ? 'pointer' : 'auto';
  24648. }
  24649. function updatePointer( event ) {
  24650. const rect = _domElement.getBoundingClientRect();
  24651. _pointer.x = ( event.clientX - rect.left ) / rect.width * 2 - 1;
  24652. _pointer.y = - ( event.clientY - rect.top ) / rect.height * 2 + 1;
  24653. }
  24654. activate();
  24655. // API
  24656. this.enabled = true;
  24657. this.transformGroup = false;
  24658. this.activate = activate;
  24659. this.deactivate = deactivate;
  24660. this.dispose = dispose;
  24661. this.getObjects = getObjects;
  24662. }
  24663. }
  24664. function forceCenter(x, y, z) {
  24665. var nodes, strength = 1;
  24666. if (x == null) x = 0;
  24667. if (y == null) y = 0;
  24668. if (z == null) z = 0;
  24669. function force() {
  24670. var i,
  24671. n = nodes.length,
  24672. node,
  24673. sx = 0,
  24674. sy = 0,
  24675. sz = 0;
  24676. for (i = 0; i < n; ++i) {
  24677. node = nodes[i], sx += node.x || 0, sy += node.y || 0, sz += node.z || 0;
  24678. }
  24679. for (sx = (sx / n - x) * strength, sy = (sy / n - y) * strength, sz = (sz / n - z) * strength, i = 0; i < n; ++i) {
  24680. node = nodes[i];
  24681. if (sx) { node.x -= sx; }
  24682. if (sy) { node.y -= sy; }
  24683. if (sz) { node.z -= sz; }
  24684. }
  24685. }
  24686. force.initialize = function(_) {
  24687. nodes = _;
  24688. };
  24689. force.x = function(_) {
  24690. return arguments.length ? (x = +_, force) : x;
  24691. };
  24692. force.y = function(_) {
  24693. return arguments.length ? (y = +_, force) : y;
  24694. };
  24695. force.z = function(_) {
  24696. return arguments.length ? (z = +_, force) : z;
  24697. };
  24698. force.strength = function(_) {
  24699. return arguments.length ? (strength = +_, force) : strength;
  24700. };
  24701. return force;
  24702. }
  24703. function tree_add$2(d) {
  24704. var x = +this._x.call(null, d);
  24705. return add$3(this.cover(x), x, d);
  24706. }
  24707. function add$3(tree, x, d) {
  24708. if (isNaN(x)) return tree; // ignore invalid points
  24709. var parent,
  24710. node = tree._root,
  24711. leaf = {data: d},
  24712. x0 = tree._x0,
  24713. x1 = tree._x1,
  24714. xm,
  24715. xp,
  24716. right,
  24717. i,
  24718. j;
  24719. // If the tree is empty, initialize the root as a leaf.
  24720. if (!node) return tree._root = leaf, tree;
  24721. // Find the existing leaf for the new point, or add it.
  24722. while (node.length) {
  24723. if (right = x >= (xm = (x0 + x1) / 2)) x0 = xm; else x1 = xm;
  24724. if (parent = node, !(node = node[i = +right])) return parent[i] = leaf, tree;
  24725. }
  24726. // Is the new point is exactly coincident with the existing point?
  24727. xp = +tree._x.call(null, node.data);
  24728. if (x === xp) return leaf.next = node, parent ? parent[i] = leaf : tree._root = leaf, tree;
  24729. // Otherwise, split the leaf node until the old and new point are separated.
  24730. do {
  24731. parent = parent ? parent[i] = new Array(2) : tree._root = new Array(2);
  24732. if (right = x >= (xm = (x0 + x1) / 2)) x0 = xm; else x1 = xm;
  24733. } while ((i = +right) === (j = +(xp >= xm)));
  24734. return parent[j] = node, parent[i] = leaf, tree;
  24735. }
  24736. function addAll$2(data) {
  24737. var i, n = data.length,
  24738. x,
  24739. xz = new Array(n),
  24740. x0 = Infinity,
  24741. x1 = -Infinity;
  24742. // Compute the points and their extent.
  24743. for (i = 0; i < n; ++i) {
  24744. if (isNaN(x = +this._x.call(null, data[i]))) continue;
  24745. xz[i] = x;
  24746. if (x < x0) x0 = x;
  24747. if (x > x1) x1 = x;
  24748. }
  24749. // If there were no (valid) points, abort.
  24750. if (x0 > x1) return this;
  24751. // Expand the tree to cover the new points.
  24752. this.cover(x0).cover(x1);
  24753. // Add the new points.
  24754. for (i = 0; i < n; ++i) {
  24755. add$3(this, xz[i], data[i]);
  24756. }
  24757. return this;
  24758. }
  24759. function tree_cover$2(x) {
  24760. if (isNaN(x = +x)) return this; // ignore invalid points
  24761. var x0 = this._x0,
  24762. x1 = this._x1;
  24763. // If the binarytree has no extent, initialize them.
  24764. // Integer extent are necessary so that if we later double the extent,
  24765. // the existing half boundaries don’t change due to floating point error!
  24766. if (isNaN(x0)) {
  24767. x1 = (x0 = Math.floor(x)) + 1;
  24768. }
  24769. // Otherwise, double repeatedly to cover.
  24770. else {
  24771. var z = x1 - x0 || 1,
  24772. node = this._root,
  24773. parent,
  24774. i;
  24775. while (x0 > x || x >= x1) {
  24776. i = +(x < x0);
  24777. parent = new Array(2), parent[i] = node, node = parent, z *= 2;
  24778. switch (i) {
  24779. case 0: x1 = x0 + z; break;
  24780. case 1: x0 = x1 - z; break;
  24781. }
  24782. }
  24783. if (this._root && this._root.length) this._root = node;
  24784. }
  24785. this._x0 = x0;
  24786. this._x1 = x1;
  24787. return this;
  24788. }
  24789. function tree_data$2() {
  24790. var data = [];
  24791. this.visit(function(node) {
  24792. if (!node.length) do data.push(node.data); while (node = node.next)
  24793. });
  24794. return data;
  24795. }
  24796. function tree_extent$2(_) {
  24797. return arguments.length
  24798. ? this.cover(+_[0][0]).cover(+_[1][0])
  24799. : isNaN(this._x0) ? undefined : [[this._x0], [this._x1]];
  24800. }
  24801. function Half(node, x0, x1) {
  24802. this.node = node;
  24803. this.x0 = x0;
  24804. this.x1 = x1;
  24805. }
  24806. function tree_find$2(x, radius) {
  24807. var data,
  24808. x0 = this._x0,
  24809. x1,
  24810. x2,
  24811. x3 = this._x1,
  24812. halves = [],
  24813. node = this._root,
  24814. q,
  24815. i;
  24816. if (node) halves.push(new Half(node, x0, x3));
  24817. if (radius == null) radius = Infinity;
  24818. else {
  24819. x0 = x - radius;
  24820. x3 = x + radius;
  24821. }
  24822. while (q = halves.pop()) {
  24823. // Stop searching if this half can’t contain a closer node.
  24824. if (!(node = q.node)
  24825. || (x1 = q.x0) > x3
  24826. || (x2 = q.x1) < x0) continue;
  24827. // Bisect the current half.
  24828. if (node.length) {
  24829. var xm = (x1 + x2) / 2;
  24830. halves.push(
  24831. new Half(node[1], xm, x2),
  24832. new Half(node[0], x1, xm)
  24833. );
  24834. // Visit the closest half first.
  24835. if (i = +(x >= xm)) {
  24836. q = halves[halves.length - 1];
  24837. halves[halves.length - 1] = halves[halves.length - 1 - i];
  24838. halves[halves.length - 1 - i] = q;
  24839. }
  24840. }
  24841. // Visit this point. (Visiting coincident points isn’t necessary!)
  24842. else {
  24843. var d = Math.abs(x - +this._x.call(null, node.data));
  24844. if (d < radius) {
  24845. radius = d;
  24846. x0 = x - d;
  24847. x3 = x + d;
  24848. data = node.data;
  24849. }
  24850. }
  24851. }
  24852. return data;
  24853. }
  24854. function tree_remove$2(d) {
  24855. if (isNaN(x = +this._x.call(null, d))) return this; // ignore invalid points
  24856. var parent,
  24857. node = this._root,
  24858. retainer,
  24859. previous,
  24860. next,
  24861. x0 = this._x0,
  24862. x1 = this._x1,
  24863. x,
  24864. xm,
  24865. right,
  24866. i,
  24867. j;
  24868. // If the tree is empty, initialize the root as a leaf.
  24869. if (!node) return this;
  24870. // Find the leaf node for the point.
  24871. // While descending, also retain the deepest parent with a non-removed sibling.
  24872. if (node.length) while (true) {
  24873. if (right = x >= (xm = (x0 + x1) / 2)) x0 = xm; else x1 = xm;
  24874. if (!(parent = node, node = node[i = +right])) return this;
  24875. if (!node.length) break;
  24876. if (parent[(i + 1) & 1]) retainer = parent, j = i;
  24877. }
  24878. // Find the point to remove.
  24879. while (node.data !== d) if (!(previous = node, node = node.next)) return this;
  24880. if (next = node.next) delete node.next;
  24881. // If there are multiple coincident points, remove just the point.
  24882. if (previous) return (next ? previous.next = next : delete previous.next), this;
  24883. // If this is the root point, remove it.
  24884. if (!parent) return this._root = next, this;
  24885. // Remove this leaf.
  24886. next ? parent[i] = next : delete parent[i];
  24887. // If the parent now contains exactly one leaf, collapse superfluous parents.
  24888. if ((node = parent[0] || parent[1])
  24889. && node === (parent[1] || parent[0])
  24890. && !node.length) {
  24891. if (retainer) retainer[j] = node;
  24892. else this._root = node;
  24893. }
  24894. return this;
  24895. }
  24896. function removeAll$3(data) {
  24897. for (var i = 0, n = data.length; i < n; ++i) this.remove(data[i]);
  24898. return this;
  24899. }
  24900. function tree_root$2() {
  24901. return this._root;
  24902. }
  24903. function tree_size$2() {
  24904. var size = 0;
  24905. this.visit(function(node) {
  24906. if (!node.length) do ++size; while (node = node.next)
  24907. });
  24908. return size;
  24909. }
  24910. function tree_visit$2(callback) {
  24911. var halves = [], q, node = this._root, child, x0, x1;
  24912. if (node) halves.push(new Half(node, this._x0, this._x1));
  24913. while (q = halves.pop()) {
  24914. if (!callback(node = q.node, x0 = q.x0, x1 = q.x1) && node.length) {
  24915. var xm = (x0 + x1) / 2;
  24916. if (child = node[1]) halves.push(new Half(child, xm, x1));
  24917. if (child = node[0]) halves.push(new Half(child, x0, xm));
  24918. }
  24919. }
  24920. return this;
  24921. }
  24922. function tree_visitAfter$2(callback) {
  24923. var halves = [], next = [], q;
  24924. if (this._root) halves.push(new Half(this._root, this._x0, this._x1));
  24925. while (q = halves.pop()) {
  24926. var node = q.node;
  24927. if (node.length) {
  24928. var child, x0 = q.x0, x1 = q.x1, xm = (x0 + x1) / 2;
  24929. if (child = node[0]) halves.push(new Half(child, x0, xm));
  24930. if (child = node[1]) halves.push(new Half(child, xm, x1));
  24931. }
  24932. next.push(q);
  24933. }
  24934. while (q = next.pop()) {
  24935. callback(q.node, q.x0, q.x1);
  24936. }
  24937. return this;
  24938. }
  24939. function defaultX$2(d) {
  24940. return d[0];
  24941. }
  24942. function tree_x$2(_) {
  24943. return arguments.length ? (this._x = _, this) : this._x;
  24944. }
  24945. function binarytree(nodes, x) {
  24946. var tree = new Binarytree(x == null ? defaultX$2 : x, NaN, NaN);
  24947. return nodes == null ? tree : tree.addAll(nodes);
  24948. }
  24949. function Binarytree(x, x0, x1) {
  24950. this._x = x;
  24951. this._x0 = x0;
  24952. this._x1 = x1;
  24953. this._root = undefined;
  24954. }
  24955. function leaf_copy$2(leaf) {
  24956. var copy = {data: leaf.data}, next = copy;
  24957. while (leaf = leaf.next) next = next.next = {data: leaf.data};
  24958. return copy;
  24959. }
  24960. var treeProto$2 = binarytree.prototype = Binarytree.prototype;
  24961. treeProto$2.copy = function() {
  24962. var copy = new Binarytree(this._x, this._x0, this._x1),
  24963. node = this._root,
  24964. nodes,
  24965. child;
  24966. if (!node) return copy;
  24967. if (!node.length) return copy._root = leaf_copy$2(node), copy;
  24968. nodes = [{source: node, target: copy._root = new Array(2)}];
  24969. while (node = nodes.pop()) {
  24970. for (var i = 0; i < 2; ++i) {
  24971. if (child = node.source[i]) {
  24972. if (child.length) nodes.push({source: child, target: node.target[i] = new Array(2)});
  24973. else node.target[i] = leaf_copy$2(child);
  24974. }
  24975. }
  24976. }
  24977. return copy;
  24978. };
  24979. treeProto$2.add = tree_add$2;
  24980. treeProto$2.addAll = addAll$2;
  24981. treeProto$2.cover = tree_cover$2;
  24982. treeProto$2.data = tree_data$2;
  24983. treeProto$2.extent = tree_extent$2;
  24984. treeProto$2.find = tree_find$2;
  24985. treeProto$2.remove = tree_remove$2;
  24986. treeProto$2.removeAll = removeAll$3;
  24987. treeProto$2.root = tree_root$2;
  24988. treeProto$2.size = tree_size$2;
  24989. treeProto$2.visit = tree_visit$2;
  24990. treeProto$2.visitAfter = tree_visitAfter$2;
  24991. treeProto$2.x = tree_x$2;
  24992. function tree_add$1(d) {
  24993. const x = +this._x.call(null, d),
  24994. y = +this._y.call(null, d);
  24995. return add$2(this.cover(x, y), x, y, d);
  24996. }
  24997. function add$2(tree, x, y, d) {
  24998. if (isNaN(x) || isNaN(y)) return tree; // ignore invalid points
  24999. var parent,
  25000. node = tree._root,
  25001. leaf = {data: d},
  25002. x0 = tree._x0,
  25003. y0 = tree._y0,
  25004. x1 = tree._x1,
  25005. y1 = tree._y1,
  25006. xm,
  25007. ym,
  25008. xp,
  25009. yp,
  25010. right,
  25011. bottom,
  25012. i,
  25013. j;
  25014. // If the tree is empty, initialize the root as a leaf.
  25015. if (!node) return tree._root = leaf, tree;
  25016. // Find the existing leaf for the new point, or add it.
  25017. while (node.length) {
  25018. if (right = x >= (xm = (x0 + x1) / 2)) x0 = xm; else x1 = xm;
  25019. if (bottom = y >= (ym = (y0 + y1) / 2)) y0 = ym; else y1 = ym;
  25020. if (parent = node, !(node = node[i = bottom << 1 | right])) return parent[i] = leaf, tree;
  25021. }
  25022. // Is the new point is exactly coincident with the existing point?
  25023. xp = +tree._x.call(null, node.data);
  25024. yp = +tree._y.call(null, node.data);
  25025. if (x === xp && y === yp) return leaf.next = node, parent ? parent[i] = leaf : tree._root = leaf, tree;
  25026. // Otherwise, split the leaf node until the old and new point are separated.
  25027. do {
  25028. parent = parent ? parent[i] = new Array(4) : tree._root = new Array(4);
  25029. if (right = x >= (xm = (x0 + x1) / 2)) x0 = xm; else x1 = xm;
  25030. if (bottom = y >= (ym = (y0 + y1) / 2)) y0 = ym; else y1 = ym;
  25031. } while ((i = bottom << 1 | right) === (j = (yp >= ym) << 1 | (xp >= xm)));
  25032. return parent[j] = node, parent[i] = leaf, tree;
  25033. }
  25034. function addAll$1(data) {
  25035. var d, i, n = data.length,
  25036. x,
  25037. y,
  25038. xz = new Array(n),
  25039. yz = new Array(n),
  25040. x0 = Infinity,
  25041. y0 = Infinity,
  25042. x1 = -Infinity,
  25043. y1 = -Infinity;
  25044. // Compute the points and their extent.
  25045. for (i = 0; i < n; ++i) {
  25046. if (isNaN(x = +this._x.call(null, d = data[i])) || isNaN(y = +this._y.call(null, d))) continue;
  25047. xz[i] = x;
  25048. yz[i] = y;
  25049. if (x < x0) x0 = x;
  25050. if (x > x1) x1 = x;
  25051. if (y < y0) y0 = y;
  25052. if (y > y1) y1 = y;
  25053. }
  25054. // If there were no (valid) points, abort.
  25055. if (x0 > x1 || y0 > y1) return this;
  25056. // Expand the tree to cover the new points.
  25057. this.cover(x0, y0).cover(x1, y1);
  25058. // Add the new points.
  25059. for (i = 0; i < n; ++i) {
  25060. add$2(this, xz[i], yz[i], data[i]);
  25061. }
  25062. return this;
  25063. }
  25064. function tree_cover$1(x, y) {
  25065. if (isNaN(x = +x) || isNaN(y = +y)) return this; // ignore invalid points
  25066. var x0 = this._x0,
  25067. y0 = this._y0,
  25068. x1 = this._x1,
  25069. y1 = this._y1;
  25070. // If the quadtree has no extent, initialize them.
  25071. // Integer extent are necessary so that if we later double the extent,
  25072. // the existing quadrant boundaries don’t change due to floating point error!
  25073. if (isNaN(x0)) {
  25074. x1 = (x0 = Math.floor(x)) + 1;
  25075. y1 = (y0 = Math.floor(y)) + 1;
  25076. }
  25077. // Otherwise, double repeatedly to cover.
  25078. else {
  25079. var z = x1 - x0 || 1,
  25080. node = this._root,
  25081. parent,
  25082. i;
  25083. while (x0 > x || x >= x1 || y0 > y || y >= y1) {
  25084. i = (y < y0) << 1 | (x < x0);
  25085. parent = new Array(4), parent[i] = node, node = parent, z *= 2;
  25086. switch (i) {
  25087. case 0: x1 = x0 + z, y1 = y0 + z; break;
  25088. case 1: x0 = x1 - z, y1 = y0 + z; break;
  25089. case 2: x1 = x0 + z, y0 = y1 - z; break;
  25090. case 3: x0 = x1 - z, y0 = y1 - z; break;
  25091. }
  25092. }
  25093. if (this._root && this._root.length) this._root = node;
  25094. }
  25095. this._x0 = x0;
  25096. this._y0 = y0;
  25097. this._x1 = x1;
  25098. this._y1 = y1;
  25099. return this;
  25100. }
  25101. function tree_data$1() {
  25102. var data = [];
  25103. this.visit(function(node) {
  25104. if (!node.length) do data.push(node.data); while (node = node.next)
  25105. });
  25106. return data;
  25107. }
  25108. function tree_extent$1(_) {
  25109. return arguments.length
  25110. ? this.cover(+_[0][0], +_[0][1]).cover(+_[1][0], +_[1][1])
  25111. : isNaN(this._x0) ? undefined : [[this._x0, this._y0], [this._x1, this._y1]];
  25112. }
  25113. function Quad(node, x0, y0, x1, y1) {
  25114. this.node = node;
  25115. this.x0 = x0;
  25116. this.y0 = y0;
  25117. this.x1 = x1;
  25118. this.y1 = y1;
  25119. }
  25120. function tree_find$1(x, y, radius) {
  25121. var data,
  25122. x0 = this._x0,
  25123. y0 = this._y0,
  25124. x1,
  25125. y1,
  25126. x2,
  25127. y2,
  25128. x3 = this._x1,
  25129. y3 = this._y1,
  25130. quads = [],
  25131. node = this._root,
  25132. q,
  25133. i;
  25134. if (node) quads.push(new Quad(node, x0, y0, x3, y3));
  25135. if (radius == null) radius = Infinity;
  25136. else {
  25137. x0 = x - radius, y0 = y - radius;
  25138. x3 = x + radius, y3 = y + radius;
  25139. radius *= radius;
  25140. }
  25141. while (q = quads.pop()) {
  25142. // Stop searching if this quadrant can’t contain a closer node.
  25143. if (!(node = q.node)
  25144. || (x1 = q.x0) > x3
  25145. || (y1 = q.y0) > y3
  25146. || (x2 = q.x1) < x0
  25147. || (y2 = q.y1) < y0) continue;
  25148. // Bisect the current quadrant.
  25149. if (node.length) {
  25150. var xm = (x1 + x2) / 2,
  25151. ym = (y1 + y2) / 2;
  25152. quads.push(
  25153. new Quad(node[3], xm, ym, x2, y2),
  25154. new Quad(node[2], x1, ym, xm, y2),
  25155. new Quad(node[1], xm, y1, x2, ym),
  25156. new Quad(node[0], x1, y1, xm, ym)
  25157. );
  25158. // Visit the closest quadrant first.
  25159. if (i = (y >= ym) << 1 | (x >= xm)) {
  25160. q = quads[quads.length - 1];
  25161. quads[quads.length - 1] = quads[quads.length - 1 - i];
  25162. quads[quads.length - 1 - i] = q;
  25163. }
  25164. }
  25165. // Visit this point. (Visiting coincident points isn’t necessary!)
  25166. else {
  25167. var dx = x - +this._x.call(null, node.data),
  25168. dy = y - +this._y.call(null, node.data),
  25169. d2 = dx * dx + dy * dy;
  25170. if (d2 < radius) {
  25171. var d = Math.sqrt(radius = d2);
  25172. x0 = x - d, y0 = y - d;
  25173. x3 = x + d, y3 = y + d;
  25174. data = node.data;
  25175. }
  25176. }
  25177. }
  25178. return data;
  25179. }
  25180. function tree_remove$1(d) {
  25181. if (isNaN(x = +this._x.call(null, d)) || isNaN(y = +this._y.call(null, d))) return this; // ignore invalid points
  25182. var parent,
  25183. node = this._root,
  25184. retainer,
  25185. previous,
  25186. next,
  25187. x0 = this._x0,
  25188. y0 = this._y0,
  25189. x1 = this._x1,
  25190. y1 = this._y1,
  25191. x,
  25192. y,
  25193. xm,
  25194. ym,
  25195. right,
  25196. bottom,
  25197. i,
  25198. j;
  25199. // If the tree is empty, initialize the root as a leaf.
  25200. if (!node) return this;
  25201. // Find the leaf node for the point.
  25202. // While descending, also retain the deepest parent with a non-removed sibling.
  25203. if (node.length) while (true) {
  25204. if (right = x >= (xm = (x0 + x1) / 2)) x0 = xm; else x1 = xm;
  25205. if (bottom = y >= (ym = (y0 + y1) / 2)) y0 = ym; else y1 = ym;
  25206. if (!(parent = node, node = node[i = bottom << 1 | right])) return this;
  25207. if (!node.length) break;
  25208. if (parent[(i + 1) & 3] || parent[(i + 2) & 3] || parent[(i + 3) & 3]) retainer = parent, j = i;
  25209. }
  25210. // Find the point to remove.
  25211. while (node.data !== d) if (!(previous = node, node = node.next)) return this;
  25212. if (next = node.next) delete node.next;
  25213. // If there are multiple coincident points, remove just the point.
  25214. if (previous) return (next ? previous.next = next : delete previous.next), this;
  25215. // If this is the root point, remove it.
  25216. if (!parent) return this._root = next, this;
  25217. // Remove this leaf.
  25218. next ? parent[i] = next : delete parent[i];
  25219. // If the parent now contains exactly one leaf, collapse superfluous parents.
  25220. if ((node = parent[0] || parent[1] || parent[2] || parent[3])
  25221. && node === (parent[3] || parent[2] || parent[1] || parent[0])
  25222. && !node.length) {
  25223. if (retainer) retainer[j] = node;
  25224. else this._root = node;
  25225. }
  25226. return this;
  25227. }
  25228. function removeAll$2(data) {
  25229. for (var i = 0, n = data.length; i < n; ++i) this.remove(data[i]);
  25230. return this;
  25231. }
  25232. function tree_root$1() {
  25233. return this._root;
  25234. }
  25235. function tree_size$1() {
  25236. var size = 0;
  25237. this.visit(function(node) {
  25238. if (!node.length) do ++size; while (node = node.next)
  25239. });
  25240. return size;
  25241. }
  25242. function tree_visit$1(callback) {
  25243. var quads = [], q, node = this._root, child, x0, y0, x1, y1;
  25244. if (node) quads.push(new Quad(node, this._x0, this._y0, this._x1, this._y1));
  25245. while (q = quads.pop()) {
  25246. if (!callback(node = q.node, x0 = q.x0, y0 = q.y0, x1 = q.x1, y1 = q.y1) && node.length) {
  25247. var xm = (x0 + x1) / 2, ym = (y0 + y1) / 2;
  25248. if (child = node[3]) quads.push(new Quad(child, xm, ym, x1, y1));
  25249. if (child = node[2]) quads.push(new Quad(child, x0, ym, xm, y1));
  25250. if (child = node[1]) quads.push(new Quad(child, xm, y0, x1, ym));
  25251. if (child = node[0]) quads.push(new Quad(child, x0, y0, xm, ym));
  25252. }
  25253. }
  25254. return this;
  25255. }
  25256. function tree_visitAfter$1(callback) {
  25257. var quads = [], next = [], q;
  25258. if (this._root) quads.push(new Quad(this._root, this._x0, this._y0, this._x1, this._y1));
  25259. while (q = quads.pop()) {
  25260. var node = q.node;
  25261. if (node.length) {
  25262. var child, x0 = q.x0, y0 = q.y0, x1 = q.x1, y1 = q.y1, xm = (x0 + x1) / 2, ym = (y0 + y1) / 2;
  25263. if (child = node[0]) quads.push(new Quad(child, x0, y0, xm, ym));
  25264. if (child = node[1]) quads.push(new Quad(child, xm, y0, x1, ym));
  25265. if (child = node[2]) quads.push(new Quad(child, x0, ym, xm, y1));
  25266. if (child = node[3]) quads.push(new Quad(child, xm, ym, x1, y1));
  25267. }
  25268. next.push(q);
  25269. }
  25270. while (q = next.pop()) {
  25271. callback(q.node, q.x0, q.y0, q.x1, q.y1);
  25272. }
  25273. return this;
  25274. }
  25275. function defaultX$1(d) {
  25276. return d[0];
  25277. }
  25278. function tree_x$1(_) {
  25279. return arguments.length ? (this._x = _, this) : this._x;
  25280. }
  25281. function defaultY$1(d) {
  25282. return d[1];
  25283. }
  25284. function tree_y$1(_) {
  25285. return arguments.length ? (this._y = _, this) : this._y;
  25286. }
  25287. function quadtree(nodes, x, y) {
  25288. var tree = new Quadtree(x == null ? defaultX$1 : x, y == null ? defaultY$1 : y, NaN, NaN, NaN, NaN);
  25289. return nodes == null ? tree : tree.addAll(nodes);
  25290. }
  25291. function Quadtree(x, y, x0, y0, x1, y1) {
  25292. this._x = x;
  25293. this._y = y;
  25294. this._x0 = x0;
  25295. this._y0 = y0;
  25296. this._x1 = x1;
  25297. this._y1 = y1;
  25298. this._root = undefined;
  25299. }
  25300. function leaf_copy$1(leaf) {
  25301. var copy = {data: leaf.data}, next = copy;
  25302. while (leaf = leaf.next) next = next.next = {data: leaf.data};
  25303. return copy;
  25304. }
  25305. var treeProto$1 = quadtree.prototype = Quadtree.prototype;
  25306. treeProto$1.copy = function() {
  25307. var copy = new Quadtree(this._x, this._y, this._x0, this._y0, this._x1, this._y1),
  25308. node = this._root,
  25309. nodes,
  25310. child;
  25311. if (!node) return copy;
  25312. if (!node.length) return copy._root = leaf_copy$1(node), copy;
  25313. nodes = [{source: node, target: copy._root = new Array(4)}];
  25314. while (node = nodes.pop()) {
  25315. for (var i = 0; i < 4; ++i) {
  25316. if (child = node.source[i]) {
  25317. if (child.length) nodes.push({source: child, target: node.target[i] = new Array(4)});
  25318. else node.target[i] = leaf_copy$1(child);
  25319. }
  25320. }
  25321. }
  25322. return copy;
  25323. };
  25324. treeProto$1.add = tree_add$1;
  25325. treeProto$1.addAll = addAll$1;
  25326. treeProto$1.cover = tree_cover$1;
  25327. treeProto$1.data = tree_data$1;
  25328. treeProto$1.extent = tree_extent$1;
  25329. treeProto$1.find = tree_find$1;
  25330. treeProto$1.remove = tree_remove$1;
  25331. treeProto$1.removeAll = removeAll$2;
  25332. treeProto$1.root = tree_root$1;
  25333. treeProto$1.size = tree_size$1;
  25334. treeProto$1.visit = tree_visit$1;
  25335. treeProto$1.visitAfter = tree_visitAfter$1;
  25336. treeProto$1.x = tree_x$1;
  25337. treeProto$1.y = tree_y$1;
  25338. function tree_add(d) {
  25339. var x = +this._x.call(null, d),
  25340. y = +this._y.call(null, d),
  25341. z = +this._z.call(null, d);
  25342. return add$1(this.cover(x, y, z), x, y, z, d);
  25343. }
  25344. function add$1(tree, x, y, z, d) {
  25345. if (isNaN(x) || isNaN(y) || isNaN(z)) return tree; // ignore invalid points
  25346. var parent,
  25347. node = tree._root,
  25348. leaf = {data: d},
  25349. x0 = tree._x0,
  25350. y0 = tree._y0,
  25351. z0 = tree._z0,
  25352. x1 = tree._x1,
  25353. y1 = tree._y1,
  25354. z1 = tree._z1,
  25355. xm,
  25356. ym,
  25357. zm,
  25358. xp,
  25359. yp,
  25360. zp,
  25361. right,
  25362. bottom,
  25363. deep,
  25364. i,
  25365. j;
  25366. // If the tree is empty, initialize the root as a leaf.
  25367. if (!node) return tree._root = leaf, tree;
  25368. // Find the existing leaf for the new point, or add it.
  25369. while (node.length) {
  25370. if (right = x >= (xm = (x0 + x1) / 2)) x0 = xm; else x1 = xm;
  25371. if (bottom = y >= (ym = (y0 + y1) / 2)) y0 = ym; else y1 = ym;
  25372. if (deep = z >= (zm = (z0 + z1) / 2)) z0 = zm; else z1 = zm;
  25373. if (parent = node, !(node = node[i = deep << 2 | bottom << 1 | right])) return parent[i] = leaf, tree;
  25374. }
  25375. // Is the new point is exactly coincident with the existing point?
  25376. xp = +tree._x.call(null, node.data);
  25377. yp = +tree._y.call(null, node.data);
  25378. zp = +tree._z.call(null, node.data);
  25379. if (x === xp && y === yp && z === zp) return leaf.next = node, parent ? parent[i] = leaf : tree._root = leaf, tree;
  25380. // Otherwise, split the leaf node until the old and new point are separated.
  25381. do {
  25382. parent = parent ? parent[i] = new Array(8) : tree._root = new Array(8);
  25383. if (right = x >= (xm = (x0 + x1) / 2)) x0 = xm; else x1 = xm;
  25384. if (bottom = y >= (ym = (y0 + y1) / 2)) y0 = ym; else y1 = ym;
  25385. if (deep = z >= (zm = (z0 + z1) / 2)) z0 = zm; else z1 = zm;
  25386. } while ((i = deep << 2 | bottom << 1 | right) === (j = (zp >= zm) << 2 | (yp >= ym) << 1 | (xp >= xm)));
  25387. return parent[j] = node, parent[i] = leaf, tree;
  25388. }
  25389. function addAll(data) {
  25390. var d, i, n = data.length,
  25391. x,
  25392. y,
  25393. z,
  25394. xz = new Array(n),
  25395. yz = new Array(n),
  25396. zz = new Array(n),
  25397. x0 = Infinity,
  25398. y0 = Infinity,
  25399. z0 = Infinity,
  25400. x1 = -Infinity,
  25401. y1 = -Infinity,
  25402. z1 = -Infinity;
  25403. // Compute the points and their extent.
  25404. for (i = 0; i < n; ++i) {
  25405. if (isNaN(x = +this._x.call(null, d = data[i])) || isNaN(y = +this._y.call(null, d)) || isNaN(z = +this._z.call(null, d))) continue;
  25406. xz[i] = x;
  25407. yz[i] = y;
  25408. zz[i] = z;
  25409. if (x < x0) x0 = x;
  25410. if (x > x1) x1 = x;
  25411. if (y < y0) y0 = y;
  25412. if (y > y1) y1 = y;
  25413. if (z < z0) z0 = z;
  25414. if (z > z1) z1 = z;
  25415. }
  25416. // If there were no (valid) points, abort.
  25417. if (x0 > x1 || y0 > y1 || z0 > z1) return this;
  25418. // Expand the tree to cover the new points.
  25419. this.cover(x0, y0, z0).cover(x1, y1, z1);
  25420. // Add the new points.
  25421. for (i = 0; i < n; ++i) {
  25422. add$1(this, xz[i], yz[i], zz[i], data[i]);
  25423. }
  25424. return this;
  25425. }
  25426. function tree_cover(x, y, z) {
  25427. if (isNaN(x = +x) || isNaN(y = +y) || isNaN(z = +z)) return this; // ignore invalid points
  25428. var x0 = this._x0,
  25429. y0 = this._y0,
  25430. z0 = this._z0,
  25431. x1 = this._x1,
  25432. y1 = this._y1,
  25433. z1 = this._z1;
  25434. // If the octree has no extent, initialize them.
  25435. // Integer extent are necessary so that if we later double the extent,
  25436. // the existing octant boundaries don’t change due to floating point error!
  25437. if (isNaN(x0)) {
  25438. x1 = (x0 = Math.floor(x)) + 1;
  25439. y1 = (y0 = Math.floor(y)) + 1;
  25440. z1 = (z0 = Math.floor(z)) + 1;
  25441. }
  25442. // Otherwise, double repeatedly to cover.
  25443. else {
  25444. var t = x1 - x0 || 1,
  25445. node = this._root,
  25446. parent,
  25447. i;
  25448. while (x0 > x || x >= x1 || y0 > y || y >= y1 || z0 > z || z >= z1) {
  25449. i = (z < z0) << 2 | (y < y0) << 1 | (x < x0);
  25450. parent = new Array(8), parent[i] = node, node = parent, t *= 2;
  25451. switch (i) {
  25452. case 0: x1 = x0 + t, y1 = y0 + t, z1 = z0 + t; break;
  25453. case 1: x0 = x1 - t, y1 = y0 + t, z1 = z0 + t; break;
  25454. case 2: x1 = x0 + t, y0 = y1 - t, z1 = z0 + t; break;
  25455. case 3: x0 = x1 - t, y0 = y1 - t, z1 = z0 + t; break;
  25456. case 4: x1 = x0 + t, y1 = y0 + t, z0 = z1 - t; break;
  25457. case 5: x0 = x1 - t, y1 = y0 + t, z0 = z1 - t; break;
  25458. case 6: x1 = x0 + t, y0 = y1 - t, z0 = z1 - t; break;
  25459. case 7: x0 = x1 - t, y0 = y1 - t, z0 = z1 - t; break;
  25460. }
  25461. }
  25462. if (this._root && this._root.length) this._root = node;
  25463. }
  25464. this._x0 = x0;
  25465. this._y0 = y0;
  25466. this._z0 = z0;
  25467. this._x1 = x1;
  25468. this._y1 = y1;
  25469. this._z1 = z1;
  25470. return this;
  25471. }
  25472. function tree_data() {
  25473. var data = [];
  25474. this.visit(function(node) {
  25475. if (!node.length) do data.push(node.data); while (node = node.next)
  25476. });
  25477. return data;
  25478. }
  25479. function tree_extent(_) {
  25480. return arguments.length
  25481. ? this.cover(+_[0][0], +_[0][1], +_[0][2]).cover(+_[1][0], +_[1][1], +_[1][2])
  25482. : isNaN(this._x0) ? undefined : [[this._x0, this._y0, this._z0], [this._x1, this._y1, this._z1]];
  25483. }
  25484. function Octant(node, x0, y0, z0, x1, y1, z1) {
  25485. this.node = node;
  25486. this.x0 = x0;
  25487. this.y0 = y0;
  25488. this.z0 = z0;
  25489. this.x1 = x1;
  25490. this.y1 = y1;
  25491. this.z1 = z1;
  25492. }
  25493. function tree_find(x, y, z, radius) {
  25494. var data,
  25495. x0 = this._x0,
  25496. y0 = this._y0,
  25497. z0 = this._z0,
  25498. x1,
  25499. y1,
  25500. z1,
  25501. x2,
  25502. y2,
  25503. z2,
  25504. x3 = this._x1,
  25505. y3 = this._y1,
  25506. z3 = this._z1,
  25507. octs = [],
  25508. node = this._root,
  25509. q,
  25510. i;
  25511. if (node) octs.push(new Octant(node, x0, y0, z0, x3, y3, z3));
  25512. if (radius == null) radius = Infinity;
  25513. else {
  25514. x0 = x - radius, y0 = y - radius, z0 = z - radius;
  25515. x3 = x + radius, y3 = y + radius, z3 = z + radius;
  25516. radius *= radius;
  25517. }
  25518. while (q = octs.pop()) {
  25519. // Stop searching if this octant can’t contain a closer node.
  25520. if (!(node = q.node)
  25521. || (x1 = q.x0) > x3
  25522. || (y1 = q.y0) > y3
  25523. || (z1 = q.z0) > z3
  25524. || (x2 = q.x1) < x0
  25525. || (y2 = q.y1) < y0
  25526. || (z2 = q.z1) < z0) continue;
  25527. // Bisect the current octant.
  25528. if (node.length) {
  25529. var xm = (x1 + x2) / 2,
  25530. ym = (y1 + y2) / 2,
  25531. zm = (z1 + z2) / 2;
  25532. octs.push(
  25533. new Octant(node[7], xm, ym, zm, x2, y2, z2),
  25534. new Octant(node[6], x1, ym, zm, xm, y2, z2),
  25535. new Octant(node[5], xm, y1, zm, x2, ym, z2),
  25536. new Octant(node[4], x1, y1, zm, xm, ym, z2),
  25537. new Octant(node[3], xm, ym, z1, x2, y2, zm),
  25538. new Octant(node[2], x1, ym, z1, xm, y2, zm),
  25539. new Octant(node[1], xm, y1, z1, x2, ym, zm),
  25540. new Octant(node[0], x1, y1, z1, xm, ym, zm)
  25541. );
  25542. // Visit the closest octant first.
  25543. if (i = (z >= zm) << 2 | (y >= ym) << 1 | (x >= xm)) {
  25544. q = octs[octs.length - 1];
  25545. octs[octs.length - 1] = octs[octs.length - 1 - i];
  25546. octs[octs.length - 1 - i] = q;
  25547. }
  25548. }
  25549. // Visit this point. (Visiting coincident points isn’t necessary!)
  25550. else {
  25551. var dx = x - +this._x.call(null, node.data),
  25552. dy = y - +this._y.call(null, node.data),
  25553. dz = z - +this._z.call(null, node.data),
  25554. d2 = dx * dx + dy * dy + dz * dz;
  25555. if (d2 < radius) {
  25556. var d = Math.sqrt(radius = d2);
  25557. x0 = x - d, y0 = y - d, z0 = z - d;
  25558. x3 = x + d, y3 = y + d, z3 = z + d;
  25559. data = node.data;
  25560. }
  25561. }
  25562. }
  25563. return data;
  25564. }
  25565. function tree_remove(d) {
  25566. if (isNaN(x = +this._x.call(null, d)) || isNaN(y = +this._y.call(null, d)) || isNaN(z = +this._z.call(null, d))) return this; // ignore invalid points
  25567. var parent,
  25568. node = this._root,
  25569. retainer,
  25570. previous,
  25571. next,
  25572. x0 = this._x0,
  25573. y0 = this._y0,
  25574. z0 = this._z0,
  25575. x1 = this._x1,
  25576. y1 = this._y1,
  25577. z1 = this._z1,
  25578. x,
  25579. y,
  25580. z,
  25581. xm,
  25582. ym,
  25583. zm,
  25584. right,
  25585. bottom,
  25586. deep,
  25587. i,
  25588. j;
  25589. // If the tree is empty, initialize the root as a leaf.
  25590. if (!node) return this;
  25591. // Find the leaf node for the point.
  25592. // While descending, also retain the deepest parent with a non-removed sibling.
  25593. if (node.length) while (true) {
  25594. if (right = x >= (xm = (x0 + x1) / 2)) x0 = xm; else x1 = xm;
  25595. if (bottom = y >= (ym = (y0 + y1) / 2)) y0 = ym; else y1 = ym;
  25596. if (deep = z >= (zm = (z0 + z1) / 2)) z0 = zm; else z1 = zm;
  25597. if (!(parent = node, node = node[i = deep << 2 | bottom << 1 | right])) return this;
  25598. if (!node.length) break;
  25599. if (parent[(i + 1) & 7] || parent[(i + 2) & 7] || parent[(i + 3) & 7] || parent[(i + 4) & 7] || parent[(i + 5) & 7] || parent[(i + 6) & 7] || parent[(i + 7) & 7]) retainer = parent, j = i;
  25600. }
  25601. // Find the point to remove.
  25602. while (node.data !== d) if (!(previous = node, node = node.next)) return this;
  25603. if (next = node.next) delete node.next;
  25604. // If there are multiple coincident points, remove just the point.
  25605. if (previous) return (next ? previous.next = next : delete previous.next), this;
  25606. // If this is the root point, remove it.
  25607. if (!parent) return this._root = next, this;
  25608. // Remove this leaf.
  25609. next ? parent[i] = next : delete parent[i];
  25610. // If the parent now contains exactly one leaf, collapse superfluous parents.
  25611. if ((node = parent[0] || parent[1] || parent[2] || parent[3] || parent[4] || parent[5] || parent[6] || parent[7])
  25612. && node === (parent[7] || parent[6] || parent[5] || parent[4] || parent[3] || parent[2] || parent[1] || parent[0])
  25613. && !node.length) {
  25614. if (retainer) retainer[j] = node;
  25615. else this._root = node;
  25616. }
  25617. return this;
  25618. }
  25619. function removeAll$1(data) {
  25620. for (var i = 0, n = data.length; i < n; ++i) this.remove(data[i]);
  25621. return this;
  25622. }
  25623. function tree_root() {
  25624. return this._root;
  25625. }
  25626. function tree_size() {
  25627. var size = 0;
  25628. this.visit(function(node) {
  25629. if (!node.length) do ++size; while (node = node.next)
  25630. });
  25631. return size;
  25632. }
  25633. function tree_visit(callback) {
  25634. var octs = [], q, node = this._root, child, x0, y0, z0, x1, y1, z1;
  25635. if (node) octs.push(new Octant(node, this._x0, this._y0, this._z0, this._x1, this._y1, this._z1));
  25636. while (q = octs.pop()) {
  25637. if (!callback(node = q.node, x0 = q.x0, y0 = q.y0, z0 = q.z0, x1 = q.x1, y1 = q.y1, z1 = q.z1) && node.length) {
  25638. var xm = (x0 + x1) / 2, ym = (y0 + y1) / 2, zm = (z0 + z1) / 2;
  25639. if (child = node[7]) octs.push(new Octant(child, xm, ym, zm, x1, y1, z1));
  25640. if (child = node[6]) octs.push(new Octant(child, x0, ym, zm, xm, y1, z1));
  25641. if (child = node[5]) octs.push(new Octant(child, xm, y0, zm, x1, ym, z1));
  25642. if (child = node[4]) octs.push(new Octant(child, x0, y0, zm, xm, ym, z1));
  25643. if (child = node[3]) octs.push(new Octant(child, xm, ym, z0, x1, y1, zm));
  25644. if (child = node[2]) octs.push(new Octant(child, x0, ym, z0, xm, y1, zm));
  25645. if (child = node[1]) octs.push(new Octant(child, xm, y0, z0, x1, ym, zm));
  25646. if (child = node[0]) octs.push(new Octant(child, x0, y0, z0, xm, ym, zm));
  25647. }
  25648. }
  25649. return this;
  25650. }
  25651. function tree_visitAfter(callback) {
  25652. var octs = [], next = [], q;
  25653. if (this._root) octs.push(new Octant(this._root, this._x0, this._y0, this._z0, this._x1, this._y1, this._z1));
  25654. while (q = octs.pop()) {
  25655. var node = q.node;
  25656. if (node.length) {
  25657. var child, x0 = q.x0, y0 = q.y0, z0 = q.z0, x1 = q.x1, y1 = q.y1, z1 = q.z1, xm = (x0 + x1) / 2, ym = (y0 + y1) / 2, zm = (z0 + z1) / 2;
  25658. if (child = node[0]) octs.push(new Octant(child, x0, y0, z0, xm, ym, zm));
  25659. if (child = node[1]) octs.push(new Octant(child, xm, y0, z0, x1, ym, zm));
  25660. if (child = node[2]) octs.push(new Octant(child, x0, ym, z0, xm, y1, zm));
  25661. if (child = node[3]) octs.push(new Octant(child, xm, ym, z0, x1, y1, zm));
  25662. if (child = node[4]) octs.push(new Octant(child, x0, y0, zm, xm, ym, z1));
  25663. if (child = node[5]) octs.push(new Octant(child, xm, y0, zm, x1, ym, z1));
  25664. if (child = node[6]) octs.push(new Octant(child, x0, ym, zm, xm, y1, z1));
  25665. if (child = node[7]) octs.push(new Octant(child, xm, ym, zm, x1, y1, z1));
  25666. }
  25667. next.push(q);
  25668. }
  25669. while (q = next.pop()) {
  25670. callback(q.node, q.x0, q.y0, q.z0, q.x1, q.y1, q.z1);
  25671. }
  25672. return this;
  25673. }
  25674. function defaultX(d) {
  25675. return d[0];
  25676. }
  25677. function tree_x(_) {
  25678. return arguments.length ? (this._x = _, this) : this._x;
  25679. }
  25680. function defaultY(d) {
  25681. return d[1];
  25682. }
  25683. function tree_y(_) {
  25684. return arguments.length ? (this._y = _, this) : this._y;
  25685. }
  25686. function defaultZ(d) {
  25687. return d[2];
  25688. }
  25689. function tree_z(_) {
  25690. return arguments.length ? (this._z = _, this) : this._z;
  25691. }
  25692. function octree(nodes, x, y, z) {
  25693. var tree = new Octree(x == null ? defaultX : x, y == null ? defaultY : y, z == null ? defaultZ : z, NaN, NaN, NaN, NaN, NaN, NaN);
  25694. return nodes == null ? tree : tree.addAll(nodes);
  25695. }
  25696. function Octree(x, y, z, x0, y0, z0, x1, y1, z1) {
  25697. this._x = x;
  25698. this._y = y;
  25699. this._z = z;
  25700. this._x0 = x0;
  25701. this._y0 = y0;
  25702. this._z0 = z0;
  25703. this._x1 = x1;
  25704. this._y1 = y1;
  25705. this._z1 = z1;
  25706. this._root = undefined;
  25707. }
  25708. function leaf_copy(leaf) {
  25709. var copy = {data: leaf.data}, next = copy;
  25710. while (leaf = leaf.next) next = next.next = {data: leaf.data};
  25711. return copy;
  25712. }
  25713. var treeProto = octree.prototype = Octree.prototype;
  25714. treeProto.copy = function() {
  25715. var copy = new Octree(this._x, this._y, this._z, this._x0, this._y0, this._z0, this._x1, this._y1, this._z1),
  25716. node = this._root,
  25717. nodes,
  25718. child;
  25719. if (!node) return copy;
  25720. if (!node.length) return copy._root = leaf_copy(node), copy;
  25721. nodes = [{source: node, target: copy._root = new Array(8)}];
  25722. while (node = nodes.pop()) {
  25723. for (var i = 0; i < 8; ++i) {
  25724. if (child = node.source[i]) {
  25725. if (child.length) nodes.push({source: child, target: node.target[i] = new Array(8)});
  25726. else node.target[i] = leaf_copy(child);
  25727. }
  25728. }
  25729. }
  25730. return copy;
  25731. };
  25732. treeProto.add = tree_add;
  25733. treeProto.addAll = addAll;
  25734. treeProto.cover = tree_cover;
  25735. treeProto.data = tree_data;
  25736. treeProto.extent = tree_extent;
  25737. treeProto.find = tree_find;
  25738. treeProto.remove = tree_remove;
  25739. treeProto.removeAll = removeAll$1;
  25740. treeProto.root = tree_root;
  25741. treeProto.size = tree_size;
  25742. treeProto.visit = tree_visit;
  25743. treeProto.visitAfter = tree_visitAfter;
  25744. treeProto.x = tree_x;
  25745. treeProto.y = tree_y;
  25746. treeProto.z = tree_z;
  25747. function constant(x) {
  25748. return function() {
  25749. return x;
  25750. };
  25751. }
  25752. function jiggle(random) {
  25753. return (random() - 0.5) * 1e-6;
  25754. }
  25755. function index$3(d) {
  25756. return d.index;
  25757. }
  25758. function find(nodeById, nodeId) {
  25759. var node = nodeById.get(nodeId);
  25760. if (!node) throw new Error("node not found: " + nodeId);
  25761. return node;
  25762. }
  25763. function forceLink(links) {
  25764. var id = index$3,
  25765. strength = defaultStrength,
  25766. strengths,
  25767. distance = constant(30),
  25768. distances,
  25769. nodes,
  25770. nDim,
  25771. count,
  25772. bias,
  25773. random,
  25774. iterations = 1;
  25775. if (links == null) links = [];
  25776. function defaultStrength(link) {
  25777. return 1 / Math.min(count[link.source.index], count[link.target.index]);
  25778. }
  25779. function force(alpha) {
  25780. for (var k = 0, n = links.length; k < iterations; ++k) {
  25781. for (var i = 0, link, source, target, x = 0, y = 0, z = 0, l, b; i < n; ++i) {
  25782. link = links[i], source = link.source, target = link.target;
  25783. x = target.x + target.vx - source.x - source.vx || jiggle(random);
  25784. if (nDim > 1) { y = target.y + target.vy - source.y - source.vy || jiggle(random); }
  25785. if (nDim > 2) { z = target.z + target.vz - source.z - source.vz || jiggle(random); }
  25786. l = Math.sqrt(x * x + y * y + z * z);
  25787. l = (l - distances[i]) / l * alpha * strengths[i];
  25788. x *= l, y *= l, z *= l;
  25789. target.vx -= x * (b = bias[i]);
  25790. if (nDim > 1) { target.vy -= y * b; }
  25791. if (nDim > 2) { target.vz -= z * b; }
  25792. source.vx += x * (b = 1 - b);
  25793. if (nDim > 1) { source.vy += y * b; }
  25794. if (nDim > 2) { source.vz += z * b; }
  25795. }
  25796. }
  25797. }
  25798. function initialize() {
  25799. if (!nodes) return;
  25800. var i,
  25801. n = nodes.length,
  25802. m = links.length,
  25803. nodeById = new Map(nodes.map((d, i) => [id(d, i, nodes), d])),
  25804. link;
  25805. for (i = 0, count = new Array(n); i < m; ++i) {
  25806. link = links[i], link.index = i;
  25807. if (typeof link.source !== "object") link.source = find(nodeById, link.source);
  25808. if (typeof link.target !== "object") link.target = find(nodeById, link.target);
  25809. count[link.source.index] = (count[link.source.index] || 0) + 1;
  25810. count[link.target.index] = (count[link.target.index] || 0) + 1;
  25811. }
  25812. for (i = 0, bias = new Array(m); i < m; ++i) {
  25813. link = links[i], bias[i] = count[link.source.index] / (count[link.source.index] + count[link.target.index]);
  25814. }
  25815. strengths = new Array(m), initializeStrength();
  25816. distances = new Array(m), initializeDistance();
  25817. }
  25818. function initializeStrength() {
  25819. if (!nodes) return;
  25820. for (var i = 0, n = links.length; i < n; ++i) {
  25821. strengths[i] = +strength(links[i], i, links);
  25822. }
  25823. }
  25824. function initializeDistance() {
  25825. if (!nodes) return;
  25826. for (var i = 0, n = links.length; i < n; ++i) {
  25827. distances[i] = +distance(links[i], i, links);
  25828. }
  25829. }
  25830. force.initialize = function(_nodes, ...args) {
  25831. nodes = _nodes;
  25832. random = args.find(arg => typeof arg === 'function') || Math.random;
  25833. nDim = args.find(arg => [1, 2, 3].includes(arg)) || 2;
  25834. initialize();
  25835. };
  25836. force.links = function(_) {
  25837. return arguments.length ? (links = _, initialize(), force) : links;
  25838. };
  25839. force.id = function(_) {
  25840. return arguments.length ? (id = _, force) : id;
  25841. };
  25842. force.iterations = function(_) {
  25843. return arguments.length ? (iterations = +_, force) : iterations;
  25844. };
  25845. force.strength = function(_) {
  25846. return arguments.length ? (strength = typeof _ === "function" ? _ : constant(+_), initializeStrength(), force) : strength;
  25847. };
  25848. force.distance = function(_) {
  25849. return arguments.length ? (distance = typeof _ === "function" ? _ : constant(+_), initializeDistance(), force) : distance;
  25850. };
  25851. return force;
  25852. }
  25853. var noop$1 = {value: () => {}};
  25854. function dispatch() {
  25855. for (var i = 0, n = arguments.length, _ = {}, t; i < n; ++i) {
  25856. if (!(t = arguments[i] + "") || (t in _) || /[\s.]/.test(t)) throw new Error("illegal type: " + t);
  25857. _[t] = [];
  25858. }
  25859. return new Dispatch(_);
  25860. }
  25861. function Dispatch(_) {
  25862. this._ = _;
  25863. }
  25864. function parseTypenames(typenames, types) {
  25865. return typenames.trim().split(/^|\s+/).map(function(t) {
  25866. var name = "", i = t.indexOf(".");
  25867. if (i >= 0) name = t.slice(i + 1), t = t.slice(0, i);
  25868. if (t && !types.hasOwnProperty(t)) throw new Error("unknown type: " + t);
  25869. return {type: t, name: name};
  25870. });
  25871. }
  25872. Dispatch.prototype = dispatch.prototype = {
  25873. constructor: Dispatch,
  25874. on: function(typename, callback) {
  25875. var _ = this._,
  25876. T = parseTypenames(typename + "", _),
  25877. t,
  25878. i = -1,
  25879. n = T.length;
  25880. // If no callback was specified, return the callback of the given type and name.
  25881. if (arguments.length < 2) {
  25882. while (++i < n) if ((t = (typename = T[i]).type) && (t = get(_[t], typename.name))) return t;
  25883. return;
  25884. }
  25885. // If a type was specified, set the callback for the given type and name.
  25886. // Otherwise, if a null callback was specified, remove callbacks of the given name.
  25887. if (callback != null && typeof callback !== "function") throw new Error("invalid callback: " + callback);
  25888. while (++i < n) {
  25889. if (t = (typename = T[i]).type) _[t] = set(_[t], typename.name, callback);
  25890. else if (callback == null) for (t in _) _[t] = set(_[t], typename.name, null);
  25891. }
  25892. return this;
  25893. },
  25894. copy: function() {
  25895. var copy = {}, _ = this._;
  25896. for (var t in _) copy[t] = _[t].slice();
  25897. return new Dispatch(copy);
  25898. },
  25899. call: function(type, that) {
  25900. if ((n = arguments.length - 2) > 0) for (var args = new Array(n), i = 0, n, t; i < n; ++i) args[i] = arguments[i + 2];
  25901. if (!this._.hasOwnProperty(type)) throw new Error("unknown type: " + type);
  25902. for (t = this._[type], i = 0, n = t.length; i < n; ++i) t[i].value.apply(that, args);
  25903. },
  25904. apply: function(type, that, args) {
  25905. if (!this._.hasOwnProperty(type)) throw new Error("unknown type: " + type);
  25906. for (var t = this._[type], i = 0, n = t.length; i < n; ++i) t[i].value.apply(that, args);
  25907. }
  25908. };
  25909. function get(type, name) {
  25910. for (var i = 0, n = type.length, c; i < n; ++i) {
  25911. if ((c = type[i]).name === name) {
  25912. return c.value;
  25913. }
  25914. }
  25915. }
  25916. function set(type, name, callback) {
  25917. for (var i = 0, n = type.length; i < n; ++i) {
  25918. if (type[i].name === name) {
  25919. type[i] = noop$1, type = type.slice(0, i).concat(type.slice(i + 1));
  25920. break;
  25921. }
  25922. }
  25923. if (callback != null) type.push({name: name, value: callback});
  25924. return type;
  25925. }
  25926. var frame = 0, // is an animation frame pending?
  25927. timeout = 0, // is a timeout pending?
  25928. interval = 0, // are any timers active?
  25929. pokeDelay = 1000, // how frequently we check for clock skew
  25930. taskHead,
  25931. taskTail,
  25932. clockLast = 0,
  25933. clockNow = 0,
  25934. clockSkew = 0,
  25935. clock = typeof performance === "object" && performance.now ? performance : Date,
  25936. setFrame = typeof window === "object" && window.requestAnimationFrame ? window.requestAnimationFrame.bind(window) : function(f) { setTimeout(f, 17); };
  25937. function now$2() {
  25938. return clockNow || (setFrame(clearNow), clockNow = clock.now() + clockSkew);
  25939. }
  25940. function clearNow() {
  25941. clockNow = 0;
  25942. }
  25943. function Timer() {
  25944. this._call =
  25945. this._time =
  25946. this._next = null;
  25947. }
  25948. Timer.prototype = timer.prototype = {
  25949. constructor: Timer,
  25950. restart: function(callback, delay, time) {
  25951. if (typeof callback !== "function") throw new TypeError("callback is not a function");
  25952. time = (time == null ? now$2() : +time) + (delay == null ? 0 : +delay);
  25953. if (!this._next && taskTail !== this) {
  25954. if (taskTail) taskTail._next = this;
  25955. else taskHead = this;
  25956. taskTail = this;
  25957. }
  25958. this._call = callback;
  25959. this._time = time;
  25960. sleep();
  25961. },
  25962. stop: function() {
  25963. if (this._call) {
  25964. this._call = null;
  25965. this._time = Infinity;
  25966. sleep();
  25967. }
  25968. }
  25969. };
  25970. function timer(callback, delay, time) {
  25971. var t = new Timer;
  25972. t.restart(callback, delay, time);
  25973. return t;
  25974. }
  25975. function timerFlush() {
  25976. now$2(); // Get the current time, if not already set.
  25977. ++frame; // Pretend we’ve set an alarm, if we haven’t already.
  25978. var t = taskHead, e;
  25979. while (t) {
  25980. if ((e = clockNow - t._time) >= 0) t._call.call(undefined, e);
  25981. t = t._next;
  25982. }
  25983. --frame;
  25984. }
  25985. function wake() {
  25986. clockNow = (clockLast = clock.now()) + clockSkew;
  25987. frame = timeout = 0;
  25988. try {
  25989. timerFlush();
  25990. } finally {
  25991. frame = 0;
  25992. nap();
  25993. clockNow = 0;
  25994. }
  25995. }
  25996. function poke() {
  25997. var now = clock.now(), delay = now - clockLast;
  25998. if (delay > pokeDelay) clockSkew -= delay, clockLast = now;
  25999. }
  26000. function nap() {
  26001. var t0, t1 = taskHead, t2, time = Infinity;
  26002. while (t1) {
  26003. if (t1._call) {
  26004. if (time > t1._time) time = t1._time;
  26005. t0 = t1, t1 = t1._next;
  26006. } else {
  26007. t2 = t1._next, t1._next = null;
  26008. t1 = t0 ? t0._next = t2 : taskHead = t2;
  26009. }
  26010. }
  26011. taskTail = t0;
  26012. sleep(time);
  26013. }
  26014. function sleep(time) {
  26015. if (frame) return; // Soonest alarm already set, or will be.
  26016. if (timeout) timeout = clearTimeout(timeout);
  26017. var delay = time - clockNow; // Strictly less than if we recomputed clockNow.
  26018. if (delay > 24) {
  26019. if (time < Infinity) timeout = setTimeout(wake, time - clock.now() - clockSkew);
  26020. if (interval) interval = clearInterval(interval);
  26021. } else {
  26022. if (!interval) clockLast = clock.now(), interval = setInterval(poke, pokeDelay);
  26023. frame = 1, setFrame(wake);
  26024. }
  26025. }
  26026. // https://en.wikipedia.org/wiki/Linear_congruential_generator#Parameters_in_common_use
  26027. const a = 1664525;
  26028. const c = 1013904223;
  26029. const m = 4294967296; // 2^32
  26030. function lcg() {
  26031. let s = 1;
  26032. return () => (s = (a * s + c) % m) / m;
  26033. }
  26034. var MAX_DIMENSIONS = 3;
  26035. function x(d) {
  26036. return d.x;
  26037. }
  26038. function y(d) {
  26039. return d.y;
  26040. }
  26041. function z(d) {
  26042. return d.z;
  26043. }
  26044. var initialRadius = 10,
  26045. initialAngleRoll = Math.PI * (3 - Math.sqrt(5)), // Golden ratio angle
  26046. initialAngleYaw = Math.PI * 20 / (9 + Math.sqrt(221)); // Markov irrational number
  26047. function forceSimulation(nodes, numDimensions) {
  26048. numDimensions = numDimensions || 2;
  26049. var nDim = Math.min(MAX_DIMENSIONS, Math.max(1, Math.round(numDimensions))),
  26050. simulation,
  26051. alpha = 1,
  26052. alphaMin = 0.001,
  26053. alphaDecay = 1 - Math.pow(alphaMin, 1 / 300),
  26054. alphaTarget = 0,
  26055. velocityDecay = 0.6,
  26056. forces = new Map(),
  26057. stepper = timer(step),
  26058. event = dispatch("tick", "end"),
  26059. random = lcg();
  26060. if (nodes == null) nodes = [];
  26061. function step() {
  26062. tick();
  26063. event.call("tick", simulation);
  26064. if (alpha < alphaMin) {
  26065. stepper.stop();
  26066. event.call("end", simulation);
  26067. }
  26068. }
  26069. function tick(iterations) {
  26070. var i, n = nodes.length, node;
  26071. if (iterations === undefined) iterations = 1;
  26072. for (var k = 0; k < iterations; ++k) {
  26073. alpha += (alphaTarget - alpha) * alphaDecay;
  26074. forces.forEach(function (force) {
  26075. force(alpha);
  26076. });
  26077. for (i = 0; i < n; ++i) {
  26078. node = nodes[i];
  26079. if (node.fx == null) node.x += node.vx *= velocityDecay;
  26080. else node.x = node.fx, node.vx = 0;
  26081. if (nDim > 1) {
  26082. if (node.fy == null) node.y += node.vy *= velocityDecay;
  26083. else node.y = node.fy, node.vy = 0;
  26084. }
  26085. if (nDim > 2) {
  26086. if (node.fz == null) node.z += node.vz *= velocityDecay;
  26087. else node.z = node.fz, node.vz = 0;
  26088. }
  26089. }
  26090. }
  26091. return simulation;
  26092. }
  26093. function initializeNodes() {
  26094. for (var i = 0, n = nodes.length, node; i < n; ++i) {
  26095. node = nodes[i], node.index = i;
  26096. if (node.fx != null) node.x = node.fx;
  26097. if (node.fy != null) node.y = node.fy;
  26098. if (node.fz != null) node.z = node.fz;
  26099. if (isNaN(node.x) || (nDim > 1 && isNaN(node.y)) || (nDim > 2 && isNaN(node.z))) {
  26100. var radius = initialRadius * (nDim > 2 ? Math.cbrt(0.5 + i) : (nDim > 1 ? Math.sqrt(0.5 + i) : i)),
  26101. rollAngle = i * initialAngleRoll,
  26102. yawAngle = i * initialAngleYaw;
  26103. if (nDim === 1) {
  26104. node.x = radius;
  26105. } else if (nDim === 2) {
  26106. node.x = radius * Math.cos(rollAngle);
  26107. node.y = radius * Math.sin(rollAngle);
  26108. } else { // 3 dimensions: use spherical distribution along 2 irrational number angles
  26109. node.x = radius * Math.sin(rollAngle) * Math.cos(yawAngle);
  26110. node.y = radius * Math.cos(rollAngle);
  26111. node.z = radius * Math.sin(rollAngle) * Math.sin(yawAngle);
  26112. }
  26113. }
  26114. if (isNaN(node.vx) || (nDim > 1 && isNaN(node.vy)) || (nDim > 2 && isNaN(node.vz))) {
  26115. node.vx = 0;
  26116. if (nDim > 1) { node.vy = 0; }
  26117. if (nDim > 2) { node.vz = 0; }
  26118. }
  26119. }
  26120. }
  26121. function initializeForce(force) {
  26122. if (force.initialize) force.initialize(nodes, random, nDim);
  26123. return force;
  26124. }
  26125. initializeNodes();
  26126. return simulation = {
  26127. tick: tick,
  26128. restart: function() {
  26129. return stepper.restart(step), simulation;
  26130. },
  26131. stop: function() {
  26132. return stepper.stop(), simulation;
  26133. },
  26134. numDimensions: function(_) {
  26135. return arguments.length
  26136. ? (nDim = Math.min(MAX_DIMENSIONS, Math.max(1, Math.round(_))), forces.forEach(initializeForce), simulation)
  26137. : nDim;
  26138. },
  26139. nodes: function(_) {
  26140. return arguments.length ? (nodes = _, initializeNodes(), forces.forEach(initializeForce), simulation) : nodes;
  26141. },
  26142. alpha: function(_) {
  26143. return arguments.length ? (alpha = +_, simulation) : alpha;
  26144. },
  26145. alphaMin: function(_) {
  26146. return arguments.length ? (alphaMin = +_, simulation) : alphaMin;
  26147. },
  26148. alphaDecay: function(_) {
  26149. return arguments.length ? (alphaDecay = +_, simulation) : +alphaDecay;
  26150. },
  26151. alphaTarget: function(_) {
  26152. return arguments.length ? (alphaTarget = +_, simulation) : alphaTarget;
  26153. },
  26154. velocityDecay: function(_) {
  26155. return arguments.length ? (velocityDecay = 1 - _, simulation) : 1 - velocityDecay;
  26156. },
  26157. randomSource: function(_) {
  26158. return arguments.length ? (random = _, forces.forEach(initializeForce), simulation) : random;
  26159. },
  26160. force: function(name, _) {
  26161. return arguments.length > 1 ? ((_ == null ? forces.delete(name) : forces.set(name, initializeForce(_))), simulation) : forces.get(name);
  26162. },
  26163. find: function() {
  26164. var args = Array.prototype.slice.call(arguments);
  26165. var x = args.shift() || 0,
  26166. y = (nDim > 1 ? args.shift() : null) || 0,
  26167. z = (nDim > 2 ? args.shift() : null) || 0,
  26168. radius = args.shift() || Infinity;
  26169. var i = 0,
  26170. n = nodes.length,
  26171. dx,
  26172. dy,
  26173. dz,
  26174. d2,
  26175. node,
  26176. closest;
  26177. radius *= radius;
  26178. for (i = 0; i < n; ++i) {
  26179. node = nodes[i];
  26180. dx = x - node.x;
  26181. dy = y - (node.y || 0);
  26182. dz = z - (node.z ||0);
  26183. d2 = dx * dx + dy * dy + dz * dz;
  26184. if (d2 < radius) closest = node, radius = d2;
  26185. }
  26186. return closest;
  26187. },
  26188. on: function(name, _) {
  26189. return arguments.length > 1 ? (event.on(name, _), simulation) : event.on(name);
  26190. }
  26191. };
  26192. }
  26193. function forceManyBody() {
  26194. var nodes,
  26195. nDim,
  26196. node,
  26197. random,
  26198. alpha,
  26199. strength = constant(-30),
  26200. strengths,
  26201. distanceMin2 = 1,
  26202. distanceMax2 = Infinity,
  26203. theta2 = 0.81;
  26204. function force(_) {
  26205. var i,
  26206. n = nodes.length,
  26207. tree =
  26208. (nDim === 1 ? binarytree(nodes, x)
  26209. :(nDim === 2 ? quadtree(nodes, x, y)
  26210. :(nDim === 3 ? octree(nodes, x, y, z)
  26211. :null
  26212. ))).visitAfter(accumulate);
  26213. for (alpha = _, i = 0; i < n; ++i) node = nodes[i], tree.visit(apply);
  26214. }
  26215. function initialize() {
  26216. if (!nodes) return;
  26217. var i, n = nodes.length, node;
  26218. strengths = new Array(n);
  26219. for (i = 0; i < n; ++i) node = nodes[i], strengths[node.index] = +strength(node, i, nodes);
  26220. }
  26221. function accumulate(treeNode) {
  26222. var strength = 0, q, c, weight = 0, x, y, z, i;
  26223. var numChildren = treeNode.length;
  26224. // For internal nodes, accumulate forces from children.
  26225. if (numChildren) {
  26226. for (x = y = z = i = 0; i < numChildren; ++i) {
  26227. if ((q = treeNode[i]) && (c = Math.abs(q.value))) {
  26228. strength += q.value, weight += c, x += c * (q.x || 0), y += c * (q.y || 0), z += c * (q.z || 0);
  26229. }
  26230. }
  26231. strength *= Math.sqrt(4 / numChildren); // scale accumulated strength according to number of dimensions
  26232. treeNode.x = x / weight;
  26233. if (nDim > 1) { treeNode.y = y / weight; }
  26234. if (nDim > 2) { treeNode.z = z / weight; }
  26235. }
  26236. // For leaf nodes, accumulate forces from coincident nodes.
  26237. else {
  26238. q = treeNode;
  26239. q.x = q.data.x;
  26240. if (nDim > 1) { q.y = q.data.y; }
  26241. if (nDim > 2) { q.z = q.data.z; }
  26242. do strength += strengths[q.data.index];
  26243. while (q = q.next);
  26244. }
  26245. treeNode.value = strength;
  26246. }
  26247. function apply(treeNode, x1, arg1, arg2, arg3) {
  26248. if (!treeNode.value) return true;
  26249. var x2 = [arg1, arg2, arg3][nDim-1];
  26250. var x = treeNode.x - node.x,
  26251. y = (nDim > 1 ? treeNode.y - node.y : 0),
  26252. z = (nDim > 2 ? treeNode.z - node.z : 0),
  26253. w = x2 - x1,
  26254. l = x * x + y * y + z * z;
  26255. // Apply the Barnes-Hut approximation if possible.
  26256. // Limit forces for very close nodes; randomize direction if coincident.
  26257. if (w * w / theta2 < l) {
  26258. if (l < distanceMax2) {
  26259. if (x === 0) x = jiggle(random), l += x * x;
  26260. if (nDim > 1 && y === 0) y = jiggle(random), l += y * y;
  26261. if (nDim > 2 && z === 0) z = jiggle(random), l += z * z;
  26262. if (l < distanceMin2) l = Math.sqrt(distanceMin2 * l);
  26263. node.vx += x * treeNode.value * alpha / l;
  26264. if (nDim > 1) { node.vy += y * treeNode.value * alpha / l; }
  26265. if (nDim > 2) { node.vz += z * treeNode.value * alpha / l; }
  26266. }
  26267. return true;
  26268. }
  26269. // Otherwise, process points directly.
  26270. else if (treeNode.length || l >= distanceMax2) return;
  26271. // Limit forces for very close nodes; randomize direction if coincident.
  26272. if (treeNode.data !== node || treeNode.next) {
  26273. if (x === 0) x = jiggle(random), l += x * x;
  26274. if (nDim > 1 && y === 0) y = jiggle(random), l += y * y;
  26275. if (nDim > 2 && z === 0) z = jiggle(random), l += z * z;
  26276. if (l < distanceMin2) l = Math.sqrt(distanceMin2 * l);
  26277. }
  26278. do if (treeNode.data !== node) {
  26279. w = strengths[treeNode.data.index] * alpha / l;
  26280. node.vx += x * w;
  26281. if (nDim > 1) { node.vy += y * w; }
  26282. if (nDim > 2) { node.vz += z * w; }
  26283. } while (treeNode = treeNode.next);
  26284. }
  26285. force.initialize = function(_nodes, ...args) {
  26286. nodes = _nodes;
  26287. random = args.find(arg => typeof arg === 'function') || Math.random;
  26288. nDim = args.find(arg => [1, 2, 3].includes(arg)) || 2;
  26289. initialize();
  26290. };
  26291. force.strength = function(_) {
  26292. return arguments.length ? (strength = typeof _ === "function" ? _ : constant(+_), initialize(), force) : strength;
  26293. };
  26294. force.distanceMin = function(_) {
  26295. return arguments.length ? (distanceMin2 = _ * _, force) : Math.sqrt(distanceMin2);
  26296. };
  26297. force.distanceMax = function(_) {
  26298. return arguments.length ? (distanceMax2 = _ * _, force) : Math.sqrt(distanceMax2);
  26299. };
  26300. force.theta = function(_) {
  26301. return arguments.length ? (theta2 = _ * _, force) : Math.sqrt(theta2);
  26302. };
  26303. return force;
  26304. }
  26305. function forceRadial(radius, x, y, z) {
  26306. var nodes,
  26307. nDim,
  26308. strength = constant(0.1),
  26309. strengths,
  26310. radiuses;
  26311. if (typeof radius !== "function") radius = constant(+radius);
  26312. if (x == null) x = 0;
  26313. if (y == null) y = 0;
  26314. if (z == null) z = 0;
  26315. function force(alpha) {
  26316. for (var i = 0, n = nodes.length; i < n; ++i) {
  26317. var node = nodes[i],
  26318. dx = node.x - x || 1e-6,
  26319. dy = (node.y || 0) - y || 1e-6,
  26320. dz = (node.z || 0) - z || 1e-6,
  26321. r = Math.sqrt(dx * dx + dy * dy + dz * dz),
  26322. k = (radiuses[i] - r) * strengths[i] * alpha / r;
  26323. node.vx += dx * k;
  26324. if (nDim>1) { node.vy += dy * k; }
  26325. if (nDim>2) { node.vz += dz * k; }
  26326. }
  26327. }
  26328. function initialize() {
  26329. if (!nodes) return;
  26330. var i, n = nodes.length;
  26331. strengths = new Array(n);
  26332. radiuses = new Array(n);
  26333. for (i = 0; i < n; ++i) {
  26334. radiuses[i] = +radius(nodes[i], i, nodes);
  26335. strengths[i] = isNaN(radiuses[i]) ? 0 : +strength(nodes[i], i, nodes);
  26336. }
  26337. }
  26338. force.initialize = function(initNodes, ...args) {
  26339. nodes = initNodes;
  26340. nDim = args.find(arg => [1, 2, 3].includes(arg)) || 2;
  26341. initialize();
  26342. };
  26343. force.strength = function(_) {
  26344. return arguments.length ? (strength = typeof _ === "function" ? _ : constant(+_), initialize(), force) : strength;
  26345. };
  26346. force.radius = function(_) {
  26347. return arguments.length ? (radius = typeof _ === "function" ? _ : constant(+_), initialize(), force) : radius;
  26348. };
  26349. force.x = function(_) {
  26350. return arguments.length ? (x = +_, force) : x;
  26351. };
  26352. force.y = function(_) {
  26353. return arguments.length ? (y = +_, force) : y;
  26354. };
  26355. force.z = function(_) {
  26356. return arguments.length ? (z = +_, force) : z;
  26357. };
  26358. return force;
  26359. }
  26360. var ngraph_events = function eventify(subject) {
  26361. validateSubject(subject);
  26362. var eventsStorage = createEventsStorage(subject);
  26363. subject.on = eventsStorage.on;
  26364. subject.off = eventsStorage.off;
  26365. subject.fire = eventsStorage.fire;
  26366. return subject;
  26367. };
  26368. function createEventsStorage(subject) {
  26369. // Store all event listeners to this hash. Key is event name, value is array
  26370. // of callback records.
  26371. //
  26372. // A callback record consists of callback function and its optional context:
  26373. // { 'eventName' => [{callback: function, ctx: object}] }
  26374. var registeredEvents = Object.create(null);
  26375. return {
  26376. on: function (eventName, callback, ctx) {
  26377. if (typeof callback !== 'function') {
  26378. throw new Error('callback is expected to be a function');
  26379. }
  26380. var handlers = registeredEvents[eventName];
  26381. if (!handlers) {
  26382. handlers = registeredEvents[eventName] = [];
  26383. }
  26384. handlers.push({callback: callback, ctx: ctx});
  26385. return subject;
  26386. },
  26387. off: function (eventName, callback) {
  26388. var wantToRemoveAll = (typeof eventName === 'undefined');
  26389. if (wantToRemoveAll) {
  26390. // Killing old events storage should be enough in this case:
  26391. registeredEvents = Object.create(null);
  26392. return subject;
  26393. }
  26394. if (registeredEvents[eventName]) {
  26395. var deleteAllCallbacksForEvent = (typeof callback !== 'function');
  26396. if (deleteAllCallbacksForEvent) {
  26397. delete registeredEvents[eventName];
  26398. } else {
  26399. var callbacks = registeredEvents[eventName];
  26400. for (var i = 0; i < callbacks.length; ++i) {
  26401. if (callbacks[i].callback === callback) {
  26402. callbacks.splice(i, 1);
  26403. }
  26404. }
  26405. }
  26406. }
  26407. return subject;
  26408. },
  26409. fire: function (eventName) {
  26410. var callbacks = registeredEvents[eventName];
  26411. if (!callbacks) {
  26412. return subject;
  26413. }
  26414. var fireArguments;
  26415. if (arguments.length > 1) {
  26416. fireArguments = Array.prototype.splice.call(arguments, 1);
  26417. }
  26418. for(var i = 0; i < callbacks.length; ++i) {
  26419. var callbackInfo = callbacks[i];
  26420. callbackInfo.callback.apply(callbackInfo.ctx, fireArguments);
  26421. }
  26422. return subject;
  26423. }
  26424. };
  26425. }
  26426. function validateSubject(subject) {
  26427. if (!subject) {
  26428. throw new Error('Eventify cannot use falsy object as events subject');
  26429. }
  26430. var reservedWords = ['on', 'fire', 'off'];
  26431. for (var i = 0; i < reservedWords.length; ++i) {
  26432. if (subject.hasOwnProperty(reservedWords[i])) {
  26433. throw new Error("Subject cannot be eventified, since it already has property '" + reservedWords[i] + "'");
  26434. }
  26435. }
  26436. }
  26437. /**
  26438. * @fileOverview Contains definition of the core graph object.
  26439. */
  26440. // TODO: need to change storage layer:
  26441. // 1. Be able to get all nodes O(1)
  26442. // 2. Be able to get number of links O(1)
  26443. /**
  26444. * @example
  26445. * var graph = require('ngraph.graph')();
  26446. * graph.addNode(1); // graph has one node.
  26447. * graph.addLink(2, 3); // now graph contains three nodes and one link.
  26448. *
  26449. */
  26450. var ngraph_graph = createGraph;
  26451. var eventify$1 = ngraph_events;
  26452. /**
  26453. * Creates a new graph
  26454. */
  26455. function createGraph(options) {
  26456. // Graph structure is maintained as dictionary of nodes
  26457. // and array of links. Each node has 'links' property which
  26458. // hold all links related to that node. And general links
  26459. // array is used to speed up all links enumeration. This is inefficient
  26460. // in terms of memory, but simplifies coding.
  26461. options = options || {};
  26462. if ('uniqueLinkId' in options) {
  26463. console.warn(
  26464. 'ngraph.graph: Starting from version 0.14 `uniqueLinkId` is deprecated.\n' +
  26465. 'Use `multigraph` option instead\n',
  26466. '\n',
  26467. 'Note: there is also change in default behavior: From now on each graph\n'+
  26468. 'is considered to be not a multigraph by default (each edge is unique).'
  26469. );
  26470. options.multigraph = options.uniqueLinkId;
  26471. }
  26472. // Dear reader, the non-multigraphs do not guarantee that there is only
  26473. // one link for a given pair of node. When this option is set to false
  26474. // we can save some memory and CPU (18% faster for non-multigraph);
  26475. if (options.multigraph === undefined) options.multigraph = false;
  26476. if (typeof Map !== 'function') {
  26477. // TODO: Should we polyfill it ourselves? We don't use much operations there..
  26478. throw new Error('ngraph.graph requires `Map` to be defined. Please polyfill it before using ngraph');
  26479. }
  26480. var nodes = new Map();
  26481. var links = [],
  26482. // Hash of multi-edges. Used to track ids of edges between same nodes
  26483. multiEdges = {},
  26484. suspendEvents = 0,
  26485. createLink = options.multigraph ? createUniqueLink : createSingleLink,
  26486. // Our graph API provides means to listen to graph changes. Users can subscribe
  26487. // to be notified about changes in the graph by using `on` method. However
  26488. // in some cases they don't use it. To avoid unnecessary memory consumption
  26489. // we will not record graph changes until we have at least one subscriber.
  26490. // Code below supports this optimization.
  26491. //
  26492. // Accumulates all changes made during graph updates.
  26493. // Each change element contains:
  26494. // changeType - one of the strings: 'add', 'remove' or 'update';
  26495. // node - if change is related to node this property is set to changed graph's node;
  26496. // link - if change is related to link this property is set to changed graph's link;
  26497. changes = [],
  26498. recordLinkChange = noop,
  26499. recordNodeChange = noop,
  26500. enterModification = noop,
  26501. exitModification = noop;
  26502. // this is our public API:
  26503. var graphPart = {
  26504. /**
  26505. * Adds node to the graph. If node with given id already exists in the graph
  26506. * its data is extended with whatever comes in 'data' argument.
  26507. *
  26508. * @param nodeId the node's identifier. A string or number is preferred.
  26509. * @param [data] additional data for the node being added. If node already
  26510. * exists its data object is augmented with the new one.
  26511. *
  26512. * @return {node} The newly added node or node with given id if it already exists.
  26513. */
  26514. addNode: addNode,
  26515. /**
  26516. * Adds a link to the graph. The function always create a new
  26517. * link between two nodes. If one of the nodes does not exists
  26518. * a new node is created.
  26519. *
  26520. * @param fromId link start node id;
  26521. * @param toId link end node id;
  26522. * @param [data] additional data to be set on the new link;
  26523. *
  26524. * @return {link} The newly created link
  26525. */
  26526. addLink: addLink,
  26527. /**
  26528. * Removes link from the graph. If link does not exist does nothing.
  26529. *
  26530. * @param link - object returned by addLink() or getLinks() methods.
  26531. *
  26532. * @returns true if link was removed; false otherwise.
  26533. */
  26534. removeLink: removeLink,
  26535. /**
  26536. * Removes node with given id from the graph. If node does not exist in the graph
  26537. * does nothing.
  26538. *
  26539. * @param nodeId node's identifier passed to addNode() function.
  26540. *
  26541. * @returns true if node was removed; false otherwise.
  26542. */
  26543. removeNode: removeNode,
  26544. /**
  26545. * Gets node with given identifier. If node does not exist undefined value is returned.
  26546. *
  26547. * @param nodeId requested node identifier;
  26548. *
  26549. * @return {node} in with requested identifier or undefined if no such node exists.
  26550. */
  26551. getNode: getNode,
  26552. /**
  26553. * Gets number of nodes in this graph.
  26554. *
  26555. * @return number of nodes in the graph.
  26556. */
  26557. getNodeCount: getNodeCount,
  26558. /**
  26559. * Gets total number of links in the graph.
  26560. */
  26561. getLinkCount: getLinkCount,
  26562. /**
  26563. * Synonym for `getLinkCount()`
  26564. */
  26565. getLinksCount: getLinkCount,
  26566. /**
  26567. * Synonym for `getNodeCount()`
  26568. */
  26569. getNodesCount: getNodeCount,
  26570. /**
  26571. * Gets all links (inbound and outbound) from the node with given id.
  26572. * If node with given id is not found null is returned.
  26573. *
  26574. * @param nodeId requested node identifier.
  26575. *
  26576. * @return Array of links from and to requested node if such node exists;
  26577. * otherwise null is returned.
  26578. */
  26579. getLinks: getLinks,
  26580. /**
  26581. * Invokes callback on each node of the graph.
  26582. *
  26583. * @param {Function(node)} callback Function to be invoked. The function
  26584. * is passed one argument: visited node.
  26585. */
  26586. forEachNode: forEachNode,
  26587. /**
  26588. * Invokes callback on every linked (adjacent) node to the given one.
  26589. *
  26590. * @param nodeId Identifier of the requested node.
  26591. * @param {Function(node, link)} callback Function to be called on all linked nodes.
  26592. * The function is passed two parameters: adjacent node and link object itself.
  26593. * @param oriented if true graph treated as oriented.
  26594. */
  26595. forEachLinkedNode: forEachLinkedNode,
  26596. /**
  26597. * Enumerates all links in the graph
  26598. *
  26599. * @param {Function(link)} callback Function to be called on all links in the graph.
  26600. * The function is passed one parameter: graph's link object.
  26601. *
  26602. * Link object contains at least the following fields:
  26603. * fromId - node id where link starts;
  26604. * toId - node id where link ends,
  26605. * data - additional data passed to graph.addLink() method.
  26606. */
  26607. forEachLink: forEachLink,
  26608. /**
  26609. * Suspend all notifications about graph changes until
  26610. * endUpdate is called.
  26611. */
  26612. beginUpdate: enterModification,
  26613. /**
  26614. * Resumes all notifications about graph changes and fires
  26615. * graph 'changed' event in case there are any pending changes.
  26616. */
  26617. endUpdate: exitModification,
  26618. /**
  26619. * Removes all nodes and links from the graph.
  26620. */
  26621. clear: clear,
  26622. /**
  26623. * Detects whether there is a link between two nodes.
  26624. * Operation complexity is O(n) where n - number of links of a node.
  26625. * NOTE: this function is synonim for getLink()
  26626. *
  26627. * @returns link if there is one. null otherwise.
  26628. */
  26629. hasLink: getLink,
  26630. /**
  26631. * Detects whether there is a node with given id
  26632. *
  26633. * Operation complexity is O(1)
  26634. * NOTE: this function is synonim for getNode()
  26635. *
  26636. * @returns node if there is one; Falsy value otherwise.
  26637. */
  26638. hasNode: getNode,
  26639. /**
  26640. * Gets an edge between two nodes.
  26641. * Operation complexity is O(n) where n - number of links of a node.
  26642. *
  26643. * @param {string} fromId link start identifier
  26644. * @param {string} toId link end identifier
  26645. *
  26646. * @returns link if there is one. null otherwise.
  26647. */
  26648. getLink: getLink
  26649. };
  26650. // this will add `on()` and `fire()` methods.
  26651. eventify$1(graphPart);
  26652. monitorSubscribers();
  26653. return graphPart;
  26654. function monitorSubscribers() {
  26655. var realOn = graphPart.on;
  26656. // replace real `on` with our temporary on, which will trigger change
  26657. // modification monitoring:
  26658. graphPart.on = on;
  26659. function on() {
  26660. // now it's time to start tracking stuff:
  26661. graphPart.beginUpdate = enterModification = enterModificationReal;
  26662. graphPart.endUpdate = exitModification = exitModificationReal;
  26663. recordLinkChange = recordLinkChangeReal;
  26664. recordNodeChange = recordNodeChangeReal;
  26665. // this will replace current `on` method with real pub/sub from `eventify`.
  26666. graphPart.on = realOn;
  26667. // delegate to real `on` handler:
  26668. return realOn.apply(graphPart, arguments);
  26669. }
  26670. }
  26671. function recordLinkChangeReal(link, changeType) {
  26672. changes.push({
  26673. link: link,
  26674. changeType: changeType
  26675. });
  26676. }
  26677. function recordNodeChangeReal(node, changeType) {
  26678. changes.push({
  26679. node: node,
  26680. changeType: changeType
  26681. });
  26682. }
  26683. function addNode(nodeId, data) {
  26684. if (nodeId === undefined) {
  26685. throw new Error('Invalid node identifier');
  26686. }
  26687. enterModification();
  26688. var node = getNode(nodeId);
  26689. if (!node) {
  26690. node = new Node(nodeId, data);
  26691. recordNodeChange(node, 'add');
  26692. } else {
  26693. node.data = data;
  26694. recordNodeChange(node, 'update');
  26695. }
  26696. nodes.set(nodeId, node);
  26697. exitModification();
  26698. return node;
  26699. }
  26700. function getNode(nodeId) {
  26701. return nodes.get(nodeId);
  26702. }
  26703. function removeNode(nodeId) {
  26704. var node = getNode(nodeId);
  26705. if (!node) {
  26706. return false;
  26707. }
  26708. enterModification();
  26709. var prevLinks = node.links;
  26710. if (prevLinks) {
  26711. node.links = null;
  26712. for(var i = 0; i < prevLinks.length; ++i) {
  26713. removeLink(prevLinks[i]);
  26714. }
  26715. }
  26716. nodes.delete(nodeId);
  26717. recordNodeChange(node, 'remove');
  26718. exitModification();
  26719. return true;
  26720. }
  26721. function addLink(fromId, toId, data) {
  26722. enterModification();
  26723. var fromNode = getNode(fromId) || addNode(fromId);
  26724. var toNode = getNode(toId) || addNode(toId);
  26725. var link = createLink(fromId, toId, data);
  26726. links.push(link);
  26727. // TODO: this is not cool. On large graphs potentially would consume more memory.
  26728. addLinkToNode(fromNode, link);
  26729. if (fromId !== toId) {
  26730. // make sure we are not duplicating links for self-loops
  26731. addLinkToNode(toNode, link);
  26732. }
  26733. recordLinkChange(link, 'add');
  26734. exitModification();
  26735. return link;
  26736. }
  26737. function createSingleLink(fromId, toId, data) {
  26738. var linkId = makeLinkId(fromId, toId);
  26739. return new Link(fromId, toId, data, linkId);
  26740. }
  26741. function createUniqueLink(fromId, toId, data) {
  26742. // TODO: Get rid of this method.
  26743. var linkId = makeLinkId(fromId, toId);
  26744. var isMultiEdge = multiEdges.hasOwnProperty(linkId);
  26745. if (isMultiEdge || getLink(fromId, toId)) {
  26746. if (!isMultiEdge) {
  26747. multiEdges[linkId] = 0;
  26748. }
  26749. var suffix = '@' + (++multiEdges[linkId]);
  26750. linkId = makeLinkId(fromId + suffix, toId + suffix);
  26751. }
  26752. return new Link(fromId, toId, data, linkId);
  26753. }
  26754. function getNodeCount() {
  26755. return nodes.size;
  26756. }
  26757. function getLinkCount() {
  26758. return links.length;
  26759. }
  26760. function getLinks(nodeId) {
  26761. var node = getNode(nodeId);
  26762. return node ? node.links : null;
  26763. }
  26764. function removeLink(link) {
  26765. if (!link) {
  26766. return false;
  26767. }
  26768. var idx = indexOfElementInArray(link, links);
  26769. if (idx < 0) {
  26770. return false;
  26771. }
  26772. enterModification();
  26773. links.splice(idx, 1);
  26774. var fromNode = getNode(link.fromId);
  26775. var toNode = getNode(link.toId);
  26776. if (fromNode) {
  26777. idx = indexOfElementInArray(link, fromNode.links);
  26778. if (idx >= 0) {
  26779. fromNode.links.splice(idx, 1);
  26780. }
  26781. }
  26782. if (toNode) {
  26783. idx = indexOfElementInArray(link, toNode.links);
  26784. if (idx >= 0) {
  26785. toNode.links.splice(idx, 1);
  26786. }
  26787. }
  26788. recordLinkChange(link, 'remove');
  26789. exitModification();
  26790. return true;
  26791. }
  26792. function getLink(fromNodeId, toNodeId) {
  26793. // TODO: Use sorted links to speed this up
  26794. var node = getNode(fromNodeId),
  26795. i;
  26796. if (!node || !node.links) {
  26797. return null;
  26798. }
  26799. for (i = 0; i < node.links.length; ++i) {
  26800. var link = node.links[i];
  26801. if (link.fromId === fromNodeId && link.toId === toNodeId) {
  26802. return link;
  26803. }
  26804. }
  26805. return null; // no link.
  26806. }
  26807. function clear() {
  26808. enterModification();
  26809. forEachNode(function(node) {
  26810. removeNode(node.id);
  26811. });
  26812. exitModification();
  26813. }
  26814. function forEachLink(callback) {
  26815. var i, length;
  26816. if (typeof callback === 'function') {
  26817. for (i = 0, length = links.length; i < length; ++i) {
  26818. callback(links[i]);
  26819. }
  26820. }
  26821. }
  26822. function forEachLinkedNode(nodeId, callback, oriented) {
  26823. var node = getNode(nodeId);
  26824. if (node && node.links && typeof callback === 'function') {
  26825. if (oriented) {
  26826. return forEachOrientedLink(node.links, nodeId, callback);
  26827. } else {
  26828. return forEachNonOrientedLink(node.links, nodeId, callback);
  26829. }
  26830. }
  26831. }
  26832. function forEachNonOrientedLink(links, nodeId, callback) {
  26833. var quitFast;
  26834. for (var i = 0; i < links.length; ++i) {
  26835. var link = links[i];
  26836. var linkedNodeId = link.fromId === nodeId ? link.toId : link.fromId;
  26837. quitFast = callback(nodes.get(linkedNodeId), link);
  26838. if (quitFast) {
  26839. return true; // Client does not need more iterations. Break now.
  26840. }
  26841. }
  26842. }
  26843. function forEachOrientedLink(links, nodeId, callback) {
  26844. var quitFast;
  26845. for (var i = 0; i < links.length; ++i) {
  26846. var link = links[i];
  26847. if (link.fromId === nodeId) {
  26848. quitFast = callback(nodes.get(link.toId), link);
  26849. if (quitFast) {
  26850. return true; // Client does not need more iterations. Break now.
  26851. }
  26852. }
  26853. }
  26854. }
  26855. // we will not fire anything until users of this library explicitly call `on()`
  26856. // method.
  26857. function noop() {}
  26858. // Enter, Exit modification allows bulk graph updates without firing events.
  26859. function enterModificationReal() {
  26860. suspendEvents += 1;
  26861. }
  26862. function exitModificationReal() {
  26863. suspendEvents -= 1;
  26864. if (suspendEvents === 0 && changes.length > 0) {
  26865. graphPart.fire('changed', changes);
  26866. changes.length = 0;
  26867. }
  26868. }
  26869. function forEachNode(callback) {
  26870. if (typeof callback !== 'function') {
  26871. throw new Error('Function is expected to iterate over graph nodes. You passed ' + callback);
  26872. }
  26873. var valuesIterator = nodes.values();
  26874. var nextValue = valuesIterator.next();
  26875. while (!nextValue.done) {
  26876. if (callback(nextValue.value)) {
  26877. return true; // client doesn't want to proceed. Return.
  26878. }
  26879. nextValue = valuesIterator.next();
  26880. }
  26881. }
  26882. }
  26883. // need this for old browsers. Should this be a separate module?
  26884. function indexOfElementInArray(element, array) {
  26885. if (!array) return -1;
  26886. if (array.indexOf) {
  26887. return array.indexOf(element);
  26888. }
  26889. var len = array.length,
  26890. i;
  26891. for (i = 0; i < len; i += 1) {
  26892. if (array[i] === element) {
  26893. return i;
  26894. }
  26895. }
  26896. return -1;
  26897. }
  26898. /**
  26899. * Internal structure to represent node;
  26900. */
  26901. function Node(id, data) {
  26902. this.id = id;
  26903. this.links = null;
  26904. this.data = data;
  26905. }
  26906. function addLinkToNode(node, link) {
  26907. if (node.links) {
  26908. node.links.push(link);
  26909. } else {
  26910. node.links = [link];
  26911. }
  26912. }
  26913. /**
  26914. * Internal structure to represent links;
  26915. */
  26916. function Link(fromId, toId, data, id) {
  26917. this.fromId = fromId;
  26918. this.toId = toId;
  26919. this.data = data;
  26920. this.id = id;
  26921. }
  26922. function makeLinkId(fromId, toId) {
  26923. return fromId.toString() + '👉 ' + toId.toString();
  26924. }
  26925. var ngraph_forcelayout = {exports: {}};
  26926. var generateCreateBody = {exports: {}};
  26927. var getVariableName$2 = function getVariableName(index) {
  26928. if (index === 0) return 'x';
  26929. if (index === 1) return 'y';
  26930. if (index === 2) return 'z';
  26931. return 'c' + (index + 1);
  26932. };
  26933. const getVariableName$1 = getVariableName$2;
  26934. var createPatternBuilder$6 = function createPatternBuilder(dimension) {
  26935. return pattern;
  26936. function pattern(template, config) {
  26937. let indent = (config && config.indent) || 0;
  26938. let join = (config && config.join !== undefined) ? config.join : '\n';
  26939. let indentString = Array(indent + 1).join(' ');
  26940. let buffer = [];
  26941. for (let i = 0; i < dimension; ++i) {
  26942. let variableName = getVariableName$1(i);
  26943. let prefix = (i === 0) ? '' : indentString;
  26944. buffer.push(prefix + template.replace(/{var}/g, variableName));
  26945. }
  26946. return buffer.join(join);
  26947. }
  26948. };
  26949. const createPatternBuilder$5 = createPatternBuilder$6;
  26950. generateCreateBody.exports = generateCreateBodyFunction$1;
  26951. generateCreateBody.exports.generateCreateBodyFunctionBody = generateCreateBodyFunctionBody;
  26952. // InlineTransform: getVectorCode
  26953. generateCreateBody.exports.getVectorCode = getVectorCode;
  26954. // InlineTransform: getBodyCode
  26955. generateCreateBody.exports.getBodyCode = getBodyCode;
  26956. // InlineTransformExport: module.exports = function() { return Body; }
  26957. function generateCreateBodyFunction$1(dimension, debugSetters) {
  26958. let code = generateCreateBodyFunctionBody(dimension, debugSetters);
  26959. let {Body} = (new Function(code))();
  26960. return Body;
  26961. }
  26962. function generateCreateBodyFunctionBody(dimension, debugSetters) {
  26963. let code = `
  26964. ${getVectorCode(dimension, debugSetters)}
  26965. ${getBodyCode(dimension)}
  26966. return {Body: Body, Vector: Vector};
  26967. `;
  26968. return code;
  26969. }
  26970. function getBodyCode(dimension) {
  26971. let pattern = createPatternBuilder$5(dimension);
  26972. let variableList = pattern('{var}', {join: ', '});
  26973. return `
  26974. function Body(${variableList}) {
  26975. this.isPinned = false;
  26976. this.pos = new Vector(${variableList});
  26977. this.force = new Vector();
  26978. this.velocity = new Vector();
  26979. this.mass = 1;
  26980. this.springCount = 0;
  26981. this.springLength = 0;
  26982. }
  26983. Body.prototype.reset = function() {
  26984. this.force.reset();
  26985. this.springCount = 0;
  26986. this.springLength = 0;
  26987. }
  26988. Body.prototype.setPosition = function (${variableList}) {
  26989. ${pattern('this.pos.{var} = {var} || 0;', {indent: 2})}
  26990. };`;
  26991. }
  26992. function getVectorCode(dimension, debugSetters) {
  26993. let pattern = createPatternBuilder$5(dimension);
  26994. let setters = '';
  26995. if (debugSetters) {
  26996. setters = `${pattern("\n\
  26997. var v{var};\n\
  26998. Object.defineProperty(this, '{var}', {\n\
  26999. set: function(v) { \n\
  27000. if (!Number.isFinite(v)) throw new Error('Cannot set non-numbers to {var}');\n\
  27001. v{var} = v; \n\
  27002. },\n\
  27003. get: function() { return v{var}; }\n\
  27004. });")}`;
  27005. }
  27006. let variableList = pattern('{var}', {join: ', '});
  27007. return `function Vector(${variableList}) {
  27008. ${setters}
  27009. if (typeof arguments[0] === 'object') {
  27010. // could be another vector
  27011. let v = arguments[0];
  27012. ${pattern('if (!Number.isFinite(v.{var})) throw new Error("Expected value is not a finite number at Vector constructor ({var})");', {indent: 4})}
  27013. ${pattern('this.{var} = v.{var};', {indent: 4})}
  27014. } else {
  27015. ${pattern('this.{var} = typeof {var} === "number" ? {var} : 0;', {indent: 4})}
  27016. }
  27017. }
  27018. Vector.prototype.reset = function () {
  27019. ${pattern('this.{var} = ', {join: ''})}0;
  27020. };`;
  27021. }
  27022. var generateQuadTree = {exports: {}};
  27023. const createPatternBuilder$4 = createPatternBuilder$6;
  27024. const getVariableName = getVariableName$2;
  27025. generateQuadTree.exports = generateQuadTreeFunction$1;
  27026. generateQuadTree.exports.generateQuadTreeFunctionBody = generateQuadTreeFunctionBody;
  27027. // These exports are for InlineTransform tool.
  27028. // InlineTransform: getInsertStackCode
  27029. generateQuadTree.exports.getInsertStackCode = getInsertStackCode;
  27030. // InlineTransform: getQuadNodeCode
  27031. generateQuadTree.exports.getQuadNodeCode = getQuadNodeCode;
  27032. // InlineTransform: isSamePosition
  27033. generateQuadTree.exports.isSamePosition = isSamePosition;
  27034. // InlineTransform: getChildBodyCode
  27035. generateQuadTree.exports.getChildBodyCode = getChildBodyCode;
  27036. // InlineTransform: setChildBodyCode
  27037. generateQuadTree.exports.setChildBodyCode = setChildBodyCode;
  27038. function generateQuadTreeFunction$1(dimension) {
  27039. let code = generateQuadTreeFunctionBody(dimension);
  27040. return (new Function(code))();
  27041. }
  27042. function generateQuadTreeFunctionBody(dimension) {
  27043. let pattern = createPatternBuilder$4(dimension);
  27044. let quadCount = Math.pow(2, dimension);
  27045. let code = `
  27046. ${getInsertStackCode()}
  27047. ${getQuadNodeCode(dimension)}
  27048. ${isSamePosition(dimension)}
  27049. ${getChildBodyCode(dimension)}
  27050. ${setChildBodyCode(dimension)}
  27051. function createQuadTree(options, random) {
  27052. options = options || {};
  27053. options.gravity = typeof options.gravity === 'number' ? options.gravity : -1;
  27054. options.theta = typeof options.theta === 'number' ? options.theta : 0.8;
  27055. var gravity = options.gravity;
  27056. var updateQueue = [];
  27057. var insertStack = new InsertStack();
  27058. var theta = options.theta;
  27059. var nodesCache = [];
  27060. var currentInCache = 0;
  27061. var root = newNode();
  27062. return {
  27063. insertBodies: insertBodies,
  27064. /**
  27065. * Gets root node if it is present
  27066. */
  27067. getRoot: function() {
  27068. return root;
  27069. },
  27070. updateBodyForce: update,
  27071. options: function(newOptions) {
  27072. if (newOptions) {
  27073. if (typeof newOptions.gravity === 'number') {
  27074. gravity = newOptions.gravity;
  27075. }
  27076. if (typeof newOptions.theta === 'number') {
  27077. theta = newOptions.theta;
  27078. }
  27079. return this;
  27080. }
  27081. return {
  27082. gravity: gravity,
  27083. theta: theta
  27084. };
  27085. }
  27086. };
  27087. function newNode() {
  27088. // To avoid pressure on GC we reuse nodes.
  27089. var node = nodesCache[currentInCache];
  27090. if (node) {
  27091. ${assignQuads(' node.')}
  27092. node.body = null;
  27093. node.mass = ${pattern('node.mass_{var} = ', {join: ''})}0;
  27094. ${pattern('node.min_{var} = node.max_{var} = ', {join: ''})}0;
  27095. } else {
  27096. node = new QuadNode();
  27097. nodesCache[currentInCache] = node;
  27098. }
  27099. ++currentInCache;
  27100. return node;
  27101. }
  27102. function update(sourceBody) {
  27103. var queue = updateQueue;
  27104. var v;
  27105. ${pattern('var d{var};', {indent: 4})}
  27106. var r;
  27107. ${pattern('var f{var} = 0;', {indent: 4})}
  27108. var queueLength = 1;
  27109. var shiftIdx = 0;
  27110. var pushIdx = 1;
  27111. queue[0] = root;
  27112. while (queueLength) {
  27113. var node = queue[shiftIdx];
  27114. var body = node.body;
  27115. queueLength -= 1;
  27116. shiftIdx += 1;
  27117. var differentBody = (body !== sourceBody);
  27118. if (body && differentBody) {
  27119. // If the current node is a leaf node (and it is not source body),
  27120. // calculate the force exerted by the current node on body, and add this
  27121. // amount to body's net force.
  27122. ${pattern('d{var} = body.pos.{var} - sourceBody.pos.{var};', {indent: 8})}
  27123. r = Math.sqrt(${pattern('d{var} * d{var}', {join: ' + '})});
  27124. if (r === 0) {
  27125. // Poor man's protection against zero distance.
  27126. ${pattern('d{var} = (random.nextDouble() - 0.5) / 50;', {indent: 10})}
  27127. r = Math.sqrt(${pattern('d{var} * d{var}', {join: ' + '})});
  27128. }
  27129. // This is standard gravitation force calculation but we divide
  27130. // by r^3 to save two operations when normalizing force vector.
  27131. v = gravity * body.mass * sourceBody.mass / (r * r * r);
  27132. ${pattern('f{var} += v * d{var};', {indent: 8})}
  27133. } else if (differentBody) {
  27134. // Otherwise, calculate the ratio s / r, where s is the width of the region
  27135. // represented by the internal node, and r is the distance between the body
  27136. // and the node's center-of-mass
  27137. ${pattern('d{var} = node.mass_{var} / node.mass - sourceBody.pos.{var};', {indent: 8})}
  27138. r = Math.sqrt(${pattern('d{var} * d{var}', {join: ' + '})});
  27139. if (r === 0) {
  27140. // Sorry about code duplication. I don't want to create many functions
  27141. // right away. Just want to see performance first.
  27142. ${pattern('d{var} = (random.nextDouble() - 0.5) / 50;', {indent: 10})}
  27143. r = Math.sqrt(${pattern('d{var} * d{var}', {join: ' + '})});
  27144. }
  27145. // If s / r < θ, treat this internal node as a single body, and calculate the
  27146. // force it exerts on sourceBody, and add this amount to sourceBody's net force.
  27147. if ((node.max_${getVariableName(0)} - node.min_${getVariableName(0)}) / r < theta) {
  27148. // in the if statement above we consider node's width only
  27149. // because the region was made into square during tree creation.
  27150. // Thus there is no difference between using width or height.
  27151. v = gravity * node.mass * sourceBody.mass / (r * r * r);
  27152. ${pattern('f{var} += v * d{var};', {indent: 10})}
  27153. } else {
  27154. // Otherwise, run the procedure recursively on each of the current node's children.
  27155. // I intentionally unfolded this loop, to save several CPU cycles.
  27156. ${runRecursiveOnChildren()}
  27157. }
  27158. }
  27159. }
  27160. ${pattern('sourceBody.force.{var} += f{var};', {indent: 4})}
  27161. }
  27162. function insertBodies(bodies) {
  27163. ${pattern('var {var}min = Number.MAX_VALUE;', {indent: 4})}
  27164. ${pattern('var {var}max = Number.MIN_VALUE;', {indent: 4})}
  27165. var i = bodies.length;
  27166. // To reduce quad tree depth we are looking for exact bounding box of all particles.
  27167. while (i--) {
  27168. var pos = bodies[i].pos;
  27169. ${pattern('if (pos.{var} < {var}min) {var}min = pos.{var};', {indent: 6})}
  27170. ${pattern('if (pos.{var} > {var}max) {var}max = pos.{var};', {indent: 6})}
  27171. }
  27172. // Makes the bounds square.
  27173. var maxSideLength = -Infinity;
  27174. ${pattern('if ({var}max - {var}min > maxSideLength) maxSideLength = {var}max - {var}min ;', {indent: 4})}
  27175. currentInCache = 0;
  27176. root = newNode();
  27177. ${pattern('root.min_{var} = {var}min;', {indent: 4})}
  27178. ${pattern('root.max_{var} = {var}min + maxSideLength;', {indent: 4})}
  27179. i = bodies.length - 1;
  27180. if (i >= 0) {
  27181. root.body = bodies[i];
  27182. }
  27183. while (i--) {
  27184. insert(bodies[i], root);
  27185. }
  27186. }
  27187. function insert(newBody) {
  27188. insertStack.reset();
  27189. insertStack.push(root, newBody);
  27190. while (!insertStack.isEmpty()) {
  27191. var stackItem = insertStack.pop();
  27192. var node = stackItem.node;
  27193. var body = stackItem.body;
  27194. if (!node.body) {
  27195. // This is internal node. Update the total mass of the node and center-of-mass.
  27196. ${pattern('var {var} = body.pos.{var};', {indent: 8})}
  27197. node.mass += body.mass;
  27198. ${pattern('node.mass_{var} += body.mass * {var};', {indent: 8})}
  27199. // Recursively insert the body in the appropriate quadrant.
  27200. // But first find the appropriate quadrant.
  27201. var quadIdx = 0; // Assume we are in the 0's quad.
  27202. ${pattern('var min_{var} = node.min_{var};', {indent: 8})}
  27203. ${pattern('var max_{var} = (min_{var} + node.max_{var}) / 2;', {indent: 8})}
  27204. ${assignInsertionQuadIndex(8)}
  27205. var child = getChild(node, quadIdx);
  27206. if (!child) {
  27207. // The node is internal but this quadrant is not taken. Add
  27208. // subnode to it.
  27209. child = newNode();
  27210. ${pattern('child.min_{var} = min_{var};', {indent: 10})}
  27211. ${pattern('child.max_{var} = max_{var};', {indent: 10})}
  27212. child.body = body;
  27213. setChild(node, quadIdx, child);
  27214. } else {
  27215. // continue searching in this quadrant.
  27216. insertStack.push(child, body);
  27217. }
  27218. } else {
  27219. // We are trying to add to the leaf node.
  27220. // We have to convert current leaf into internal node
  27221. // and continue adding two nodes.
  27222. var oldBody = node.body;
  27223. node.body = null; // internal nodes do not cary bodies
  27224. if (isSamePosition(oldBody.pos, body.pos)) {
  27225. // Prevent infinite subdivision by bumping one node
  27226. // anywhere in this quadrant
  27227. var retriesCount = 3;
  27228. do {
  27229. var offset = random.nextDouble();
  27230. ${pattern('var d{var} = (node.max_{var} - node.min_{var}) * offset;', {indent: 12})}
  27231. ${pattern('oldBody.pos.{var} = node.min_{var} + d{var};', {indent: 12})}
  27232. retriesCount -= 1;
  27233. // Make sure we don't bump it out of the box. If we do, next iteration should fix it
  27234. } while (retriesCount > 0 && isSamePosition(oldBody.pos, body.pos));
  27235. if (retriesCount === 0 && isSamePosition(oldBody.pos, body.pos)) {
  27236. // This is very bad, we ran out of precision.
  27237. // if we do not return from the method we'll get into
  27238. // infinite loop here. So we sacrifice correctness of layout, and keep the app running
  27239. // Next layout iteration should get larger bounding box in the first step and fix this
  27240. return;
  27241. }
  27242. }
  27243. // Next iteration should subdivide node further.
  27244. insertStack.push(node, oldBody);
  27245. insertStack.push(node, body);
  27246. }
  27247. }
  27248. }
  27249. }
  27250. return createQuadTree;
  27251. `;
  27252. return code;
  27253. function assignInsertionQuadIndex(indentCount) {
  27254. let insertionCode = [];
  27255. let indent = Array(indentCount + 1).join(' ');
  27256. for (let i = 0; i < dimension; ++i) {
  27257. insertionCode.push(indent + `if (${getVariableName(i)} > max_${getVariableName(i)}) {`);
  27258. insertionCode.push(indent + ` quadIdx = quadIdx + ${Math.pow(2, i)};`);
  27259. insertionCode.push(indent + ` min_${getVariableName(i)} = max_${getVariableName(i)};`);
  27260. insertionCode.push(indent + ` max_${getVariableName(i)} = node.max_${getVariableName(i)};`);
  27261. insertionCode.push(indent + `}`);
  27262. }
  27263. return insertionCode.join('\n');
  27264. // if (x > max_x) { // somewhere in the eastern part.
  27265. // quadIdx = quadIdx + 1;
  27266. // left = right;
  27267. // right = node.right;
  27268. // }
  27269. }
  27270. function runRecursiveOnChildren() {
  27271. let indent = Array(11).join(' ');
  27272. let recursiveCode = [];
  27273. for (let i = 0; i < quadCount; ++i) {
  27274. recursiveCode.push(indent + `if (node.quad${i}) {`);
  27275. recursiveCode.push(indent + ` queue[pushIdx] = node.quad${i};`);
  27276. recursiveCode.push(indent + ` queueLength += 1;`);
  27277. recursiveCode.push(indent + ` pushIdx += 1;`);
  27278. recursiveCode.push(indent + `}`);
  27279. }
  27280. return recursiveCode.join('\n');
  27281. // if (node.quad0) {
  27282. // queue[pushIdx] = node.quad0;
  27283. // queueLength += 1;
  27284. // pushIdx += 1;
  27285. // }
  27286. }
  27287. function assignQuads(indent) {
  27288. // this.quad0 = null;
  27289. // this.quad1 = null;
  27290. // this.quad2 = null;
  27291. // this.quad3 = null;
  27292. let quads = [];
  27293. for (let i = 0; i < quadCount; ++i) {
  27294. quads.push(`${indent}quad${i} = null;`);
  27295. }
  27296. return quads.join('\n');
  27297. }
  27298. }
  27299. function isSamePosition(dimension) {
  27300. let pattern = createPatternBuilder$4(dimension);
  27301. return `
  27302. function isSamePosition(point1, point2) {
  27303. ${pattern('var d{var} = Math.abs(point1.{var} - point2.{var});', {indent: 2})}
  27304. return ${pattern('d{var} < 1e-8', {join: ' && '})};
  27305. }
  27306. `;
  27307. }
  27308. function setChildBodyCode(dimension) {
  27309. var quadCount = Math.pow(2, dimension);
  27310. return `
  27311. function setChild(node, idx, child) {
  27312. ${setChildBody()}
  27313. }`;
  27314. function setChildBody() {
  27315. let childBody = [];
  27316. for (let i = 0; i < quadCount; ++i) {
  27317. let prefix = (i === 0) ? ' ' : ' else ';
  27318. childBody.push(`${prefix}if (idx === ${i}) node.quad${i} = child;`);
  27319. }
  27320. return childBody.join('\n');
  27321. // if (idx === 0) node.quad0 = child;
  27322. // else if (idx === 1) node.quad1 = child;
  27323. // else if (idx === 2) node.quad2 = child;
  27324. // else if (idx === 3) node.quad3 = child;
  27325. }
  27326. }
  27327. function getChildBodyCode(dimension) {
  27328. return `function getChild(node, idx) {
  27329. ${getChildBody()}
  27330. return null;
  27331. }`;
  27332. function getChildBody() {
  27333. let childBody = [];
  27334. let quadCount = Math.pow(2, dimension);
  27335. for (let i = 0; i < quadCount; ++i) {
  27336. childBody.push(` if (idx === ${i}) return node.quad${i};`);
  27337. }
  27338. return childBody.join('\n');
  27339. // if (idx === 0) return node.quad0;
  27340. // if (idx === 1) return node.quad1;
  27341. // if (idx === 2) return node.quad2;
  27342. // if (idx === 3) return node.quad3;
  27343. }
  27344. }
  27345. function getQuadNodeCode(dimension) {
  27346. let pattern = createPatternBuilder$4(dimension);
  27347. let quadCount = Math.pow(2, dimension);
  27348. var quadNodeCode = `
  27349. function QuadNode() {
  27350. // body stored inside this node. In quad tree only leaf nodes (by construction)
  27351. // contain bodies:
  27352. this.body = null;
  27353. // Child nodes are stored in quads. Each quad is presented by number:
  27354. // 0 | 1
  27355. // -----
  27356. // 2 | 3
  27357. ${assignQuads(' this.')}
  27358. // Total mass of current node
  27359. this.mass = 0;
  27360. // Center of mass coordinates
  27361. ${pattern('this.mass_{var} = 0;', {indent: 2})}
  27362. // bounding box coordinates
  27363. ${pattern('this.min_{var} = 0;', {indent: 2})}
  27364. ${pattern('this.max_{var} = 0;', {indent: 2})}
  27365. }
  27366. `;
  27367. return quadNodeCode;
  27368. function assignQuads(indent) {
  27369. // this.quad0 = null;
  27370. // this.quad1 = null;
  27371. // this.quad2 = null;
  27372. // this.quad3 = null;
  27373. let quads = [];
  27374. for (let i = 0; i < quadCount; ++i) {
  27375. quads.push(`${indent}quad${i} = null;`);
  27376. }
  27377. return quads.join('\n');
  27378. }
  27379. }
  27380. function getInsertStackCode() {
  27381. return `
  27382. /**
  27383. * Our implementation of QuadTree is non-recursive to avoid GC hit
  27384. * This data structure represent stack of elements
  27385. * which we are trying to insert into quad tree.
  27386. */
  27387. function InsertStack () {
  27388. this.stack = [];
  27389. this.popIdx = 0;
  27390. }
  27391. InsertStack.prototype = {
  27392. isEmpty: function() {
  27393. return this.popIdx === 0;
  27394. },
  27395. push: function (node, body) {
  27396. var item = this.stack[this.popIdx];
  27397. if (!item) {
  27398. // we are trying to avoid memory pressure: create new element
  27399. // only when absolutely necessary
  27400. this.stack[this.popIdx] = new InsertStackElement(node, body);
  27401. } else {
  27402. item.node = node;
  27403. item.body = body;
  27404. }
  27405. ++this.popIdx;
  27406. },
  27407. pop: function () {
  27408. if (this.popIdx > 0) {
  27409. return this.stack[--this.popIdx];
  27410. }
  27411. },
  27412. reset: function () {
  27413. this.popIdx = 0;
  27414. }
  27415. };
  27416. function InsertStackElement(node, body) {
  27417. this.node = node; // QuadTree node
  27418. this.body = body; // physical body which needs to be inserted to node
  27419. }
  27420. `;
  27421. }
  27422. var generateBounds = {exports: {}};
  27423. generateBounds.exports = generateBoundsFunction$1;
  27424. generateBounds.exports.generateFunctionBody = generateBoundsFunctionBody;
  27425. const createPatternBuilder$3 = createPatternBuilder$6;
  27426. function generateBoundsFunction$1(dimension) {
  27427. let code = generateBoundsFunctionBody(dimension);
  27428. return new Function('bodies', 'settings', 'random', code);
  27429. }
  27430. function generateBoundsFunctionBody(dimension) {
  27431. let pattern = createPatternBuilder$3(dimension);
  27432. let code = `
  27433. var boundingBox = {
  27434. ${pattern('min_{var}: 0, max_{var}: 0,', {indent: 4})}
  27435. };
  27436. return {
  27437. box: boundingBox,
  27438. update: updateBoundingBox,
  27439. reset: resetBoundingBox,
  27440. getBestNewPosition: function (neighbors) {
  27441. var ${pattern('base_{var} = 0', {join: ', '})};
  27442. if (neighbors.length) {
  27443. for (var i = 0; i < neighbors.length; ++i) {
  27444. let neighborPos = neighbors[i].pos;
  27445. ${pattern('base_{var} += neighborPos.{var};', {indent: 10})}
  27446. }
  27447. ${pattern('base_{var} /= neighbors.length;', {indent: 8})}
  27448. } else {
  27449. ${pattern('base_{var} = (boundingBox.min_{var} + boundingBox.max_{var}) / 2;', {indent: 8})}
  27450. }
  27451. var springLength = settings.springLength;
  27452. return {
  27453. ${pattern('{var}: base_{var} + (random.nextDouble() - 0.5) * springLength,', {indent: 8})}
  27454. };
  27455. }
  27456. };
  27457. function updateBoundingBox() {
  27458. var i = bodies.length;
  27459. if (i === 0) return; // No bodies - no borders.
  27460. ${pattern('var max_{var} = -Infinity;', {indent: 4})}
  27461. ${pattern('var min_{var} = Infinity;', {indent: 4})}
  27462. while(i--) {
  27463. // this is O(n), it could be done faster with quadtree, if we check the root node bounds
  27464. var bodyPos = bodies[i].pos;
  27465. ${pattern('if (bodyPos.{var} < min_{var}) min_{var} = bodyPos.{var};', {indent: 6})}
  27466. ${pattern('if (bodyPos.{var} > max_{var}) max_{var} = bodyPos.{var};', {indent: 6})}
  27467. }
  27468. ${pattern('boundingBox.min_{var} = min_{var};', {indent: 4})}
  27469. ${pattern('boundingBox.max_{var} = max_{var};', {indent: 4})}
  27470. }
  27471. function resetBoundingBox() {
  27472. ${pattern('boundingBox.min_{var} = boundingBox.max_{var} = 0;', {indent: 4})}
  27473. }
  27474. `;
  27475. return code;
  27476. }
  27477. var generateCreateDragForce = {exports: {}};
  27478. const createPatternBuilder$2 = createPatternBuilder$6;
  27479. generateCreateDragForce.exports = generateCreateDragForceFunction$1;
  27480. generateCreateDragForce.exports.generateCreateDragForceFunctionBody = generateCreateDragForceFunctionBody;
  27481. function generateCreateDragForceFunction$1(dimension) {
  27482. let code = generateCreateDragForceFunctionBody(dimension);
  27483. return new Function('options', code);
  27484. }
  27485. function generateCreateDragForceFunctionBody(dimension) {
  27486. let pattern = createPatternBuilder$2(dimension);
  27487. let code = `
  27488. if (!Number.isFinite(options.dragCoefficient)) throw new Error('dragCoefficient is not a finite number');
  27489. return {
  27490. update: function(body) {
  27491. ${pattern('body.force.{var} -= options.dragCoefficient * body.velocity.{var};', {indent: 6})}
  27492. }
  27493. };
  27494. `;
  27495. return code;
  27496. }
  27497. var generateCreateSpringForce = {exports: {}};
  27498. const createPatternBuilder$1 = createPatternBuilder$6;
  27499. generateCreateSpringForce.exports = generateCreateSpringForceFunction$1;
  27500. generateCreateSpringForce.exports.generateCreateSpringForceFunctionBody = generateCreateSpringForceFunctionBody;
  27501. function generateCreateSpringForceFunction$1(dimension) {
  27502. let code = generateCreateSpringForceFunctionBody(dimension);
  27503. return new Function('options', 'random', code);
  27504. }
  27505. function generateCreateSpringForceFunctionBody(dimension) {
  27506. let pattern = createPatternBuilder$1(dimension);
  27507. let code = `
  27508. if (!Number.isFinite(options.springCoefficient)) throw new Error('Spring coefficient is not a number');
  27509. if (!Number.isFinite(options.springLength)) throw new Error('Spring length is not a number');
  27510. return {
  27511. /**
  27512. * Updates forces acting on a spring
  27513. */
  27514. update: function (spring) {
  27515. var body1 = spring.from;
  27516. var body2 = spring.to;
  27517. var length = spring.length < 0 ? options.springLength : spring.length;
  27518. ${pattern('var d{var} = body2.pos.{var} - body1.pos.{var};', {indent: 6})}
  27519. var r = Math.sqrt(${pattern('d{var} * d{var}', {join: ' + '})});
  27520. if (r === 0) {
  27521. ${pattern('d{var} = (random.nextDouble() - 0.5) / 50;', {indent: 8})}
  27522. r = Math.sqrt(${pattern('d{var} * d{var}', {join: ' + '})});
  27523. }
  27524. var d = r - length;
  27525. var coefficient = ((spring.coefficient > 0) ? spring.coefficient : options.springCoefficient) * d / r;
  27526. ${pattern('body1.force.{var} += coefficient * d{var}', {indent: 6})};
  27527. body1.springCount += 1;
  27528. body1.springLength += r;
  27529. ${pattern('body2.force.{var} -= coefficient * d{var}', {indent: 6})};
  27530. body2.springCount += 1;
  27531. body2.springLength += r;
  27532. }
  27533. };
  27534. `;
  27535. return code;
  27536. }
  27537. var generateIntegrator = {exports: {}};
  27538. const createPatternBuilder = createPatternBuilder$6;
  27539. generateIntegrator.exports = generateIntegratorFunction$1;
  27540. generateIntegrator.exports.generateIntegratorFunctionBody = generateIntegratorFunctionBody;
  27541. function generateIntegratorFunction$1(dimension) {
  27542. let code = generateIntegratorFunctionBody(dimension);
  27543. return new Function('bodies', 'timeStep', 'adaptiveTimeStepWeight', code);
  27544. }
  27545. function generateIntegratorFunctionBody(dimension) {
  27546. let pattern = createPatternBuilder(dimension);
  27547. let code = `
  27548. var length = bodies.length;
  27549. if (length === 0) return 0;
  27550. ${pattern('var d{var} = 0, t{var} = 0;', {indent: 2})}
  27551. for (var i = 0; i < length; ++i) {
  27552. var body = bodies[i];
  27553. if (body.isPinned) continue;
  27554. if (adaptiveTimeStepWeight && body.springCount) {
  27555. timeStep = (adaptiveTimeStepWeight * body.springLength/body.springCount);
  27556. }
  27557. var coeff = timeStep / body.mass;
  27558. ${pattern('body.velocity.{var} += coeff * body.force.{var};', {indent: 4})}
  27559. ${pattern('var v{var} = body.velocity.{var};', {indent: 4})}
  27560. var v = Math.sqrt(${pattern('v{var} * v{var}', {join: ' + '})});
  27561. if (v > 1) {
  27562. // We normalize it so that we move within timeStep range.
  27563. // for the case when v <= 1 - we let velocity to fade out.
  27564. ${pattern('body.velocity.{var} = v{var} / v;', {indent: 6})}
  27565. }
  27566. ${pattern('d{var} = timeStep * body.velocity.{var};', {indent: 4})}
  27567. ${pattern('body.pos.{var} += d{var};', {indent: 4})}
  27568. ${pattern('t{var} += Math.abs(d{var});', {indent: 4})}
  27569. }
  27570. return (${pattern('t{var} * t{var}', {join: ' + '})})/length;
  27571. `;
  27572. return code;
  27573. }
  27574. var spring = Spring;
  27575. /**
  27576. * Represents a physical spring. Spring connects two bodies, has rest length
  27577. * stiffness coefficient and optional weight
  27578. */
  27579. function Spring(fromBody, toBody, length, springCoefficient) {
  27580. this.from = fromBody;
  27581. this.to = toBody;
  27582. this.length = length;
  27583. this.coefficient = springCoefficient;
  27584. }
  27585. var ngraph_merge = merge;
  27586. /**
  27587. * Augments `target` with properties in `options`. Does not override
  27588. * target's properties if they are defined and matches expected type in
  27589. * options
  27590. *
  27591. * @returns {Object} merged object
  27592. */
  27593. function merge(target, options) {
  27594. var key;
  27595. if (!target) { target = {}; }
  27596. if (options) {
  27597. for (key in options) {
  27598. if (options.hasOwnProperty(key)) {
  27599. var targetHasIt = target.hasOwnProperty(key),
  27600. optionsValueType = typeof options[key],
  27601. shouldReplace = !targetHasIt || (typeof target[key] !== optionsValueType);
  27602. if (shouldReplace) {
  27603. target[key] = options[key];
  27604. } else if (optionsValueType === 'object') {
  27605. // go deep, don't care about loops here, we are simple API!:
  27606. target[key] = merge(target[key], options[key]);
  27607. }
  27608. }
  27609. }
  27610. }
  27611. return target;
  27612. }
  27613. var ngraph_random = {exports: {}};
  27614. ngraph_random.exports = random;
  27615. // TODO: Deprecate?
  27616. ngraph_random.exports.random = random,
  27617. ngraph_random.exports.randomIterator = randomIterator;
  27618. /**
  27619. * Creates seeded PRNG with two methods:
  27620. * next() and nextDouble()
  27621. */
  27622. function random(inputSeed) {
  27623. var seed = typeof inputSeed === 'number' ? inputSeed : (+new Date());
  27624. return new Generator(seed)
  27625. }
  27626. function Generator(seed) {
  27627. this.seed = seed;
  27628. }
  27629. /**
  27630. * Generates random integer number in the range from 0 (inclusive) to maxValue (exclusive)
  27631. *
  27632. * @param maxValue Number REQUIRED. Omitting this number will result in NaN values from PRNG.
  27633. */
  27634. Generator.prototype.next = next;
  27635. /**
  27636. * Generates random double number in the range from 0 (inclusive) to 1 (exclusive)
  27637. * This function is the same as Math.random() (except that it could be seeded)
  27638. */
  27639. Generator.prototype.nextDouble = nextDouble;
  27640. /**
  27641. * Returns a random real number from uniform distribution in [0, 1)
  27642. */
  27643. Generator.prototype.uniform = nextDouble;
  27644. /**
  27645. * Returns a random real number from a Gaussian distribution
  27646. * with 0 as a mean, and 1 as standard deviation u ~ N(0,1)
  27647. */
  27648. Generator.prototype.gaussian = gaussian;
  27649. function gaussian() {
  27650. // use the polar form of the Box-Muller transform
  27651. // based on https://introcs.cs.princeton.edu/java/23recursion/StdRandom.java
  27652. var r, x, y;
  27653. do {
  27654. x = this.nextDouble() * 2 - 1;
  27655. y = this.nextDouble() * 2 - 1;
  27656. r = x * x + y * y;
  27657. } while (r >= 1 || r === 0);
  27658. return x * Math.sqrt(-2 * Math.log(r)/r);
  27659. }
  27660. /**
  27661. * See https://twitter.com/anvaka/status/1296182534150135808
  27662. */
  27663. Generator.prototype.levy = levy;
  27664. function levy() {
  27665. var beta = 3 / 2;
  27666. var sigma = Math.pow(
  27667. gamma( 1 + beta ) * Math.sin(Math.PI * beta / 2) /
  27668. (gamma((1 + beta) / 2) * beta * Math.pow(2, (beta - 1) / 2)),
  27669. 1/beta
  27670. );
  27671. return this.gaussian() * sigma / Math.pow(Math.abs(this.gaussian()), 1/beta);
  27672. }
  27673. // gamma function approximation
  27674. function gamma(z) {
  27675. return Math.sqrt(2 * Math.PI / z) * Math.pow((1 / Math.E) * (z + 1 / (12 * z - 1 / (10 * z))), z);
  27676. }
  27677. function nextDouble() {
  27678. var seed = this.seed;
  27679. // Robert Jenkins' 32 bit integer hash function.
  27680. seed = ((seed + 0x7ed55d16) + (seed << 12)) & 0xffffffff;
  27681. seed = ((seed ^ 0xc761c23c) ^ (seed >>> 19)) & 0xffffffff;
  27682. seed = ((seed + 0x165667b1) + (seed << 5)) & 0xffffffff;
  27683. seed = ((seed + 0xd3a2646c) ^ (seed << 9)) & 0xffffffff;
  27684. seed = ((seed + 0xfd7046c5) + (seed << 3)) & 0xffffffff;
  27685. seed = ((seed ^ 0xb55a4f09) ^ (seed >>> 16)) & 0xffffffff;
  27686. this.seed = seed;
  27687. return (seed & 0xfffffff) / 0x10000000;
  27688. }
  27689. function next(maxValue) {
  27690. return Math.floor(this.nextDouble() * maxValue);
  27691. }
  27692. /*
  27693. * Creates iterator over array, which returns items of array in random order
  27694. * Time complexity is guaranteed to be O(n);
  27695. */
  27696. function randomIterator(array, customRandom) {
  27697. var localRandom = customRandom || random();
  27698. if (typeof localRandom.next !== 'function') {
  27699. throw new Error('customRandom does not match expected API: next() function is missing');
  27700. }
  27701. return {
  27702. forEach: forEach,
  27703. /**
  27704. * Shuffles array randomly, in place.
  27705. */
  27706. shuffle: shuffle
  27707. };
  27708. function shuffle() {
  27709. var i, j, t;
  27710. for (i = array.length - 1; i > 0; --i) {
  27711. j = localRandom.next(i + 1); // i inclusive
  27712. t = array[j];
  27713. array[j] = array[i];
  27714. array[i] = t;
  27715. }
  27716. return array;
  27717. }
  27718. function forEach(callback) {
  27719. var i, j, t;
  27720. for (i = array.length - 1; i > 0; --i) {
  27721. j = localRandom.next(i + 1); // i inclusive
  27722. t = array[j];
  27723. array[j] = array[i];
  27724. array[i] = t;
  27725. callback(t);
  27726. }
  27727. if (array.length) {
  27728. callback(array[0]);
  27729. }
  27730. }
  27731. }
  27732. /**
  27733. * Manages a simulation of physical forces acting on bodies and springs.
  27734. */
  27735. var createPhysicsSimulator_1 = createPhysicsSimulator;
  27736. var generateCreateBodyFunction = generateCreateBody.exports;
  27737. var generateQuadTreeFunction = generateQuadTree.exports;
  27738. var generateBoundsFunction = generateBounds.exports;
  27739. var generateCreateDragForceFunction = generateCreateDragForce.exports;
  27740. var generateCreateSpringForceFunction = generateCreateSpringForce.exports;
  27741. var generateIntegratorFunction = generateIntegrator.exports;
  27742. var dimensionalCache = {};
  27743. function createPhysicsSimulator(settings) {
  27744. var Spring = spring;
  27745. var merge = ngraph_merge;
  27746. var eventify = ngraph_events;
  27747. if (settings) {
  27748. // Check for names from older versions of the layout
  27749. if (settings.springCoeff !== undefined) throw new Error('springCoeff was renamed to springCoefficient');
  27750. if (settings.dragCoeff !== undefined) throw new Error('dragCoeff was renamed to dragCoefficient');
  27751. }
  27752. settings = merge(settings, {
  27753. /**
  27754. * Ideal length for links (springs in physical model).
  27755. */
  27756. springLength: 10,
  27757. /**
  27758. * Hook's law coefficient. 1 - solid spring.
  27759. */
  27760. springCoefficient: 0.8,
  27761. /**
  27762. * Coulomb's law coefficient. It's used to repel nodes thus should be negative
  27763. * if you make it positive nodes start attract each other :).
  27764. */
  27765. gravity: -12,
  27766. /**
  27767. * Theta coefficient from Barnes Hut simulation. Ranged between (0, 1).
  27768. * The closer it's to 1 the more nodes algorithm will have to go through.
  27769. * Setting it to one makes Barnes Hut simulation no different from
  27770. * brute-force forces calculation (each node is considered).
  27771. */
  27772. theta: 0.8,
  27773. /**
  27774. * Drag force coefficient. Used to slow down system, thus should be less than 1.
  27775. * The closer it is to 0 the less tight system will be.
  27776. */
  27777. dragCoefficient: 0.9, // TODO: Need to rename this to something better. E.g. `dragCoefficient`
  27778. /**
  27779. * Default time step (dt) for forces integration
  27780. */
  27781. timeStep : 0.5,
  27782. /**
  27783. * Adaptive time step uses average spring length to compute actual time step:
  27784. * See: https://twitter.com/anvaka/status/1293067160755957760
  27785. */
  27786. adaptiveTimeStepWeight: 0,
  27787. /**
  27788. * This parameter defines number of dimensions of the space where simulation
  27789. * is performed.
  27790. */
  27791. dimensions: 2,
  27792. /**
  27793. * In debug mode more checks are performed, this will help you catch errors
  27794. * quickly, however for production build it is recommended to turn off this flag
  27795. * to speed up computation.
  27796. */
  27797. debug: false
  27798. });
  27799. var factory = dimensionalCache[settings.dimensions];
  27800. if (!factory) {
  27801. var dimensions = settings.dimensions;
  27802. factory = {
  27803. Body: generateCreateBodyFunction(dimensions, settings.debug),
  27804. createQuadTree: generateQuadTreeFunction(dimensions),
  27805. createBounds: generateBoundsFunction(dimensions),
  27806. createDragForce: generateCreateDragForceFunction(dimensions),
  27807. createSpringForce: generateCreateSpringForceFunction(dimensions),
  27808. integrate: generateIntegratorFunction(dimensions),
  27809. };
  27810. dimensionalCache[dimensions] = factory;
  27811. }
  27812. var Body = factory.Body;
  27813. var createQuadTree = factory.createQuadTree;
  27814. var createBounds = factory.createBounds;
  27815. var createDragForce = factory.createDragForce;
  27816. var createSpringForce = factory.createSpringForce;
  27817. var integrate = factory.integrate;
  27818. var createBody = pos => new Body(pos);
  27819. var random = ngraph_random.exports.random(42);
  27820. var bodies = []; // Bodies in this simulation.
  27821. var springs = []; // Springs in this simulation.
  27822. var quadTree = createQuadTree(settings, random);
  27823. var bounds = createBounds(bodies, settings, random);
  27824. var springForce = createSpringForce(settings, random);
  27825. var dragForce = createDragForce(settings);
  27826. var totalMovement = 0; // how much movement we made on last step
  27827. var forces = [];
  27828. var forceMap = new Map();
  27829. var iterationNumber = 0;
  27830. addForce('nbody', nbodyForce);
  27831. addForce('spring', updateSpringForce);
  27832. var publicApi = {
  27833. /**
  27834. * Array of bodies, registered with current simulator
  27835. *
  27836. * Note: To add new body, use addBody() method. This property is only
  27837. * exposed for testing/performance purposes.
  27838. */
  27839. bodies: bodies,
  27840. quadTree: quadTree,
  27841. /**
  27842. * Array of springs, registered with current simulator
  27843. *
  27844. * Note: To add new spring, use addSpring() method. This property is only
  27845. * exposed for testing/performance purposes.
  27846. */
  27847. springs: springs,
  27848. /**
  27849. * Returns settings with which current simulator was initialized
  27850. */
  27851. settings: settings,
  27852. /**
  27853. * Adds a new force to simulation
  27854. */
  27855. addForce: addForce,
  27856. /**
  27857. * Removes a force from the simulation.
  27858. */
  27859. removeForce: removeForce,
  27860. /**
  27861. * Returns a map of all registered forces.
  27862. */
  27863. getForces: getForces,
  27864. /**
  27865. * Performs one step of force simulation.
  27866. *
  27867. * @returns {boolean} true if system is considered stable; False otherwise.
  27868. */
  27869. step: function () {
  27870. for (var i = 0; i < forces.length; ++i) {
  27871. forces[i](iterationNumber);
  27872. }
  27873. var movement = integrate(bodies, settings.timeStep, settings.adaptiveTimeStepWeight);
  27874. iterationNumber += 1;
  27875. return movement;
  27876. },
  27877. /**
  27878. * Adds body to the system
  27879. *
  27880. * @param {ngraph.physics.primitives.Body} body physical body
  27881. *
  27882. * @returns {ngraph.physics.primitives.Body} added body
  27883. */
  27884. addBody: function (body) {
  27885. if (!body) {
  27886. throw new Error('Body is required');
  27887. }
  27888. bodies.push(body);
  27889. return body;
  27890. },
  27891. /**
  27892. * Adds body to the system at given position
  27893. *
  27894. * @param {Object} pos position of a body
  27895. *
  27896. * @returns {ngraph.physics.primitives.Body} added body
  27897. */
  27898. addBodyAt: function (pos) {
  27899. if (!pos) {
  27900. throw new Error('Body position is required');
  27901. }
  27902. var body = createBody(pos);
  27903. bodies.push(body);
  27904. return body;
  27905. },
  27906. /**
  27907. * Removes body from the system
  27908. *
  27909. * @param {ngraph.physics.primitives.Body} body to remove
  27910. *
  27911. * @returns {Boolean} true if body found and removed. falsy otherwise;
  27912. */
  27913. removeBody: function (body) {
  27914. if (!body) { return; }
  27915. var idx = bodies.indexOf(body);
  27916. if (idx < 0) { return; }
  27917. bodies.splice(idx, 1);
  27918. if (bodies.length === 0) {
  27919. bounds.reset();
  27920. }
  27921. return true;
  27922. },
  27923. /**
  27924. * Adds a spring to this simulation.
  27925. *
  27926. * @returns {Object} - a handle for a spring. If you want to later remove
  27927. * spring pass it to removeSpring() method.
  27928. */
  27929. addSpring: function (body1, body2, springLength, springCoefficient) {
  27930. if (!body1 || !body2) {
  27931. throw new Error('Cannot add null spring to force simulator');
  27932. }
  27933. if (typeof springLength !== 'number') {
  27934. springLength = -1; // assume global configuration
  27935. }
  27936. var spring = new Spring(body1, body2, springLength, springCoefficient >= 0 ? springCoefficient : -1);
  27937. springs.push(spring);
  27938. // TODO: could mark simulator as dirty.
  27939. return spring;
  27940. },
  27941. /**
  27942. * Returns amount of movement performed on last step() call
  27943. */
  27944. getTotalMovement: function () {
  27945. return totalMovement;
  27946. },
  27947. /**
  27948. * Removes spring from the system
  27949. *
  27950. * @param {Object} spring to remove. Spring is an object returned by addSpring
  27951. *
  27952. * @returns {Boolean} true if spring found and removed. falsy otherwise;
  27953. */
  27954. removeSpring: function (spring) {
  27955. if (!spring) { return; }
  27956. var idx = springs.indexOf(spring);
  27957. if (idx > -1) {
  27958. springs.splice(idx, 1);
  27959. return true;
  27960. }
  27961. },
  27962. getBestNewBodyPosition: function (neighbors) {
  27963. return bounds.getBestNewPosition(neighbors);
  27964. },
  27965. /**
  27966. * Returns bounding box which covers all bodies
  27967. */
  27968. getBBox: getBoundingBox,
  27969. getBoundingBox: getBoundingBox,
  27970. invalidateBBox: function () {
  27971. console.warn('invalidateBBox() is deprecated, bounds always recomputed on `getBBox()` call');
  27972. },
  27973. // TODO: Move the force specific stuff to force
  27974. gravity: function (value) {
  27975. if (value !== undefined) {
  27976. settings.gravity = value;
  27977. quadTree.options({gravity: value});
  27978. return this;
  27979. } else {
  27980. return settings.gravity;
  27981. }
  27982. },
  27983. theta: function (value) {
  27984. if (value !== undefined) {
  27985. settings.theta = value;
  27986. quadTree.options({theta: value});
  27987. return this;
  27988. } else {
  27989. return settings.theta;
  27990. }
  27991. },
  27992. /**
  27993. * Returns pseudo-random number generator instance.
  27994. */
  27995. random: random
  27996. };
  27997. // allow settings modification via public API:
  27998. expose(settings, publicApi);
  27999. eventify(publicApi);
  28000. return publicApi;
  28001. function getBoundingBox() {
  28002. bounds.update();
  28003. return bounds.box;
  28004. }
  28005. function addForce(forceName, forceFunction) {
  28006. if (forceMap.has(forceName)) throw new Error('Force ' + forceName + ' is already added');
  28007. forceMap.set(forceName, forceFunction);
  28008. forces.push(forceFunction);
  28009. }
  28010. function removeForce(forceName) {
  28011. var forceIndex = forces.indexOf(forceMap.get(forceName));
  28012. if (forceIndex < 0) return;
  28013. forces.splice(forceIndex, 1);
  28014. forceMap.delete(forceName);
  28015. }
  28016. function getForces() {
  28017. // TODO: Should I trust them or clone the forces?
  28018. return forceMap;
  28019. }
  28020. function nbodyForce(/* iterationUmber */) {
  28021. if (bodies.length === 0) return;
  28022. quadTree.insertBodies(bodies);
  28023. var i = bodies.length;
  28024. while (i--) {
  28025. var body = bodies[i];
  28026. if (!body.isPinned) {
  28027. body.reset();
  28028. quadTree.updateBodyForce(body);
  28029. dragForce.update(body);
  28030. }
  28031. }
  28032. }
  28033. function updateSpringForce() {
  28034. var i = springs.length;
  28035. while (i--) {
  28036. springForce.update(springs[i]);
  28037. }
  28038. }
  28039. }
  28040. function expose(settings, target) {
  28041. for (var key in settings) {
  28042. augment(settings, target, key);
  28043. }
  28044. }
  28045. function augment(source, target, key) {
  28046. if (!source.hasOwnProperty(key)) return;
  28047. if (typeof target[key] === 'function') {
  28048. // this accessor is already defined. Ignore it
  28049. return;
  28050. }
  28051. var sourceIsNumber = Number.isFinite(source[key]);
  28052. if (sourceIsNumber) {
  28053. target[key] = function (value) {
  28054. if (value !== undefined) {
  28055. if (!Number.isFinite(value)) throw new Error('Value of ' + key + ' should be a valid number.');
  28056. source[key] = value;
  28057. return target;
  28058. }
  28059. return source[key];
  28060. };
  28061. } else {
  28062. target[key] = function (value) {
  28063. if (value !== undefined) {
  28064. source[key] = value;
  28065. return target;
  28066. }
  28067. return source[key];
  28068. };
  28069. }
  28070. }
  28071. ngraph_forcelayout.exports = createLayout;
  28072. ngraph_forcelayout.exports.simulator = createPhysicsSimulator_1;
  28073. var eventify = ngraph_events;
  28074. /**
  28075. * Creates force based layout for a given graph.
  28076. *
  28077. * @param {ngraph.graph} graph which needs to be laid out
  28078. * @param {object} physicsSettings if you need custom settings
  28079. * for physics simulator you can pass your own settings here. If it's not passed
  28080. * a default one will be created.
  28081. */
  28082. function createLayout(graph, physicsSettings) {
  28083. if (!graph) {
  28084. throw new Error('Graph structure cannot be undefined');
  28085. }
  28086. var createSimulator = (physicsSettings && physicsSettings.createSimulator) || createPhysicsSimulator_1;
  28087. var physicsSimulator = createSimulator(physicsSettings);
  28088. if (Array.isArray(physicsSettings)) throw new Error('Physics settings is expected to be an object');
  28089. var nodeMass = defaultNodeMass;
  28090. if (physicsSettings && typeof physicsSettings.nodeMass === 'function') {
  28091. nodeMass = physicsSettings.nodeMass;
  28092. }
  28093. var nodeBodies = new Map();
  28094. var springs = {};
  28095. var bodiesCount = 0;
  28096. var springTransform = physicsSimulator.settings.springTransform || noop;
  28097. // Initialize physics with what we have in the graph:
  28098. initPhysics();
  28099. listenToEvents();
  28100. var wasStable = false;
  28101. var api = {
  28102. /**
  28103. * Performs one step of iterative layout algorithm
  28104. *
  28105. * @returns {boolean} true if the system should be considered stable; False otherwise.
  28106. * The system is stable if no further call to `step()` can improve the layout.
  28107. */
  28108. step: function() {
  28109. if (bodiesCount === 0) {
  28110. updateStableStatus(true);
  28111. return true;
  28112. }
  28113. var lastMove = physicsSimulator.step();
  28114. // Save the movement in case if someone wants to query it in the step
  28115. // callback.
  28116. api.lastMove = lastMove;
  28117. // Allow listeners to perform low-level actions after nodes are updated.
  28118. api.fire('step');
  28119. var ratio = lastMove/bodiesCount;
  28120. var isStableNow = ratio <= 0.01; // TODO: The number is somewhat arbitrary...
  28121. updateStableStatus(isStableNow);
  28122. return isStableNow;
  28123. },
  28124. /**
  28125. * For a given `nodeId` returns position
  28126. */
  28127. getNodePosition: function (nodeId) {
  28128. return getInitializedBody(nodeId).pos;
  28129. },
  28130. /**
  28131. * Sets position of a node to a given coordinates
  28132. * @param {string} nodeId node identifier
  28133. * @param {number} x position of a node
  28134. * @param {number} y position of a node
  28135. * @param {number=} z position of node (only if applicable to body)
  28136. */
  28137. setNodePosition: function (nodeId) {
  28138. var body = getInitializedBody(nodeId);
  28139. body.setPosition.apply(body, Array.prototype.slice.call(arguments, 1));
  28140. },
  28141. /**
  28142. * @returns {Object} Link position by link id
  28143. * @returns {Object.from} {x, y} coordinates of link start
  28144. * @returns {Object.to} {x, y} coordinates of link end
  28145. */
  28146. getLinkPosition: function (linkId) {
  28147. var spring = springs[linkId];
  28148. if (spring) {
  28149. return {
  28150. from: spring.from.pos,
  28151. to: spring.to.pos
  28152. };
  28153. }
  28154. },
  28155. /**
  28156. * @returns {Object} area required to fit in the graph. Object contains
  28157. * `x1`, `y1` - top left coordinates
  28158. * `x2`, `y2` - bottom right coordinates
  28159. */
  28160. getGraphRect: function () {
  28161. return physicsSimulator.getBBox();
  28162. },
  28163. /**
  28164. * Iterates over each body in the layout simulator and performs a callback(body, nodeId)
  28165. */
  28166. forEachBody: forEachBody,
  28167. /*
  28168. * Requests layout algorithm to pin/unpin node to its current position
  28169. * Pinned nodes should not be affected by layout algorithm and always
  28170. * remain at their position
  28171. */
  28172. pinNode: function (node, isPinned) {
  28173. var body = getInitializedBody(node.id);
  28174. body.isPinned = !!isPinned;
  28175. },
  28176. /**
  28177. * Checks whether given graph's node is currently pinned
  28178. */
  28179. isNodePinned: function (node) {
  28180. return getInitializedBody(node.id).isPinned;
  28181. },
  28182. /**
  28183. * Request to release all resources
  28184. */
  28185. dispose: function() {
  28186. graph.off('changed', onGraphChanged);
  28187. api.fire('disposed');
  28188. },
  28189. /**
  28190. * Gets physical body for a given node id. If node is not found undefined
  28191. * value is returned.
  28192. */
  28193. getBody: getBody,
  28194. /**
  28195. * Gets spring for a given edge.
  28196. *
  28197. * @param {string} linkId link identifer. If two arguments are passed then
  28198. * this argument is treated as formNodeId
  28199. * @param {string=} toId when defined this parameter denotes head of the link
  28200. * and first argument is treated as tail of the link (fromId)
  28201. */
  28202. getSpring: getSpring,
  28203. /**
  28204. * Returns length of cumulative force vector. The closer this to zero - the more stable the system is
  28205. */
  28206. getForceVectorLength: getForceVectorLength,
  28207. /**
  28208. * [Read only] Gets current physics simulator
  28209. */
  28210. simulator: physicsSimulator,
  28211. /**
  28212. * Gets the graph that was used for layout
  28213. */
  28214. graph: graph,
  28215. /**
  28216. * Gets amount of movement performed during last step operation
  28217. */
  28218. lastMove: 0
  28219. };
  28220. eventify(api);
  28221. return api;
  28222. function updateStableStatus(isStableNow) {
  28223. if (wasStable !== isStableNow) {
  28224. wasStable = isStableNow;
  28225. onStableChanged(isStableNow);
  28226. }
  28227. }
  28228. function forEachBody(cb) {
  28229. nodeBodies.forEach(cb);
  28230. }
  28231. function getForceVectorLength() {
  28232. var fx = 0, fy = 0;
  28233. forEachBody(function(body) {
  28234. fx += Math.abs(body.force.x);
  28235. fy += Math.abs(body.force.y);
  28236. });
  28237. return Math.sqrt(fx * fx + fy * fy);
  28238. }
  28239. function getSpring(fromId, toId) {
  28240. var linkId;
  28241. if (toId === undefined) {
  28242. if (typeof fromId !== 'object') {
  28243. // assume fromId as a linkId:
  28244. linkId = fromId;
  28245. } else {
  28246. // assume fromId to be a link object:
  28247. linkId = fromId.id;
  28248. }
  28249. } else {
  28250. // toId is defined, should grab link:
  28251. var link = graph.hasLink(fromId, toId);
  28252. if (!link) return;
  28253. linkId = link.id;
  28254. }
  28255. return springs[linkId];
  28256. }
  28257. function getBody(nodeId) {
  28258. return nodeBodies.get(nodeId);
  28259. }
  28260. function listenToEvents() {
  28261. graph.on('changed', onGraphChanged);
  28262. }
  28263. function onStableChanged(isStable) {
  28264. api.fire('stable', isStable);
  28265. }
  28266. function onGraphChanged(changes) {
  28267. for (var i = 0; i < changes.length; ++i) {
  28268. var change = changes[i];
  28269. if (change.changeType === 'add') {
  28270. if (change.node) {
  28271. initBody(change.node.id);
  28272. }
  28273. if (change.link) {
  28274. initLink(change.link);
  28275. }
  28276. } else if (change.changeType === 'remove') {
  28277. if (change.node) {
  28278. releaseNode(change.node);
  28279. }
  28280. if (change.link) {
  28281. releaseLink(change.link);
  28282. }
  28283. }
  28284. }
  28285. bodiesCount = graph.getNodesCount();
  28286. }
  28287. function initPhysics() {
  28288. bodiesCount = 0;
  28289. graph.forEachNode(function (node) {
  28290. initBody(node.id);
  28291. bodiesCount += 1;
  28292. });
  28293. graph.forEachLink(initLink);
  28294. }
  28295. function initBody(nodeId) {
  28296. var body = nodeBodies.get(nodeId);
  28297. if (!body) {
  28298. var node = graph.getNode(nodeId);
  28299. if (!node) {
  28300. throw new Error('initBody() was called with unknown node id');
  28301. }
  28302. var pos = node.position;
  28303. if (!pos) {
  28304. var neighbors = getNeighborBodies(node);
  28305. pos = physicsSimulator.getBestNewBodyPosition(neighbors);
  28306. }
  28307. body = physicsSimulator.addBodyAt(pos);
  28308. body.id = nodeId;
  28309. nodeBodies.set(nodeId, body);
  28310. updateBodyMass(nodeId);
  28311. if (isNodeOriginallyPinned(node)) {
  28312. body.isPinned = true;
  28313. }
  28314. }
  28315. }
  28316. function releaseNode(node) {
  28317. var nodeId = node.id;
  28318. var body = nodeBodies.get(nodeId);
  28319. if (body) {
  28320. nodeBodies.delete(nodeId);
  28321. physicsSimulator.removeBody(body);
  28322. }
  28323. }
  28324. function initLink(link) {
  28325. updateBodyMass(link.fromId);
  28326. updateBodyMass(link.toId);
  28327. var fromBody = nodeBodies.get(link.fromId),
  28328. toBody = nodeBodies.get(link.toId),
  28329. spring = physicsSimulator.addSpring(fromBody, toBody, link.length);
  28330. springTransform(link, spring);
  28331. springs[link.id] = spring;
  28332. }
  28333. function releaseLink(link) {
  28334. var spring = springs[link.id];
  28335. if (spring) {
  28336. var from = graph.getNode(link.fromId),
  28337. to = graph.getNode(link.toId);
  28338. if (from) updateBodyMass(from.id);
  28339. if (to) updateBodyMass(to.id);
  28340. delete springs[link.id];
  28341. physicsSimulator.removeSpring(spring);
  28342. }
  28343. }
  28344. function getNeighborBodies(node) {
  28345. // TODO: Could probably be done better on memory
  28346. var neighbors = [];
  28347. if (!node.links) {
  28348. return neighbors;
  28349. }
  28350. var maxNeighbors = Math.min(node.links.length, 2);
  28351. for (var i = 0; i < maxNeighbors; ++i) {
  28352. var link = node.links[i];
  28353. var otherBody = link.fromId !== node.id ? nodeBodies.get(link.fromId) : nodeBodies.get(link.toId);
  28354. if (otherBody && otherBody.pos) {
  28355. neighbors.push(otherBody);
  28356. }
  28357. }
  28358. return neighbors;
  28359. }
  28360. function updateBodyMass(nodeId) {
  28361. var body = nodeBodies.get(nodeId);
  28362. body.mass = nodeMass(nodeId);
  28363. if (Number.isNaN(body.mass)) {
  28364. throw new Error('Node mass should be a number');
  28365. }
  28366. }
  28367. /**
  28368. * Checks whether graph node has in its settings pinned attribute,
  28369. * which means layout algorithm cannot move it. Node can be marked
  28370. * as pinned, if it has "isPinned" attribute, or when node.data has it.
  28371. *
  28372. * @param {Object} node a graph node to check
  28373. * @return {Boolean} true if node should be treated as pinned; false otherwise.
  28374. */
  28375. function isNodeOriginallyPinned(node) {
  28376. return (node && (node.isPinned || (node.data && node.data.isPinned)));
  28377. }
  28378. function getInitializedBody(nodeId) {
  28379. var body = nodeBodies.get(nodeId);
  28380. if (!body) {
  28381. initBody(nodeId);
  28382. body = nodeBodies.get(nodeId);
  28383. }
  28384. return body;
  28385. }
  28386. /**
  28387. * Calculates mass of a body, which corresponds to node with given id.
  28388. *
  28389. * @param {String|Number} nodeId identifier of a node, for which body mass needs to be calculated
  28390. * @returns {Number} recommended mass of the body;
  28391. */
  28392. function defaultNodeMass(nodeId) {
  28393. var links = graph.getLinks(nodeId);
  28394. if (!links) return 1;
  28395. return 1 + links.length / 3.0;
  28396. }
  28397. }
  28398. function noop() { }
  28399. var forcelayout = ngraph_forcelayout.exports;
  28400. /**
  28401. * Returns a function, that, as long as it continues to be invoked, will not
  28402. * be triggered. The function will be called after it stops being called for
  28403. * N milliseconds. If `immediate` is passed, trigger the function on the
  28404. * leading edge, instead of the trailing. The function also has a property 'clear'
  28405. * that is a function which will clear the timer to prevent previously scheduled executions.
  28406. *
  28407. * @source underscore.js
  28408. * @see http://unscriptable.com/2009/03/20/debouncing-javascript-methods/
  28409. * @param {Function} function to wrap
  28410. * @param {Number} timeout in ms (`100`)
  28411. * @param {Boolean} whether to execute at the beginning (`false`)
  28412. * @api public
  28413. */
  28414. function debounce(func, wait, immediate){
  28415. var timeout, args, context, timestamp, result;
  28416. if (null == wait) wait = 100;
  28417. function later() {
  28418. var last = Date.now() - timestamp;
  28419. if (last < wait && last >= 0) {
  28420. timeout = setTimeout(later, wait - last);
  28421. } else {
  28422. timeout = null;
  28423. if (!immediate) {
  28424. result = func.apply(context, args);
  28425. context = args = null;
  28426. }
  28427. }
  28428. }
  28429. var debounced = function(){
  28430. context = this;
  28431. args = arguments;
  28432. timestamp = Date.now();
  28433. var callNow = immediate && !timeout;
  28434. if (!timeout) timeout = setTimeout(later, wait);
  28435. if (callNow) {
  28436. result = func.apply(context, args);
  28437. context = args = null;
  28438. }
  28439. return result;
  28440. };
  28441. debounced.clear = function() {
  28442. if (timeout) {
  28443. clearTimeout(timeout);
  28444. timeout = null;
  28445. }
  28446. };
  28447. debounced.flush = function() {
  28448. if (timeout) {
  28449. result = func.apply(context, args);
  28450. context = args = null;
  28451. clearTimeout(timeout);
  28452. timeout = null;
  28453. }
  28454. };
  28455. return debounced;
  28456. }
  28457. // Adds compatibility for ES modules
  28458. debounce.debounce = debounce;
  28459. var debounce_1 = debounce;
  28460. function _classCallCheck$1(instance, Constructor) {
  28461. if (!(instance instanceof Constructor)) {
  28462. throw new TypeError("Cannot call a class as a function");
  28463. }
  28464. }
  28465. function _slicedToArray$4(arr, i) {
  28466. return _arrayWithHoles$4(arr) || _iterableToArrayLimit$4(arr, i) || _unsupportedIterableToArray$4(arr, i) || _nonIterableRest$4();
  28467. }
  28468. function _arrayWithHoles$4(arr) {
  28469. if (Array.isArray(arr)) return arr;
  28470. }
  28471. function _iterableToArrayLimit$4(arr, i) {
  28472. var _i = arr && (typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]);
  28473. if (_i == null) return;
  28474. var _arr = [];
  28475. var _n = true;
  28476. var _d = false;
  28477. var _s, _e;
  28478. try {
  28479. for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
  28480. _arr.push(_s.value);
  28481. if (i && _arr.length === i) break;
  28482. }
  28483. } catch (err) {
  28484. _d = true;
  28485. _e = err;
  28486. } finally {
  28487. try {
  28488. if (!_n && _i["return"] != null) _i["return"]();
  28489. } finally {
  28490. if (_d) throw _e;
  28491. }
  28492. }
  28493. return _arr;
  28494. }
  28495. function _unsupportedIterableToArray$4(o, minLen) {
  28496. if (!o) return;
  28497. if (typeof o === "string") return _arrayLikeToArray$4(o, minLen);
  28498. var n = Object.prototype.toString.call(o).slice(8, -1);
  28499. if (n === "Object" && o.constructor) n = o.constructor.name;
  28500. if (n === "Map" || n === "Set") return Array.from(o);
  28501. if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$4(o, minLen);
  28502. }
  28503. function _arrayLikeToArray$4(arr, len) {
  28504. if (len == null || len > arr.length) len = arr.length;
  28505. for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  28506. return arr2;
  28507. }
  28508. function _nonIterableRest$4() {
  28509. throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  28510. }
  28511. var Prop = function Prop(name, _ref) {
  28512. var _ref$default = _ref["default"],
  28513. defaultVal = _ref$default === void 0 ? null : _ref$default,
  28514. _ref$triggerUpdate = _ref.triggerUpdate,
  28515. triggerUpdate = _ref$triggerUpdate === void 0 ? true : _ref$triggerUpdate,
  28516. _ref$onChange = _ref.onChange,
  28517. onChange = _ref$onChange === void 0 ? function (newVal, state) {} : _ref$onChange;
  28518. _classCallCheck$1(this, Prop);
  28519. this.name = name;
  28520. this.defaultVal = defaultVal;
  28521. this.triggerUpdate = triggerUpdate;
  28522. this.onChange = onChange;
  28523. };
  28524. function index$2 (_ref2) {
  28525. var _ref2$stateInit = _ref2.stateInit,
  28526. stateInit = _ref2$stateInit === void 0 ? function () {
  28527. return {};
  28528. } : _ref2$stateInit,
  28529. _ref2$props = _ref2.props,
  28530. rawProps = _ref2$props === void 0 ? {} : _ref2$props,
  28531. _ref2$methods = _ref2.methods,
  28532. methods = _ref2$methods === void 0 ? {} : _ref2$methods,
  28533. _ref2$aliases = _ref2.aliases,
  28534. aliases = _ref2$aliases === void 0 ? {} : _ref2$aliases,
  28535. _ref2$init = _ref2.init,
  28536. initFn = _ref2$init === void 0 ? function () {} : _ref2$init,
  28537. _ref2$update = _ref2.update,
  28538. updateFn = _ref2$update === void 0 ? function () {} : _ref2$update;
  28539. // Parse props into Prop instances
  28540. var props = Object.keys(rawProps).map(function (propName) {
  28541. return new Prop(propName, rawProps[propName]);
  28542. });
  28543. return function () {
  28544. var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  28545. // Holds component state
  28546. var state = Object.assign({}, stateInit instanceof Function ? stateInit(options) : stateInit, // Support plain objects for backwards compatibility
  28547. {
  28548. initialised: false
  28549. }); // keeps track of which props triggered an update
  28550. var changedProps = {}; // Component constructor
  28551. function comp(nodeElement) {
  28552. initStatic(nodeElement, options);
  28553. digest();
  28554. return comp;
  28555. }
  28556. var initStatic = function initStatic(nodeElement, options) {
  28557. initFn.call(comp, nodeElement, state, options);
  28558. state.initialised = true;
  28559. };
  28560. var digest = debounce_1(function () {
  28561. if (!state.initialised) {
  28562. return;
  28563. }
  28564. updateFn.call(comp, state, changedProps);
  28565. changedProps = {};
  28566. }, 1); // Getter/setter methods
  28567. props.forEach(function (prop) {
  28568. comp[prop.name] = getSetProp(prop);
  28569. function getSetProp(_ref3) {
  28570. var prop = _ref3.name,
  28571. _ref3$triggerUpdate = _ref3.triggerUpdate,
  28572. redigest = _ref3$triggerUpdate === void 0 ? false : _ref3$triggerUpdate,
  28573. _ref3$onChange = _ref3.onChange,
  28574. onChange = _ref3$onChange === void 0 ? function (newVal, state) {} : _ref3$onChange,
  28575. _ref3$defaultVal = _ref3.defaultVal,
  28576. defaultVal = _ref3$defaultVal === void 0 ? null : _ref3$defaultVal;
  28577. return function (_) {
  28578. var curVal = state[prop];
  28579. if (!arguments.length) {
  28580. return curVal;
  28581. } // Getter mode
  28582. var val = _ === undefined ? defaultVal : _; // pick default if value passed is undefined
  28583. state[prop] = val;
  28584. onChange.call(comp, val, state, curVal); // track changed props
  28585. !changedProps.hasOwnProperty(prop) && (changedProps[prop] = curVal);
  28586. if (redigest) {
  28587. digest();
  28588. }
  28589. return comp;
  28590. };
  28591. }
  28592. }); // Other methods
  28593. Object.keys(methods).forEach(function (methodName) {
  28594. comp[methodName] = function () {
  28595. var _methods$methodName;
  28596. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  28597. args[_key] = arguments[_key];
  28598. }
  28599. return (_methods$methodName = methods[methodName]).call.apply(_methods$methodName, [comp, state].concat(args));
  28600. };
  28601. }); // Link aliases
  28602. Object.entries(aliases).forEach(function (_ref4) {
  28603. var _ref5 = _slicedToArray$4(_ref4, 2),
  28604. alias = _ref5[0],
  28605. target = _ref5[1];
  28606. return comp[alias] = comp[target];
  28607. }); // Reset all component props to their default value
  28608. comp.resetProps = function () {
  28609. props.forEach(function (prop) {
  28610. comp[prop.name](prop.defaultVal);
  28611. });
  28612. return comp;
  28613. }; //
  28614. comp.resetProps(); // Apply all prop defaults
  28615. state._rerender = digest; // Expose digest method
  28616. return comp;
  28617. };
  28618. }
  28619. var index$1 = (function (p) {
  28620. return p instanceof Function ? p // fn
  28621. : typeof p === 'string' ? function (obj) {
  28622. return obj[p];
  28623. } // property name
  28624. : function (obj) {
  28625. return p;
  28626. };
  28627. }); // constant
  28628. class InternMap extends Map {
  28629. constructor(entries, key = keyof) {
  28630. super();
  28631. Object.defineProperties(this, {_intern: {value: new Map()}, _key: {value: key}});
  28632. if (entries != null) for (const [key, value] of entries) this.set(key, value);
  28633. }
  28634. get(key) {
  28635. return super.get(intern_get(this, key));
  28636. }
  28637. has(key) {
  28638. return super.has(intern_get(this, key));
  28639. }
  28640. set(key, value) {
  28641. return super.set(intern_set(this, key), value);
  28642. }
  28643. delete(key) {
  28644. return super.delete(intern_delete(this, key));
  28645. }
  28646. }
  28647. function intern_get({_intern, _key}, value) {
  28648. const key = _key(value);
  28649. return _intern.has(key) ? _intern.get(key) : value;
  28650. }
  28651. function intern_set({_intern, _key}, value) {
  28652. const key = _key(value);
  28653. if (_intern.has(key)) return _intern.get(key);
  28654. _intern.set(key, value);
  28655. return value;
  28656. }
  28657. function intern_delete({_intern, _key}, value) {
  28658. const key = _key(value);
  28659. if (_intern.has(key)) {
  28660. value = _intern.get(value);
  28661. _intern.delete(key);
  28662. }
  28663. return value;
  28664. }
  28665. function keyof(value) {
  28666. return value !== null && typeof value === "object" ? value.valueOf() : value;
  28667. }
  28668. function max(values, valueof) {
  28669. let max;
  28670. if (valueof === undefined) {
  28671. for (const value of values) {
  28672. if (value != null
  28673. && (max < value || (max === undefined && value >= value))) {
  28674. max = value;
  28675. }
  28676. }
  28677. } else {
  28678. let index = -1;
  28679. for (let value of values) {
  28680. if ((value = valueof(value, ++index, values)) != null
  28681. && (max < value || (max === undefined && value >= value))) {
  28682. max = value;
  28683. }
  28684. }
  28685. }
  28686. return max;
  28687. }
  28688. function min(values, valueof) {
  28689. let min;
  28690. if (valueof === undefined) {
  28691. for (const value of values) {
  28692. if (value != null
  28693. && (min > value || (min === undefined && value >= value))) {
  28694. min = value;
  28695. }
  28696. }
  28697. } else {
  28698. let index = -1;
  28699. for (let value of values) {
  28700. if ((value = valueof(value, ++index, values)) != null
  28701. && (min > value || (min === undefined && value >= value))) {
  28702. min = value;
  28703. }
  28704. }
  28705. }
  28706. return min;
  28707. }
  28708. function _objectWithoutPropertiesLoose$2(source, excluded) {
  28709. if (source == null) return {};
  28710. var target = {};
  28711. var sourceKeys = Object.keys(source);
  28712. var key, i;
  28713. for (i = 0; i < sourceKeys.length; i++) {
  28714. key = sourceKeys[i];
  28715. if (excluded.indexOf(key) >= 0) continue;
  28716. target[key] = source[key];
  28717. }
  28718. return target;
  28719. }
  28720. function _objectWithoutProperties$2(source, excluded) {
  28721. if (source == null) return {};
  28722. var target = _objectWithoutPropertiesLoose$2(source, excluded);
  28723. var key, i;
  28724. if (Object.getOwnPropertySymbols) {
  28725. var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
  28726. for (i = 0; i < sourceSymbolKeys.length; i++) {
  28727. key = sourceSymbolKeys[i];
  28728. if (excluded.indexOf(key) >= 0) continue;
  28729. if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
  28730. target[key] = source[key];
  28731. }
  28732. }
  28733. return target;
  28734. }
  28735. function _slicedToArray$3(arr, i) {
  28736. return _arrayWithHoles$3(arr) || _iterableToArrayLimit$3(arr, i) || _unsupportedIterableToArray$3(arr, i) || _nonIterableRest$3();
  28737. }
  28738. function _toConsumableArray$3(arr) {
  28739. return _arrayWithoutHoles$3(arr) || _iterableToArray$3(arr) || _unsupportedIterableToArray$3(arr) || _nonIterableSpread$3();
  28740. }
  28741. function _arrayWithoutHoles$3(arr) {
  28742. if (Array.isArray(arr)) return _arrayLikeToArray$3(arr);
  28743. }
  28744. function _arrayWithHoles$3(arr) {
  28745. if (Array.isArray(arr)) return arr;
  28746. }
  28747. function _iterableToArray$3(iter) {
  28748. if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
  28749. }
  28750. function _iterableToArrayLimit$3(arr, i) {
  28751. var _i = arr && (typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]);
  28752. if (_i == null) return;
  28753. var _arr = [];
  28754. var _n = true;
  28755. var _d = false;
  28756. var _s, _e;
  28757. try {
  28758. for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
  28759. _arr.push(_s.value);
  28760. if (i && _arr.length === i) break;
  28761. }
  28762. } catch (err) {
  28763. _d = true;
  28764. _e = err;
  28765. } finally {
  28766. try {
  28767. if (!_n && _i["return"] != null) _i["return"]();
  28768. } finally {
  28769. if (_d) throw _e;
  28770. }
  28771. }
  28772. return _arr;
  28773. }
  28774. function _unsupportedIterableToArray$3(o, minLen) {
  28775. if (!o) return;
  28776. if (typeof o === "string") return _arrayLikeToArray$3(o, minLen);
  28777. var n = Object.prototype.toString.call(o).slice(8, -1);
  28778. if (n === "Object" && o.constructor) n = o.constructor.name;
  28779. if (n === "Map" || n === "Set") return Array.from(o);
  28780. if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$3(o, minLen);
  28781. }
  28782. function _arrayLikeToArray$3(arr, len) {
  28783. if (len == null || len > arr.length) len = arr.length;
  28784. for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  28785. return arr2;
  28786. }
  28787. function _nonIterableSpread$3() {
  28788. throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  28789. }
  28790. function _nonIterableRest$3() {
  28791. throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  28792. }
  28793. function _toPrimitive(input, hint) {
  28794. if (typeof input !== "object" || input === null) return input;
  28795. var prim = input[Symbol.toPrimitive];
  28796. if (prim !== undefined) {
  28797. var res = prim.call(input, hint || "default");
  28798. if (typeof res !== "object") return res;
  28799. throw new TypeError("@@toPrimitive must return a primitive value.");
  28800. }
  28801. return (hint === "string" ? String : Number)(input);
  28802. }
  28803. function _toPropertyKey(arg) {
  28804. var key = _toPrimitive(arg, "string");
  28805. return typeof key === "symbol" ? key : String(key);
  28806. }
  28807. var index = (function () {
  28808. var list = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  28809. var keyAccessors = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  28810. var multiItem = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
  28811. var flattenKeys = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
  28812. var keys = (keyAccessors instanceof Array ? keyAccessors.length ? keyAccessors : [undefined] : [keyAccessors]).map(function (key) {
  28813. return {
  28814. keyAccessor: key,
  28815. isProp: !(key instanceof Function)
  28816. };
  28817. });
  28818. var indexedResult = list.reduce(function (res, item) {
  28819. var iterObj = res;
  28820. var itemVal = item;
  28821. keys.forEach(function (_ref, idx) {
  28822. var keyAccessor = _ref.keyAccessor,
  28823. isProp = _ref.isProp;
  28824. var key;
  28825. if (isProp) {
  28826. var _itemVal = itemVal,
  28827. propVal = _itemVal[keyAccessor],
  28828. rest = _objectWithoutProperties$2(_itemVal, [keyAccessor].map(_toPropertyKey));
  28829. key = propVal;
  28830. itemVal = rest;
  28831. } else {
  28832. key = keyAccessor(itemVal, idx);
  28833. }
  28834. if (idx + 1 < keys.length) {
  28835. if (!iterObj.hasOwnProperty(key)) {
  28836. iterObj[key] = {};
  28837. }
  28838. iterObj = iterObj[key];
  28839. } else {
  28840. // Leaf key
  28841. if (multiItem) {
  28842. if (!iterObj.hasOwnProperty(key)) {
  28843. iterObj[key] = [];
  28844. }
  28845. iterObj[key].push(itemVal);
  28846. } else {
  28847. iterObj[key] = itemVal;
  28848. }
  28849. }
  28850. });
  28851. return res;
  28852. }, {});
  28853. if (multiItem instanceof Function) {
  28854. // Reduce leaf multiple values
  28855. (function reduce(node) {
  28856. var level = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
  28857. if (level === keys.length) {
  28858. Object.keys(node).forEach(function (k) {
  28859. return node[k] = multiItem(node[k]);
  28860. });
  28861. } else {
  28862. Object.values(node).forEach(function (child) {
  28863. return reduce(child, level + 1);
  28864. });
  28865. }
  28866. })(indexedResult); // IIFE
  28867. }
  28868. var result = indexedResult;
  28869. if (flattenKeys) {
  28870. // flatten into array
  28871. result = [];
  28872. (function flatten(node) {
  28873. var accKeys = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  28874. if (accKeys.length === keys.length) {
  28875. result.push({
  28876. keys: accKeys,
  28877. vals: node
  28878. });
  28879. } else {
  28880. Object.entries(node).forEach(function (_ref2) {
  28881. var _ref3 = _slicedToArray$3(_ref2, 2),
  28882. key = _ref3[0],
  28883. val = _ref3[1];
  28884. return flatten(val, [].concat(_toConsumableArray$3(accKeys), [key]));
  28885. });
  28886. }
  28887. })(indexedResult); //IIFE
  28888. if (keyAccessors instanceof Array && keyAccessors.length === 0 && result.length === 1) {
  28889. // clear keys if there's no key accessors (single result)
  28890. result[0].keys = [];
  28891. }
  28892. }
  28893. return result;
  28894. });
  28895. function ownKeys$1(object, enumerableOnly) {
  28896. var keys = Object.keys(object);
  28897. if (Object.getOwnPropertySymbols) {
  28898. var symbols = Object.getOwnPropertySymbols(object);
  28899. if (enumerableOnly) {
  28900. symbols = symbols.filter(function (sym) {
  28901. return Object.getOwnPropertyDescriptor(object, sym).enumerable;
  28902. });
  28903. }
  28904. keys.push.apply(keys, symbols);
  28905. }
  28906. return keys;
  28907. }
  28908. function _objectSpread2$1(target) {
  28909. for (var i = 1; i < arguments.length; i++) {
  28910. var source = arguments[i] != null ? arguments[i] : {};
  28911. if (i % 2) {
  28912. ownKeys$1(Object(source), true).forEach(function (key) {
  28913. _defineProperty$2(target, key, source[key]);
  28914. });
  28915. } else if (Object.getOwnPropertyDescriptors) {
  28916. Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
  28917. } else {
  28918. ownKeys$1(Object(source)).forEach(function (key) {
  28919. Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
  28920. });
  28921. }
  28922. }
  28923. return target;
  28924. }
  28925. function _defineProperty$2(obj, key, value) {
  28926. if (key in obj) {
  28927. Object.defineProperty(obj, key, {
  28928. value: value,
  28929. enumerable: true,
  28930. configurable: true,
  28931. writable: true
  28932. });
  28933. } else {
  28934. obj[key] = value;
  28935. }
  28936. return obj;
  28937. }
  28938. function _objectWithoutPropertiesLoose$1(source, excluded) {
  28939. if (source == null) return {};
  28940. var target = {};
  28941. var sourceKeys = Object.keys(source);
  28942. var key, i;
  28943. for (i = 0; i < sourceKeys.length; i++) {
  28944. key = sourceKeys[i];
  28945. if (excluded.indexOf(key) >= 0) continue;
  28946. target[key] = source[key];
  28947. }
  28948. return target;
  28949. }
  28950. function _objectWithoutProperties$1(source, excluded) {
  28951. if (source == null) return {};
  28952. var target = _objectWithoutPropertiesLoose$1(source, excluded);
  28953. var key, i;
  28954. if (Object.getOwnPropertySymbols) {
  28955. var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
  28956. for (i = 0; i < sourceSymbolKeys.length; i++) {
  28957. key = sourceSymbolKeys[i];
  28958. if (excluded.indexOf(key) >= 0) continue;
  28959. if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
  28960. target[key] = source[key];
  28961. }
  28962. }
  28963. return target;
  28964. }
  28965. function _slicedToArray$2(arr, i) {
  28966. return _arrayWithHoles$2(arr) || _iterableToArrayLimit$2(arr, i) || _unsupportedIterableToArray$2(arr, i) || _nonIterableRest$2();
  28967. }
  28968. function _toConsumableArray$2(arr) {
  28969. return _arrayWithoutHoles$2(arr) || _iterableToArray$2(arr) || _unsupportedIterableToArray$2(arr) || _nonIterableSpread$2();
  28970. }
  28971. function _arrayWithoutHoles$2(arr) {
  28972. if (Array.isArray(arr)) return _arrayLikeToArray$2(arr);
  28973. }
  28974. function _arrayWithHoles$2(arr) {
  28975. if (Array.isArray(arr)) return arr;
  28976. }
  28977. function _iterableToArray$2(iter) {
  28978. if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
  28979. }
  28980. function _iterableToArrayLimit$2(arr, i) {
  28981. var _i = arr && (typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]);
  28982. if (_i == null) return;
  28983. var _arr = [];
  28984. var _n = true;
  28985. var _d = false;
  28986. var _s, _e;
  28987. try {
  28988. for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
  28989. _arr.push(_s.value);
  28990. if (i && _arr.length === i) break;
  28991. }
  28992. } catch (err) {
  28993. _d = true;
  28994. _e = err;
  28995. } finally {
  28996. try {
  28997. if (!_n && _i["return"] != null) _i["return"]();
  28998. } finally {
  28999. if (_d) throw _e;
  29000. }
  29001. }
  29002. return _arr;
  29003. }
  29004. function _unsupportedIterableToArray$2(o, minLen) {
  29005. if (!o) return;
  29006. if (typeof o === "string") return _arrayLikeToArray$2(o, minLen);
  29007. var n = Object.prototype.toString.call(o).slice(8, -1);
  29008. if (n === "Object" && o.constructor) n = o.constructor.name;
  29009. if (n === "Map" || n === "Set") return Array.from(o);
  29010. if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$2(o, minLen);
  29011. }
  29012. function _arrayLikeToArray$2(arr, len) {
  29013. if (len == null || len > arr.length) len = arr.length;
  29014. for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  29015. return arr2;
  29016. }
  29017. function _nonIterableSpread$2() {
  29018. throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  29019. }
  29020. function _nonIterableRest$2() {
  29021. throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  29022. }
  29023. function diffArrays(prev, next, idAccessor) {
  29024. var result = {
  29025. enter: [],
  29026. update: [],
  29027. exit: []
  29028. };
  29029. if (!idAccessor) {
  29030. // use object references for comparison
  29031. var prevSet = new Set(prev);
  29032. var nextSet = new Set(next);
  29033. new Set([].concat(_toConsumableArray$2(prevSet), _toConsumableArray$2(nextSet))).forEach(function (item) {
  29034. var type = !prevSet.has(item) ? 'enter' : !nextSet.has(item) ? 'exit' : 'update';
  29035. result[type].push(type === 'update' ? [item, item] : item);
  29036. });
  29037. } else {
  29038. // compare by id (duplicate keys are ignored)
  29039. var prevById = index(prev, idAccessor, false);
  29040. var nextById = index(next, idAccessor, false);
  29041. var byId = Object.assign({}, prevById, nextById);
  29042. Object.entries(byId).forEach(function (_ref) {
  29043. var _ref2 = _slicedToArray$2(_ref, 2),
  29044. id = _ref2[0],
  29045. item = _ref2[1];
  29046. var type = !prevById.hasOwnProperty(id) ? 'enter' : !nextById.hasOwnProperty(id) ? 'exit' : 'update';
  29047. result[type].push(type === 'update' ? [prevById[id], nextById[id]] : item);
  29048. });
  29049. }
  29050. return result;
  29051. }
  29052. function dataBindDiff(data, existingObjs, _ref3) {
  29053. var _ref3$objBindAttr = _ref3.objBindAttr,
  29054. objBindAttr = _ref3$objBindAttr === void 0 ? '__obj' : _ref3$objBindAttr,
  29055. _ref3$dataBindAttr = _ref3.dataBindAttr,
  29056. dataBindAttr = _ref3$dataBindAttr === void 0 ? '__data' : _ref3$dataBindAttr,
  29057. idAccessor = _ref3.idAccessor,
  29058. _ref3$purge = _ref3.purge,
  29059. purge = _ref3$purge === void 0 ? false : _ref3$purge;
  29060. var isObjValid = function isObjValid(obj) {
  29061. return obj.hasOwnProperty(dataBindAttr);
  29062. };
  29063. var removeObjs = existingObjs.filter(function (obj) {
  29064. return !isObjValid(obj);
  29065. });
  29066. var prevD = existingObjs.filter(isObjValid).map(function (obj) {
  29067. return obj[dataBindAttr];
  29068. });
  29069. var nextD = data;
  29070. var diff = purge ? {
  29071. enter: nextD,
  29072. exit: prevD,
  29073. update: []
  29074. } // don't diff data in purge mode
  29075. : diffArrays(prevD, nextD, idAccessor);
  29076. diff.update = diff.update.map(function (_ref4) {
  29077. var _ref5 = _slicedToArray$2(_ref4, 2),
  29078. prevD = _ref5[0],
  29079. nextD = _ref5[1];
  29080. if (prevD !== nextD) {
  29081. // transfer obj to new data point (if different)
  29082. nextD[objBindAttr] = prevD[objBindAttr];
  29083. nextD[objBindAttr][dataBindAttr] = nextD;
  29084. }
  29085. return nextD;
  29086. });
  29087. diff.exit = diff.exit.concat(removeObjs.map(function (obj) {
  29088. return _defineProperty$2({}, objBindAttr, obj);
  29089. }));
  29090. return diff;
  29091. }
  29092. function viewDigest(data, existingObjs, // list
  29093. appendObj, // item => {...} function
  29094. removeObj, // item => {...} function
  29095. _ref7) {
  29096. var _ref7$createObj = _ref7.createObj,
  29097. createObj = _ref7$createObj === void 0 ? function (d) {
  29098. return {};
  29099. } : _ref7$createObj,
  29100. _ref7$updateObj = _ref7.updateObj,
  29101. updateObj = _ref7$updateObj === void 0 ? function (obj, d) {} : _ref7$updateObj,
  29102. _ref7$exitObj = _ref7.exitObj,
  29103. exitObj = _ref7$exitObj === void 0 ? function (obj) {} : _ref7$exitObj,
  29104. _ref7$objBindAttr = _ref7.objBindAttr,
  29105. objBindAttr = _ref7$objBindAttr === void 0 ? '__obj' : _ref7$objBindAttr,
  29106. _ref7$dataBindAttr = _ref7.dataBindAttr,
  29107. dataBindAttr = _ref7$dataBindAttr === void 0 ? '__data' : _ref7$dataBindAttr,
  29108. dataDiffOptions = _objectWithoutProperties$1(_ref7, ["createObj", "updateObj", "exitObj", "objBindAttr", "dataBindAttr"]);
  29109. var _dataBindDiff = dataBindDiff(data, existingObjs, _objectSpread2$1({
  29110. objBindAttr: objBindAttr,
  29111. dataBindAttr: dataBindAttr
  29112. }, dataDiffOptions)),
  29113. enter = _dataBindDiff.enter,
  29114. update = _dataBindDiff.update,
  29115. exit = _dataBindDiff.exit; // Remove exiting points
  29116. exit.forEach(function (d) {
  29117. var obj = d[objBindAttr];
  29118. delete d[objBindAttr]; // unbind obj
  29119. exitObj(obj);
  29120. removeObj(obj);
  29121. });
  29122. var newObjs = createObjs(enter);
  29123. var pointsData = [].concat(_toConsumableArray$2(enter), _toConsumableArray$2(update));
  29124. updateObjs(pointsData); // Add new points
  29125. newObjs.forEach(appendObj); //
  29126. function createObjs(data) {
  29127. var newObjs = [];
  29128. data.forEach(function (d) {
  29129. var obj = createObj(d);
  29130. if (obj) {
  29131. obj[dataBindAttr] = d;
  29132. d[objBindAttr] = obj;
  29133. newObjs.push(obj);
  29134. }
  29135. });
  29136. return newObjs;
  29137. }
  29138. function updateObjs(data) {
  29139. data.forEach(function (d) {
  29140. var obj = d[objBindAttr];
  29141. if (obj) {
  29142. obj[dataBindAttr] = d;
  29143. updateObj(obj, d);
  29144. }
  29145. });
  29146. }
  29147. }
  29148. function initRange(domain, range) {
  29149. switch (arguments.length) {
  29150. case 0: break;
  29151. case 1: this.range(domain); break;
  29152. default: this.range(range).domain(domain); break;
  29153. }
  29154. return this;
  29155. }
  29156. const implicit = Symbol("implicit");
  29157. function ordinal() {
  29158. var index = new InternMap(),
  29159. domain = [],
  29160. range = [],
  29161. unknown = implicit;
  29162. function scale(d) {
  29163. let i = index.get(d);
  29164. if (i === undefined) {
  29165. if (unknown !== implicit) return unknown;
  29166. index.set(d, i = domain.push(d) - 1);
  29167. }
  29168. return range[i % range.length];
  29169. }
  29170. scale.domain = function(_) {
  29171. if (!arguments.length) return domain.slice();
  29172. domain = [], index = new InternMap();
  29173. for (const value of _) {
  29174. if (index.has(value)) continue;
  29175. index.set(value, domain.push(value) - 1);
  29176. }
  29177. return scale;
  29178. };
  29179. scale.range = function(_) {
  29180. return arguments.length ? (range = Array.from(_), scale) : range.slice();
  29181. };
  29182. scale.unknown = function(_) {
  29183. return arguments.length ? (unknown = _, scale) : unknown;
  29184. };
  29185. scale.copy = function() {
  29186. return ordinal(domain, range).unknown(unknown);
  29187. };
  29188. initRange.apply(scale, arguments);
  29189. return scale;
  29190. }
  29191. function colors(specifier) {
  29192. var n = specifier.length / 6 | 0, colors = new Array(n), i = 0;
  29193. while (i < n) colors[i] = "#" + specifier.slice(i * 6, ++i * 6);
  29194. return colors;
  29195. }
  29196. var schemePaired = colors("a6cee31f78b4b2df8a33a02cfb9a99e31a1cfdbf6fff7f00cab2d66a3d9affff99b15928");
  29197. var tinycolor = {exports: {}};
  29198. (function (module) {
  29199. // TinyColor v1.4.2
  29200. // https://github.com/bgrins/TinyColor
  29201. // Brian Grinstead, MIT License
  29202. (function(Math) {
  29203. var trimLeft = /^\s+/,
  29204. trimRight = /\s+$/,
  29205. tinyCounter = 0,
  29206. mathRound = Math.round,
  29207. mathMin = Math.min,
  29208. mathMax = Math.max,
  29209. mathRandom = Math.random;
  29210. function tinycolor (color, opts) {
  29211. color = (color) ? color : '';
  29212. opts = opts || { };
  29213. // If input is already a tinycolor, return itself
  29214. if (color instanceof tinycolor) {
  29215. return color;
  29216. }
  29217. // If we are called as a function, call using new instead
  29218. if (!(this instanceof tinycolor)) {
  29219. return new tinycolor(color, opts);
  29220. }
  29221. var rgb = inputToRGB(color);
  29222. this._originalInput = color,
  29223. this._r = rgb.r,
  29224. this._g = rgb.g,
  29225. this._b = rgb.b,
  29226. this._a = rgb.a,
  29227. this._roundA = mathRound(100*this._a) / 100,
  29228. this._format = opts.format || rgb.format;
  29229. this._gradientType = opts.gradientType;
  29230. // Don't let the range of [0,255] come back in [0,1].
  29231. // Potentially lose a little bit of precision here, but will fix issues where
  29232. // .5 gets interpreted as half of the total, instead of half of 1
  29233. // If it was supposed to be 128, this was already taken care of by `inputToRgb`
  29234. if (this._r < 1) { this._r = mathRound(this._r); }
  29235. if (this._g < 1) { this._g = mathRound(this._g); }
  29236. if (this._b < 1) { this._b = mathRound(this._b); }
  29237. this._ok = rgb.ok;
  29238. this._tc_id = tinyCounter++;
  29239. }
  29240. tinycolor.prototype = {
  29241. isDark: function() {
  29242. return this.getBrightness() < 128;
  29243. },
  29244. isLight: function() {
  29245. return !this.isDark();
  29246. },
  29247. isValid: function() {
  29248. return this._ok;
  29249. },
  29250. getOriginalInput: function() {
  29251. return this._originalInput;
  29252. },
  29253. getFormat: function() {
  29254. return this._format;
  29255. },
  29256. getAlpha: function() {
  29257. return this._a;
  29258. },
  29259. getBrightness: function() {
  29260. //http://www.w3.org/TR/AERT#color-contrast
  29261. var rgb = this.toRgb();
  29262. return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000;
  29263. },
  29264. getLuminance: function() {
  29265. //http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef
  29266. var rgb = this.toRgb();
  29267. var RsRGB, GsRGB, BsRGB, R, G, B;
  29268. RsRGB = rgb.r/255;
  29269. GsRGB = rgb.g/255;
  29270. BsRGB = rgb.b/255;
  29271. if (RsRGB <= 0.03928) {R = RsRGB / 12.92;} else {R = Math.pow(((RsRGB + 0.055) / 1.055), 2.4);}
  29272. if (GsRGB <= 0.03928) {G = GsRGB / 12.92;} else {G = Math.pow(((GsRGB + 0.055) / 1.055), 2.4);}
  29273. if (BsRGB <= 0.03928) {B = BsRGB / 12.92;} else {B = Math.pow(((BsRGB + 0.055) / 1.055), 2.4);}
  29274. return (0.2126 * R) + (0.7152 * G) + (0.0722 * B);
  29275. },
  29276. setAlpha: function(value) {
  29277. this._a = boundAlpha(value);
  29278. this._roundA = mathRound(100*this._a) / 100;
  29279. return this;
  29280. },
  29281. toHsv: function() {
  29282. var hsv = rgbToHsv(this._r, this._g, this._b);
  29283. return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: this._a };
  29284. },
  29285. toHsvString: function() {
  29286. var hsv = rgbToHsv(this._r, this._g, this._b);
  29287. var h = mathRound(hsv.h * 360), s = mathRound(hsv.s * 100), v = mathRound(hsv.v * 100);
  29288. return (this._a == 1) ?
  29289. "hsv(" + h + ", " + s + "%, " + v + "%)" :
  29290. "hsva(" + h + ", " + s + "%, " + v + "%, "+ this._roundA + ")";
  29291. },
  29292. toHsl: function() {
  29293. var hsl = rgbToHsl(this._r, this._g, this._b);
  29294. return { h: hsl.h * 360, s: hsl.s, l: hsl.l, a: this._a };
  29295. },
  29296. toHslString: function() {
  29297. var hsl = rgbToHsl(this._r, this._g, this._b);
  29298. var h = mathRound(hsl.h * 360), s = mathRound(hsl.s * 100), l = mathRound(hsl.l * 100);
  29299. return (this._a == 1) ?
  29300. "hsl(" + h + ", " + s + "%, " + l + "%)" :
  29301. "hsla(" + h + ", " + s + "%, " + l + "%, "+ this._roundA + ")";
  29302. },
  29303. toHex: function(allow3Char) {
  29304. return rgbToHex(this._r, this._g, this._b, allow3Char);
  29305. },
  29306. toHexString: function(allow3Char) {
  29307. return '#' + this.toHex(allow3Char);
  29308. },
  29309. toHex8: function(allow4Char) {
  29310. return rgbaToHex(this._r, this._g, this._b, this._a, allow4Char);
  29311. },
  29312. toHex8String: function(allow4Char) {
  29313. return '#' + this.toHex8(allow4Char);
  29314. },
  29315. toRgb: function() {
  29316. return { r: mathRound(this._r), g: mathRound(this._g), b: mathRound(this._b), a: this._a };
  29317. },
  29318. toRgbString: function() {
  29319. return (this._a == 1) ?
  29320. "rgb(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ")" :
  29321. "rgba(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ", " + this._roundA + ")";
  29322. },
  29323. toPercentageRgb: function() {
  29324. return { r: mathRound(bound01(this._r, 255) * 100) + "%", g: mathRound(bound01(this._g, 255) * 100) + "%", b: mathRound(bound01(this._b, 255) * 100) + "%", a: this._a };
  29325. },
  29326. toPercentageRgbString: function() {
  29327. return (this._a == 1) ?
  29328. "rgb(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%)" :
  29329. "rgba(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%, " + this._roundA + ")";
  29330. },
  29331. toName: function() {
  29332. if (this._a === 0) {
  29333. return "transparent";
  29334. }
  29335. if (this._a < 1) {
  29336. return false;
  29337. }
  29338. return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false;
  29339. },
  29340. toFilter: function(secondColor) {
  29341. var hex8String = '#' + rgbaToArgbHex(this._r, this._g, this._b, this._a);
  29342. var secondHex8String = hex8String;
  29343. var gradientType = this._gradientType ? "GradientType = 1, " : "";
  29344. if (secondColor) {
  29345. var s = tinycolor(secondColor);
  29346. secondHex8String = '#' + rgbaToArgbHex(s._r, s._g, s._b, s._a);
  29347. }
  29348. return "progid:DXImageTransform.Microsoft.gradient("+gradientType+"startColorstr="+hex8String+",endColorstr="+secondHex8String+")";
  29349. },
  29350. toString: function(format) {
  29351. var formatSet = !!format;
  29352. format = format || this._format;
  29353. var formattedString = false;
  29354. var hasAlpha = this._a < 1 && this._a >= 0;
  29355. var needsAlphaFormat = !formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "hex4" || format === "hex8" || format === "name");
  29356. if (needsAlphaFormat) {
  29357. // Special case for "transparent", all other non-alpha formats
  29358. // will return rgba when there is transparency.
  29359. if (format === "name" && this._a === 0) {
  29360. return this.toName();
  29361. }
  29362. return this.toRgbString();
  29363. }
  29364. if (format === "rgb") {
  29365. formattedString = this.toRgbString();
  29366. }
  29367. if (format === "prgb") {
  29368. formattedString = this.toPercentageRgbString();
  29369. }
  29370. if (format === "hex" || format === "hex6") {
  29371. formattedString = this.toHexString();
  29372. }
  29373. if (format === "hex3") {
  29374. formattedString = this.toHexString(true);
  29375. }
  29376. if (format === "hex4") {
  29377. formattedString = this.toHex8String(true);
  29378. }
  29379. if (format === "hex8") {
  29380. formattedString = this.toHex8String();
  29381. }
  29382. if (format === "name") {
  29383. formattedString = this.toName();
  29384. }
  29385. if (format === "hsl") {
  29386. formattedString = this.toHslString();
  29387. }
  29388. if (format === "hsv") {
  29389. formattedString = this.toHsvString();
  29390. }
  29391. return formattedString || this.toHexString();
  29392. },
  29393. clone: function() {
  29394. return tinycolor(this.toString());
  29395. },
  29396. _applyModification: function(fn, args) {
  29397. var color = fn.apply(null, [this].concat([].slice.call(args)));
  29398. this._r = color._r;
  29399. this._g = color._g;
  29400. this._b = color._b;
  29401. this.setAlpha(color._a);
  29402. return this;
  29403. },
  29404. lighten: function() {
  29405. return this._applyModification(lighten, arguments);
  29406. },
  29407. brighten: function() {
  29408. return this._applyModification(brighten, arguments);
  29409. },
  29410. darken: function() {
  29411. return this._applyModification(darken, arguments);
  29412. },
  29413. desaturate: function() {
  29414. return this._applyModification(desaturate, arguments);
  29415. },
  29416. saturate: function() {
  29417. return this._applyModification(saturate, arguments);
  29418. },
  29419. greyscale: function() {
  29420. return this._applyModification(greyscale, arguments);
  29421. },
  29422. spin: function() {
  29423. return this._applyModification(spin, arguments);
  29424. },
  29425. _applyCombination: function(fn, args) {
  29426. return fn.apply(null, [this].concat([].slice.call(args)));
  29427. },
  29428. analogous: function() {
  29429. return this._applyCombination(analogous, arguments);
  29430. },
  29431. complement: function() {
  29432. return this._applyCombination(complement, arguments);
  29433. },
  29434. monochromatic: function() {
  29435. return this._applyCombination(monochromatic, arguments);
  29436. },
  29437. splitcomplement: function() {
  29438. return this._applyCombination(splitcomplement, arguments);
  29439. },
  29440. triad: function() {
  29441. return this._applyCombination(triad, arguments);
  29442. },
  29443. tetrad: function() {
  29444. return this._applyCombination(tetrad, arguments);
  29445. }
  29446. };
  29447. // If input is an object, force 1 into "1.0" to handle ratios properly
  29448. // String input requires "1.0" as input, so 1 will be treated as 1
  29449. tinycolor.fromRatio = function(color, opts) {
  29450. if (typeof color == "object") {
  29451. var newColor = {};
  29452. for (var i in color) {
  29453. if (color.hasOwnProperty(i)) {
  29454. if (i === "a") {
  29455. newColor[i] = color[i];
  29456. }
  29457. else {
  29458. newColor[i] = convertToPercentage(color[i]);
  29459. }
  29460. }
  29461. }
  29462. color = newColor;
  29463. }
  29464. return tinycolor(color, opts);
  29465. };
  29466. // Given a string or object, convert that input to RGB
  29467. // Possible string inputs:
  29468. //
  29469. // "red"
  29470. // "#f00" or "f00"
  29471. // "#ff0000" or "ff0000"
  29472. // "#ff000000" or "ff000000"
  29473. // "rgb 255 0 0" or "rgb (255, 0, 0)"
  29474. // "rgb 1.0 0 0" or "rgb (1, 0, 0)"
  29475. // "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1"
  29476. // "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1"
  29477. // "hsl(0, 100%, 50%)" or "hsl 0 100% 50%"
  29478. // "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1"
  29479. // "hsv(0, 100%, 100%)" or "hsv 0 100% 100%"
  29480. //
  29481. function inputToRGB(color) {
  29482. var rgb = { r: 0, g: 0, b: 0 };
  29483. var a = 1;
  29484. var s = null;
  29485. var v = null;
  29486. var l = null;
  29487. var ok = false;
  29488. var format = false;
  29489. if (typeof color == "string") {
  29490. color = stringInputToObject(color);
  29491. }
  29492. if (typeof color == "object") {
  29493. if (isValidCSSUnit(color.r) && isValidCSSUnit(color.g) && isValidCSSUnit(color.b)) {
  29494. rgb = rgbToRgb(color.r, color.g, color.b);
  29495. ok = true;
  29496. format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb";
  29497. }
  29498. else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.v)) {
  29499. s = convertToPercentage(color.s);
  29500. v = convertToPercentage(color.v);
  29501. rgb = hsvToRgb(color.h, s, v);
  29502. ok = true;
  29503. format = "hsv";
  29504. }
  29505. else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.l)) {
  29506. s = convertToPercentage(color.s);
  29507. l = convertToPercentage(color.l);
  29508. rgb = hslToRgb(color.h, s, l);
  29509. ok = true;
  29510. format = "hsl";
  29511. }
  29512. if (color.hasOwnProperty("a")) {
  29513. a = color.a;
  29514. }
  29515. }
  29516. a = boundAlpha(a);
  29517. return {
  29518. ok: ok,
  29519. format: color.format || format,
  29520. r: mathMin(255, mathMax(rgb.r, 0)),
  29521. g: mathMin(255, mathMax(rgb.g, 0)),
  29522. b: mathMin(255, mathMax(rgb.b, 0)),
  29523. a: a
  29524. };
  29525. }
  29526. // Conversion Functions
  29527. // --------------------
  29528. // `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from:
  29529. // <http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript>
  29530. // `rgbToRgb`
  29531. // Handle bounds / percentage checking to conform to CSS color spec
  29532. // <http://www.w3.org/TR/css3-color/>
  29533. // *Assumes:* r, g, b in [0, 255] or [0, 1]
  29534. // *Returns:* { r, g, b } in [0, 255]
  29535. function rgbToRgb(r, g, b){
  29536. return {
  29537. r: bound01(r, 255) * 255,
  29538. g: bound01(g, 255) * 255,
  29539. b: bound01(b, 255) * 255
  29540. };
  29541. }
  29542. // `rgbToHsl`
  29543. // Converts an RGB color value to HSL.
  29544. // *Assumes:* r, g, and b are contained in [0, 255] or [0, 1]
  29545. // *Returns:* { h, s, l } in [0,1]
  29546. function rgbToHsl(r, g, b) {
  29547. r = bound01(r, 255);
  29548. g = bound01(g, 255);
  29549. b = bound01(b, 255);
  29550. var max = mathMax(r, g, b), min = mathMin(r, g, b);
  29551. var h, s, l = (max + min) / 2;
  29552. if(max == min) {
  29553. h = s = 0; // achromatic
  29554. }
  29555. else {
  29556. var d = max - min;
  29557. s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
  29558. switch(max) {
  29559. case r: h = (g - b) / d + (g < b ? 6 : 0); break;
  29560. case g: h = (b - r) / d + 2; break;
  29561. case b: h = (r - g) / d + 4; break;
  29562. }
  29563. h /= 6;
  29564. }
  29565. return { h: h, s: s, l: l };
  29566. }
  29567. // `hslToRgb`
  29568. // Converts an HSL color value to RGB.
  29569. // *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100]
  29570. // *Returns:* { r, g, b } in the set [0, 255]
  29571. function hslToRgb(h, s, l) {
  29572. var r, g, b;
  29573. h = bound01(h, 360);
  29574. s = bound01(s, 100);
  29575. l = bound01(l, 100);
  29576. function hue2rgb(p, q, t) {
  29577. if(t < 0) t += 1;
  29578. if(t > 1) t -= 1;
  29579. if(t < 1/6) return p + (q - p) * 6 * t;
  29580. if(t < 1/2) return q;
  29581. if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
  29582. return p;
  29583. }
  29584. if(s === 0) {
  29585. r = g = b = l; // achromatic
  29586. }
  29587. else {
  29588. var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
  29589. var p = 2 * l - q;
  29590. r = hue2rgb(p, q, h + 1/3);
  29591. g = hue2rgb(p, q, h);
  29592. b = hue2rgb(p, q, h - 1/3);
  29593. }
  29594. return { r: r * 255, g: g * 255, b: b * 255 };
  29595. }
  29596. // `rgbToHsv`
  29597. // Converts an RGB color value to HSV
  29598. // *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1]
  29599. // *Returns:* { h, s, v } in [0,1]
  29600. function rgbToHsv(r, g, b) {
  29601. r = bound01(r, 255);
  29602. g = bound01(g, 255);
  29603. b = bound01(b, 255);
  29604. var max = mathMax(r, g, b), min = mathMin(r, g, b);
  29605. var h, s, v = max;
  29606. var d = max - min;
  29607. s = max === 0 ? 0 : d / max;
  29608. if(max == min) {
  29609. h = 0; // achromatic
  29610. }
  29611. else {
  29612. switch(max) {
  29613. case r: h = (g - b) / d + (g < b ? 6 : 0); break;
  29614. case g: h = (b - r) / d + 2; break;
  29615. case b: h = (r - g) / d + 4; break;
  29616. }
  29617. h /= 6;
  29618. }
  29619. return { h: h, s: s, v: v };
  29620. }
  29621. // `hsvToRgb`
  29622. // Converts an HSV color value to RGB.
  29623. // *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100]
  29624. // *Returns:* { r, g, b } in the set [0, 255]
  29625. function hsvToRgb(h, s, v) {
  29626. h = bound01(h, 360) * 6;
  29627. s = bound01(s, 100);
  29628. v = bound01(v, 100);
  29629. var i = Math.floor(h),
  29630. f = h - i,
  29631. p = v * (1 - s),
  29632. q = v * (1 - f * s),
  29633. t = v * (1 - (1 - f) * s),
  29634. mod = i % 6,
  29635. r = [v, q, p, p, t, v][mod],
  29636. g = [t, v, v, q, p, p][mod],
  29637. b = [p, p, t, v, v, q][mod];
  29638. return { r: r * 255, g: g * 255, b: b * 255 };
  29639. }
  29640. // `rgbToHex`
  29641. // Converts an RGB color to hex
  29642. // Assumes r, g, and b are contained in the set [0, 255]
  29643. // Returns a 3 or 6 character hex
  29644. function rgbToHex(r, g, b, allow3Char) {
  29645. var hex = [
  29646. pad2(mathRound(r).toString(16)),
  29647. pad2(mathRound(g).toString(16)),
  29648. pad2(mathRound(b).toString(16))
  29649. ];
  29650. // Return a 3 character hex if possible
  29651. if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) {
  29652. return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0);
  29653. }
  29654. return hex.join("");
  29655. }
  29656. // `rgbaToHex`
  29657. // Converts an RGBA color plus alpha transparency to hex
  29658. // Assumes r, g, b are contained in the set [0, 255] and
  29659. // a in [0, 1]. Returns a 4 or 8 character rgba hex
  29660. function rgbaToHex(r, g, b, a, allow4Char) {
  29661. var hex = [
  29662. pad2(mathRound(r).toString(16)),
  29663. pad2(mathRound(g).toString(16)),
  29664. pad2(mathRound(b).toString(16)),
  29665. pad2(convertDecimalToHex(a))
  29666. ];
  29667. // Return a 4 character hex if possible
  29668. if (allow4Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1) && hex[3].charAt(0) == hex[3].charAt(1)) {
  29669. return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0) + hex[3].charAt(0);
  29670. }
  29671. return hex.join("");
  29672. }
  29673. // `rgbaToArgbHex`
  29674. // Converts an RGBA color to an ARGB Hex8 string
  29675. // Rarely used, but required for "toFilter()"
  29676. function rgbaToArgbHex(r, g, b, a) {
  29677. var hex = [
  29678. pad2(convertDecimalToHex(a)),
  29679. pad2(mathRound(r).toString(16)),
  29680. pad2(mathRound(g).toString(16)),
  29681. pad2(mathRound(b).toString(16))
  29682. ];
  29683. return hex.join("");
  29684. }
  29685. // `equals`
  29686. // Can be called with any tinycolor input
  29687. tinycolor.equals = function (color1, color2) {
  29688. if (!color1 || !color2) { return false; }
  29689. return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString();
  29690. };
  29691. tinycolor.random = function() {
  29692. return tinycolor.fromRatio({
  29693. r: mathRandom(),
  29694. g: mathRandom(),
  29695. b: mathRandom()
  29696. });
  29697. };
  29698. // Modification Functions
  29699. // ----------------------
  29700. // Thanks to less.js for some of the basics here
  29701. // <https://github.com/cloudhead/less.js/blob/master/lib/less/functions.js>
  29702. function desaturate(color, amount) {
  29703. amount = (amount === 0) ? 0 : (amount || 10);
  29704. var hsl = tinycolor(color).toHsl();
  29705. hsl.s -= amount / 100;
  29706. hsl.s = clamp01(hsl.s);
  29707. return tinycolor(hsl);
  29708. }
  29709. function saturate(color, amount) {
  29710. amount = (amount === 0) ? 0 : (amount || 10);
  29711. var hsl = tinycolor(color).toHsl();
  29712. hsl.s += amount / 100;
  29713. hsl.s = clamp01(hsl.s);
  29714. return tinycolor(hsl);
  29715. }
  29716. function greyscale(color) {
  29717. return tinycolor(color).desaturate(100);
  29718. }
  29719. function lighten (color, amount) {
  29720. amount = (amount === 0) ? 0 : (amount || 10);
  29721. var hsl = tinycolor(color).toHsl();
  29722. hsl.l += amount / 100;
  29723. hsl.l = clamp01(hsl.l);
  29724. return tinycolor(hsl);
  29725. }
  29726. function brighten(color, amount) {
  29727. amount = (amount === 0) ? 0 : (amount || 10);
  29728. var rgb = tinycolor(color).toRgb();
  29729. rgb.r = mathMax(0, mathMin(255, rgb.r - mathRound(255 * - (amount / 100))));
  29730. rgb.g = mathMax(0, mathMin(255, rgb.g - mathRound(255 * - (amount / 100))));
  29731. rgb.b = mathMax(0, mathMin(255, rgb.b - mathRound(255 * - (amount / 100))));
  29732. return tinycolor(rgb);
  29733. }
  29734. function darken (color, amount) {
  29735. amount = (amount === 0) ? 0 : (amount || 10);
  29736. var hsl = tinycolor(color).toHsl();
  29737. hsl.l -= amount / 100;
  29738. hsl.l = clamp01(hsl.l);
  29739. return tinycolor(hsl);
  29740. }
  29741. // Spin takes a positive or negative amount within [-360, 360] indicating the change of hue.
  29742. // Values outside of this range will be wrapped into this range.
  29743. function spin(color, amount) {
  29744. var hsl = tinycolor(color).toHsl();
  29745. var hue = (hsl.h + amount) % 360;
  29746. hsl.h = hue < 0 ? 360 + hue : hue;
  29747. return tinycolor(hsl);
  29748. }
  29749. // Combination Functions
  29750. // ---------------------
  29751. // Thanks to jQuery xColor for some of the ideas behind these
  29752. // <https://github.com/infusion/jQuery-xcolor/blob/master/jquery.xcolor.js>
  29753. function complement(color) {
  29754. var hsl = tinycolor(color).toHsl();
  29755. hsl.h = (hsl.h + 180) % 360;
  29756. return tinycolor(hsl);
  29757. }
  29758. function triad(color) {
  29759. var hsl = tinycolor(color).toHsl();
  29760. var h = hsl.h;
  29761. return [
  29762. tinycolor(color),
  29763. tinycolor({ h: (h + 120) % 360, s: hsl.s, l: hsl.l }),
  29764. tinycolor({ h: (h + 240) % 360, s: hsl.s, l: hsl.l })
  29765. ];
  29766. }
  29767. function tetrad(color) {
  29768. var hsl = tinycolor(color).toHsl();
  29769. var h = hsl.h;
  29770. return [
  29771. tinycolor(color),
  29772. tinycolor({ h: (h + 90) % 360, s: hsl.s, l: hsl.l }),
  29773. tinycolor({ h: (h + 180) % 360, s: hsl.s, l: hsl.l }),
  29774. tinycolor({ h: (h + 270) % 360, s: hsl.s, l: hsl.l })
  29775. ];
  29776. }
  29777. function splitcomplement(color) {
  29778. var hsl = tinycolor(color).toHsl();
  29779. var h = hsl.h;
  29780. return [
  29781. tinycolor(color),
  29782. tinycolor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l}),
  29783. tinycolor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l})
  29784. ];
  29785. }
  29786. function analogous(color, results, slices) {
  29787. results = results || 6;
  29788. slices = slices || 30;
  29789. var hsl = tinycolor(color).toHsl();
  29790. var part = 360 / slices;
  29791. var ret = [tinycolor(color)];
  29792. for (hsl.h = ((hsl.h - (part * results >> 1)) + 720) % 360; --results; ) {
  29793. hsl.h = (hsl.h + part) % 360;
  29794. ret.push(tinycolor(hsl));
  29795. }
  29796. return ret;
  29797. }
  29798. function monochromatic(color, results) {
  29799. results = results || 6;
  29800. var hsv = tinycolor(color).toHsv();
  29801. var h = hsv.h, s = hsv.s, v = hsv.v;
  29802. var ret = [];
  29803. var modification = 1 / results;
  29804. while (results--) {
  29805. ret.push(tinycolor({ h: h, s: s, v: v}));
  29806. v = (v + modification) % 1;
  29807. }
  29808. return ret;
  29809. }
  29810. // Utility Functions
  29811. // ---------------------
  29812. tinycolor.mix = function(color1, color2, amount) {
  29813. amount = (amount === 0) ? 0 : (amount || 50);
  29814. var rgb1 = tinycolor(color1).toRgb();
  29815. var rgb2 = tinycolor(color2).toRgb();
  29816. var p = amount / 100;
  29817. var rgba = {
  29818. r: ((rgb2.r - rgb1.r) * p) + rgb1.r,
  29819. g: ((rgb2.g - rgb1.g) * p) + rgb1.g,
  29820. b: ((rgb2.b - rgb1.b) * p) + rgb1.b,
  29821. a: ((rgb2.a - rgb1.a) * p) + rgb1.a
  29822. };
  29823. return tinycolor(rgba);
  29824. };
  29825. // Readability Functions
  29826. // ---------------------
  29827. // <http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef (WCAG Version 2)
  29828. // `contrast`
  29829. // Analyze the 2 colors and returns the color contrast defined by (WCAG Version 2)
  29830. tinycolor.readability = function(color1, color2) {
  29831. var c1 = tinycolor(color1);
  29832. var c2 = tinycolor(color2);
  29833. return (Math.max(c1.getLuminance(),c2.getLuminance())+0.05) / (Math.min(c1.getLuminance(),c2.getLuminance())+0.05);
  29834. };
  29835. // `isReadable`
  29836. // Ensure that foreground and background color combinations meet WCAG2 guidelines.
  29837. // The third argument is an optional Object.
  29838. // the 'level' property states 'AA' or 'AAA' - if missing or invalid, it defaults to 'AA';
  29839. // the 'size' property states 'large' or 'small' - if missing or invalid, it defaults to 'small'.
  29840. // If the entire object is absent, isReadable defaults to {level:"AA",size:"small"}.
  29841. // *Example*
  29842. // tinycolor.isReadable("#000", "#111") => false
  29843. // tinycolor.isReadable("#000", "#111",{level:"AA",size:"large"}) => false
  29844. tinycolor.isReadable = function(color1, color2, wcag2) {
  29845. var readability = tinycolor.readability(color1, color2);
  29846. var wcag2Parms, out;
  29847. out = false;
  29848. wcag2Parms = validateWCAG2Parms(wcag2);
  29849. switch (wcag2Parms.level + wcag2Parms.size) {
  29850. case "AAsmall":
  29851. case "AAAlarge":
  29852. out = readability >= 4.5;
  29853. break;
  29854. case "AAlarge":
  29855. out = readability >= 3;
  29856. break;
  29857. case "AAAsmall":
  29858. out = readability >= 7;
  29859. break;
  29860. }
  29861. return out;
  29862. };
  29863. // `mostReadable`
  29864. // Given a base color and a list of possible foreground or background
  29865. // colors for that base, returns the most readable color.
  29866. // Optionally returns Black or White if the most readable color is unreadable.
  29867. // *Example*
  29868. // tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:false}).toHexString(); // "#112255"
  29869. // tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:true}).toHexString(); // "#ffffff"
  29870. // tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"large"}).toHexString(); // "#faf3f3"
  29871. // tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"small"}).toHexString(); // "#ffffff"
  29872. tinycolor.mostReadable = function(baseColor, colorList, args) {
  29873. var bestColor = null;
  29874. var bestScore = 0;
  29875. var readability;
  29876. var includeFallbackColors, level, size ;
  29877. args = args || {};
  29878. includeFallbackColors = args.includeFallbackColors ;
  29879. level = args.level;
  29880. size = args.size;
  29881. for (var i= 0; i < colorList.length ; i++) {
  29882. readability = tinycolor.readability(baseColor, colorList[i]);
  29883. if (readability > bestScore) {
  29884. bestScore = readability;
  29885. bestColor = tinycolor(colorList[i]);
  29886. }
  29887. }
  29888. if (tinycolor.isReadable(baseColor, bestColor, {"level":level,"size":size}) || !includeFallbackColors) {
  29889. return bestColor;
  29890. }
  29891. else {
  29892. args.includeFallbackColors=false;
  29893. return tinycolor.mostReadable(baseColor,["#fff", "#000"],args);
  29894. }
  29895. };
  29896. // Big List of Colors
  29897. // ------------------
  29898. // <http://www.w3.org/TR/css3-color/#svg-color>
  29899. var names = tinycolor.names = {
  29900. aliceblue: "f0f8ff",
  29901. antiquewhite: "faebd7",
  29902. aqua: "0ff",
  29903. aquamarine: "7fffd4",
  29904. azure: "f0ffff",
  29905. beige: "f5f5dc",
  29906. bisque: "ffe4c4",
  29907. black: "000",
  29908. blanchedalmond: "ffebcd",
  29909. blue: "00f",
  29910. blueviolet: "8a2be2",
  29911. brown: "a52a2a",
  29912. burlywood: "deb887",
  29913. burntsienna: "ea7e5d",
  29914. cadetblue: "5f9ea0",
  29915. chartreuse: "7fff00",
  29916. chocolate: "d2691e",
  29917. coral: "ff7f50",
  29918. cornflowerblue: "6495ed",
  29919. cornsilk: "fff8dc",
  29920. crimson: "dc143c",
  29921. cyan: "0ff",
  29922. darkblue: "00008b",
  29923. darkcyan: "008b8b",
  29924. darkgoldenrod: "b8860b",
  29925. darkgray: "a9a9a9",
  29926. darkgreen: "006400",
  29927. darkgrey: "a9a9a9",
  29928. darkkhaki: "bdb76b",
  29929. darkmagenta: "8b008b",
  29930. darkolivegreen: "556b2f",
  29931. darkorange: "ff8c00",
  29932. darkorchid: "9932cc",
  29933. darkred: "8b0000",
  29934. darksalmon: "e9967a",
  29935. darkseagreen: "8fbc8f",
  29936. darkslateblue: "483d8b",
  29937. darkslategray: "2f4f4f",
  29938. darkslategrey: "2f4f4f",
  29939. darkturquoise: "00ced1",
  29940. darkviolet: "9400d3",
  29941. deeppink: "ff1493",
  29942. deepskyblue: "00bfff",
  29943. dimgray: "696969",
  29944. dimgrey: "696969",
  29945. dodgerblue: "1e90ff",
  29946. firebrick: "b22222",
  29947. floralwhite: "fffaf0",
  29948. forestgreen: "228b22",
  29949. fuchsia: "f0f",
  29950. gainsboro: "dcdcdc",
  29951. ghostwhite: "f8f8ff",
  29952. gold: "ffd700",
  29953. goldenrod: "daa520",
  29954. gray: "808080",
  29955. green: "008000",
  29956. greenyellow: "adff2f",
  29957. grey: "808080",
  29958. honeydew: "f0fff0",
  29959. hotpink: "ff69b4",
  29960. indianred: "cd5c5c",
  29961. indigo: "4b0082",
  29962. ivory: "fffff0",
  29963. khaki: "f0e68c",
  29964. lavender: "e6e6fa",
  29965. lavenderblush: "fff0f5",
  29966. lawngreen: "7cfc00",
  29967. lemonchiffon: "fffacd",
  29968. lightblue: "add8e6",
  29969. lightcoral: "f08080",
  29970. lightcyan: "e0ffff",
  29971. lightgoldenrodyellow: "fafad2",
  29972. lightgray: "d3d3d3",
  29973. lightgreen: "90ee90",
  29974. lightgrey: "d3d3d3",
  29975. lightpink: "ffb6c1",
  29976. lightsalmon: "ffa07a",
  29977. lightseagreen: "20b2aa",
  29978. lightskyblue: "87cefa",
  29979. lightslategray: "789",
  29980. lightslategrey: "789",
  29981. lightsteelblue: "b0c4de",
  29982. lightyellow: "ffffe0",
  29983. lime: "0f0",
  29984. limegreen: "32cd32",
  29985. linen: "faf0e6",
  29986. magenta: "f0f",
  29987. maroon: "800000",
  29988. mediumaquamarine: "66cdaa",
  29989. mediumblue: "0000cd",
  29990. mediumorchid: "ba55d3",
  29991. mediumpurple: "9370db",
  29992. mediumseagreen: "3cb371",
  29993. mediumslateblue: "7b68ee",
  29994. mediumspringgreen: "00fa9a",
  29995. mediumturquoise: "48d1cc",
  29996. mediumvioletred: "c71585",
  29997. midnightblue: "191970",
  29998. mintcream: "f5fffa",
  29999. mistyrose: "ffe4e1",
  30000. moccasin: "ffe4b5",
  30001. navajowhite: "ffdead",
  30002. navy: "000080",
  30003. oldlace: "fdf5e6",
  30004. olive: "808000",
  30005. olivedrab: "6b8e23",
  30006. orange: "ffa500",
  30007. orangered: "ff4500",
  30008. orchid: "da70d6",
  30009. palegoldenrod: "eee8aa",
  30010. palegreen: "98fb98",
  30011. paleturquoise: "afeeee",
  30012. palevioletred: "db7093",
  30013. papayawhip: "ffefd5",
  30014. peachpuff: "ffdab9",
  30015. peru: "cd853f",
  30016. pink: "ffc0cb",
  30017. plum: "dda0dd",
  30018. powderblue: "b0e0e6",
  30019. purple: "800080",
  30020. rebeccapurple: "663399",
  30021. red: "f00",
  30022. rosybrown: "bc8f8f",
  30023. royalblue: "4169e1",
  30024. saddlebrown: "8b4513",
  30025. salmon: "fa8072",
  30026. sandybrown: "f4a460",
  30027. seagreen: "2e8b57",
  30028. seashell: "fff5ee",
  30029. sienna: "a0522d",
  30030. silver: "c0c0c0",
  30031. skyblue: "87ceeb",
  30032. slateblue: "6a5acd",
  30033. slategray: "708090",
  30034. slategrey: "708090",
  30035. snow: "fffafa",
  30036. springgreen: "00ff7f",
  30037. steelblue: "4682b4",
  30038. tan: "d2b48c",
  30039. teal: "008080",
  30040. thistle: "d8bfd8",
  30041. tomato: "ff6347",
  30042. turquoise: "40e0d0",
  30043. violet: "ee82ee",
  30044. wheat: "f5deb3",
  30045. white: "fff",
  30046. whitesmoke: "f5f5f5",
  30047. yellow: "ff0",
  30048. yellowgreen: "9acd32"
  30049. };
  30050. // Make it easy to access colors via `hexNames[hex]`
  30051. var hexNames = tinycolor.hexNames = flip(names);
  30052. // Utilities
  30053. // ---------
  30054. // `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }`
  30055. function flip(o) {
  30056. var flipped = { };
  30057. for (var i in o) {
  30058. if (o.hasOwnProperty(i)) {
  30059. flipped[o[i]] = i;
  30060. }
  30061. }
  30062. return flipped;
  30063. }
  30064. // Return a valid alpha value [0,1] with all invalid values being set to 1
  30065. function boundAlpha(a) {
  30066. a = parseFloat(a);
  30067. if (isNaN(a) || a < 0 || a > 1) {
  30068. a = 1;
  30069. }
  30070. return a;
  30071. }
  30072. // Take input from [0, n] and return it as [0, 1]
  30073. function bound01(n, max) {
  30074. if (isOnePointZero(n)) { n = "100%"; }
  30075. var processPercent = isPercentage(n);
  30076. n = mathMin(max, mathMax(0, parseFloat(n)));
  30077. // Automatically convert percentage into number
  30078. if (processPercent) {
  30079. n = parseInt(n * max, 10) / 100;
  30080. }
  30081. // Handle floating point rounding errors
  30082. if ((Math.abs(n - max) < 0.000001)) {
  30083. return 1;
  30084. }
  30085. // Convert into [0, 1] range if it isn't already
  30086. return (n % max) / parseFloat(max);
  30087. }
  30088. // Force a number between 0 and 1
  30089. function clamp01(val) {
  30090. return mathMin(1, mathMax(0, val));
  30091. }
  30092. // Parse a base-16 hex value into a base-10 integer
  30093. function parseIntFromHex(val) {
  30094. return parseInt(val, 16);
  30095. }
  30096. // Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1
  30097. // <http://stackoverflow.com/questions/7422072/javascript-how-to-detect-number-as-a-decimal-including-1-0>
  30098. function isOnePointZero(n) {
  30099. return typeof n == "string" && n.indexOf('.') != -1 && parseFloat(n) === 1;
  30100. }
  30101. // Check to see if string passed in is a percentage
  30102. function isPercentage(n) {
  30103. return typeof n === "string" && n.indexOf('%') != -1;
  30104. }
  30105. // Force a hex value to have 2 characters
  30106. function pad2(c) {
  30107. return c.length == 1 ? '0' + c : '' + c;
  30108. }
  30109. // Replace a decimal with it's percentage value
  30110. function convertToPercentage(n) {
  30111. if (n <= 1) {
  30112. n = (n * 100) + "%";
  30113. }
  30114. return n;
  30115. }
  30116. // Converts a decimal to a hex value
  30117. function convertDecimalToHex(d) {
  30118. return Math.round(parseFloat(d) * 255).toString(16);
  30119. }
  30120. // Converts a hex value to a decimal
  30121. function convertHexToDecimal(h) {
  30122. return (parseIntFromHex(h) / 255);
  30123. }
  30124. var matchers = (function() {
  30125. // <http://www.w3.org/TR/css3-values/#integers>
  30126. var CSS_INTEGER = "[-\\+]?\\d+%?";
  30127. // <http://www.w3.org/TR/css3-values/#number-value>
  30128. var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?";
  30129. // Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome.
  30130. var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")";
  30131. // Actual matching.
  30132. // Parentheses and commas are optional, but not required.
  30133. // Whitespace can take the place of commas or opening paren
  30134. var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
  30135. var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
  30136. return {
  30137. CSS_UNIT: new RegExp(CSS_UNIT),
  30138. rgb: new RegExp("rgb" + PERMISSIVE_MATCH3),
  30139. rgba: new RegExp("rgba" + PERMISSIVE_MATCH4),
  30140. hsl: new RegExp("hsl" + PERMISSIVE_MATCH3),
  30141. hsla: new RegExp("hsla" + PERMISSIVE_MATCH4),
  30142. hsv: new RegExp("hsv" + PERMISSIVE_MATCH3),
  30143. hsva: new RegExp("hsva" + PERMISSIVE_MATCH4),
  30144. hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
  30145. hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,
  30146. hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
  30147. hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/
  30148. };
  30149. })();
  30150. // `isValidCSSUnit`
  30151. // Take in a single string / number and check to see if it looks like a CSS unit
  30152. // (see `matchers` above for definition).
  30153. function isValidCSSUnit(color) {
  30154. return !!matchers.CSS_UNIT.exec(color);
  30155. }
  30156. // `stringInputToObject`
  30157. // Permissive string parsing. Take in a number of formats, and output an object
  30158. // based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}`
  30159. function stringInputToObject(color) {
  30160. color = color.replace(trimLeft,'').replace(trimRight, '').toLowerCase();
  30161. var named = false;
  30162. if (names[color]) {
  30163. color = names[color];
  30164. named = true;
  30165. }
  30166. else if (color == 'transparent') {
  30167. return { r: 0, g: 0, b: 0, a: 0, format: "name" };
  30168. }
  30169. // Try to match string input using regular expressions.
  30170. // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360]
  30171. // Just return an object and let the conversion functions handle that.
  30172. // This way the result will be the same whether the tinycolor is initialized with string or object.
  30173. var match;
  30174. if ((match = matchers.rgb.exec(color))) {
  30175. return { r: match[1], g: match[2], b: match[3] };
  30176. }
  30177. if ((match = matchers.rgba.exec(color))) {
  30178. return { r: match[1], g: match[2], b: match[3], a: match[4] };
  30179. }
  30180. if ((match = matchers.hsl.exec(color))) {
  30181. return { h: match[1], s: match[2], l: match[3] };
  30182. }
  30183. if ((match = matchers.hsla.exec(color))) {
  30184. return { h: match[1], s: match[2], l: match[3], a: match[4] };
  30185. }
  30186. if ((match = matchers.hsv.exec(color))) {
  30187. return { h: match[1], s: match[2], v: match[3] };
  30188. }
  30189. if ((match = matchers.hsva.exec(color))) {
  30190. return { h: match[1], s: match[2], v: match[3], a: match[4] };
  30191. }
  30192. if ((match = matchers.hex8.exec(color))) {
  30193. return {
  30194. r: parseIntFromHex(match[1]),
  30195. g: parseIntFromHex(match[2]),
  30196. b: parseIntFromHex(match[3]),
  30197. a: convertHexToDecimal(match[4]),
  30198. format: named ? "name" : "hex8"
  30199. };
  30200. }
  30201. if ((match = matchers.hex6.exec(color))) {
  30202. return {
  30203. r: parseIntFromHex(match[1]),
  30204. g: parseIntFromHex(match[2]),
  30205. b: parseIntFromHex(match[3]),
  30206. format: named ? "name" : "hex"
  30207. };
  30208. }
  30209. if ((match = matchers.hex4.exec(color))) {
  30210. return {
  30211. r: parseIntFromHex(match[1] + '' + match[1]),
  30212. g: parseIntFromHex(match[2] + '' + match[2]),
  30213. b: parseIntFromHex(match[3] + '' + match[3]),
  30214. a: convertHexToDecimal(match[4] + '' + match[4]),
  30215. format: named ? "name" : "hex8"
  30216. };
  30217. }
  30218. if ((match = matchers.hex3.exec(color))) {
  30219. return {
  30220. r: parseIntFromHex(match[1] + '' + match[1]),
  30221. g: parseIntFromHex(match[2] + '' + match[2]),
  30222. b: parseIntFromHex(match[3] + '' + match[3]),
  30223. format: named ? "name" : "hex"
  30224. };
  30225. }
  30226. return false;
  30227. }
  30228. function validateWCAG2Parms(parms) {
  30229. // return valid WCAG2 parms for isReadable.
  30230. // If input parms are invalid, return {"level":"AA", "size":"small"}
  30231. var level, size;
  30232. parms = parms || {"level":"AA", "size":"small"};
  30233. level = (parms.level || "AA").toUpperCase();
  30234. size = (parms.size || "small").toLowerCase();
  30235. if (level !== "AA" && level !== "AAA") {
  30236. level = "AA";
  30237. }
  30238. if (size !== "small" && size !== "large") {
  30239. size = "small";
  30240. }
  30241. return {"level":level, "size":size};
  30242. }
  30243. // Node: Export function
  30244. if (module.exports) {
  30245. module.exports = tinycolor;
  30246. }
  30247. // AMD/requirejs: Define the module
  30248. else {
  30249. window.tinycolor = tinycolor;
  30250. }
  30251. })(Math);
  30252. }(tinycolor));
  30253. var tinyColor = tinycolor.exports;
  30254. function ownKeys(object, enumerableOnly) {
  30255. var keys = Object.keys(object);
  30256. if (Object.getOwnPropertySymbols) {
  30257. var symbols = Object.getOwnPropertySymbols(object);
  30258. if (enumerableOnly) {
  30259. symbols = symbols.filter(function (sym) {
  30260. return Object.getOwnPropertyDescriptor(object, sym).enumerable;
  30261. });
  30262. }
  30263. keys.push.apply(keys, symbols);
  30264. }
  30265. return keys;
  30266. }
  30267. function _objectSpread2(target) {
  30268. for (var i = 1; i < arguments.length; i++) {
  30269. var source = arguments[i] != null ? arguments[i] : {};
  30270. if (i % 2) {
  30271. ownKeys(Object(source), true).forEach(function (key) {
  30272. _defineProperty$1(target, key, source[key]);
  30273. });
  30274. } else if (Object.getOwnPropertyDescriptors) {
  30275. Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
  30276. } else {
  30277. ownKeys(Object(source)).forEach(function (key) {
  30278. Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
  30279. });
  30280. }
  30281. }
  30282. return target;
  30283. }
  30284. function _typeof(obj) {
  30285. "@babel/helpers - typeof";
  30286. if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
  30287. _typeof = function (obj) {
  30288. return typeof obj;
  30289. };
  30290. } else {
  30291. _typeof = function (obj) {
  30292. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  30293. };
  30294. }
  30295. return _typeof(obj);
  30296. }
  30297. function _classCallCheck(instance, Constructor) {
  30298. if (!(instance instanceof Constructor)) {
  30299. throw new TypeError("Cannot call a class as a function");
  30300. }
  30301. }
  30302. function _defineProperty$1(obj, key, value) {
  30303. if (key in obj) {
  30304. Object.defineProperty(obj, key, {
  30305. value: value,
  30306. enumerable: true,
  30307. configurable: true,
  30308. writable: true
  30309. });
  30310. } else {
  30311. obj[key] = value;
  30312. }
  30313. return obj;
  30314. }
  30315. function _inherits(subClass, superClass) {
  30316. if (typeof superClass !== "function" && superClass !== null) {
  30317. throw new TypeError("Super expression must either be null or a function");
  30318. }
  30319. subClass.prototype = Object.create(superClass && superClass.prototype, {
  30320. constructor: {
  30321. value: subClass,
  30322. writable: true,
  30323. configurable: true
  30324. }
  30325. });
  30326. if (superClass) _setPrototypeOf$1(subClass, superClass);
  30327. }
  30328. function _getPrototypeOf$1(o) {
  30329. _getPrototypeOf$1 = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
  30330. return o.__proto__ || Object.getPrototypeOf(o);
  30331. };
  30332. return _getPrototypeOf$1(o);
  30333. }
  30334. function _setPrototypeOf$1(o, p) {
  30335. _setPrototypeOf$1 = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
  30336. o.__proto__ = p;
  30337. return o;
  30338. };
  30339. return _setPrototypeOf$1(o, p);
  30340. }
  30341. function _isNativeReflectConstruct$1() {
  30342. if (typeof Reflect === "undefined" || !Reflect.construct) return false;
  30343. if (Reflect.construct.sham) return false;
  30344. if (typeof Proxy === "function") return true;
  30345. try {
  30346. Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
  30347. return true;
  30348. } catch (e) {
  30349. return false;
  30350. }
  30351. }
  30352. function _construct$1(Parent, args, Class) {
  30353. if (_isNativeReflectConstruct$1()) {
  30354. _construct$1 = Reflect.construct;
  30355. } else {
  30356. _construct$1 = function _construct(Parent, args, Class) {
  30357. var a = [null];
  30358. a.push.apply(a, args);
  30359. var Constructor = Function.bind.apply(Parent, a);
  30360. var instance = new Constructor();
  30361. if (Class) _setPrototypeOf$1(instance, Class.prototype);
  30362. return instance;
  30363. };
  30364. }
  30365. return _construct$1.apply(null, arguments);
  30366. }
  30367. function _objectWithoutPropertiesLoose(source, excluded) {
  30368. if (source == null) return {};
  30369. var target = {};
  30370. var sourceKeys = Object.keys(source);
  30371. var key, i;
  30372. for (i = 0; i < sourceKeys.length; i++) {
  30373. key = sourceKeys[i];
  30374. if (excluded.indexOf(key) >= 0) continue;
  30375. target[key] = source[key];
  30376. }
  30377. return target;
  30378. }
  30379. function _objectWithoutProperties(source, excluded) {
  30380. if (source == null) return {};
  30381. var target = _objectWithoutPropertiesLoose(source, excluded);
  30382. var key, i;
  30383. if (Object.getOwnPropertySymbols) {
  30384. var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
  30385. for (i = 0; i < sourceSymbolKeys.length; i++) {
  30386. key = sourceSymbolKeys[i];
  30387. if (excluded.indexOf(key) >= 0) continue;
  30388. if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
  30389. target[key] = source[key];
  30390. }
  30391. }
  30392. return target;
  30393. }
  30394. function _assertThisInitialized$1(self) {
  30395. if (self === void 0) {
  30396. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  30397. }
  30398. return self;
  30399. }
  30400. function _possibleConstructorReturn(self, call) {
  30401. if (call && (typeof call === "object" || typeof call === "function")) {
  30402. return call;
  30403. }
  30404. return _assertThisInitialized$1(self);
  30405. }
  30406. function _createSuper(Derived) {
  30407. var hasNativeReflectConstruct = _isNativeReflectConstruct$1();
  30408. return function _createSuperInternal() {
  30409. var Super = _getPrototypeOf$1(Derived),
  30410. result;
  30411. if (hasNativeReflectConstruct) {
  30412. var NewTarget = _getPrototypeOf$1(this).constructor;
  30413. result = Reflect.construct(Super, arguments, NewTarget);
  30414. } else {
  30415. result = Super.apply(this, arguments);
  30416. }
  30417. return _possibleConstructorReturn(this, result);
  30418. };
  30419. }
  30420. function _slicedToArray$1(arr, i) {
  30421. return _arrayWithHoles$1(arr) || _iterableToArrayLimit$1(arr, i) || _unsupportedIterableToArray$1(arr, i) || _nonIterableRest$1();
  30422. }
  30423. function _toConsumableArray$1(arr) {
  30424. return _arrayWithoutHoles$1(arr) || _iterableToArray$1(arr) || _unsupportedIterableToArray$1(arr) || _nonIterableSpread$1();
  30425. }
  30426. function _arrayWithoutHoles$1(arr) {
  30427. if (Array.isArray(arr)) return _arrayLikeToArray$1(arr);
  30428. }
  30429. function _arrayWithHoles$1(arr) {
  30430. if (Array.isArray(arr)) return arr;
  30431. }
  30432. function _iterableToArray$1(iter) {
  30433. if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
  30434. }
  30435. function _iterableToArrayLimit$1(arr, i) {
  30436. var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
  30437. if (_i == null) return;
  30438. var _arr = [];
  30439. var _n = true;
  30440. var _d = false;
  30441. var _s, _e;
  30442. try {
  30443. for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
  30444. _arr.push(_s.value);
  30445. if (i && _arr.length === i) break;
  30446. }
  30447. } catch (err) {
  30448. _d = true;
  30449. _e = err;
  30450. } finally {
  30451. try {
  30452. if (!_n && _i["return"] != null) _i["return"]();
  30453. } finally {
  30454. if (_d) throw _e;
  30455. }
  30456. }
  30457. return _arr;
  30458. }
  30459. function _unsupportedIterableToArray$1(o, minLen) {
  30460. if (!o) return;
  30461. if (typeof o === "string") return _arrayLikeToArray$1(o, minLen);
  30462. var n = Object.prototype.toString.call(o).slice(8, -1);
  30463. if (n === "Object" && o.constructor) n = o.constructor.name;
  30464. if (n === "Map" || n === "Set") return Array.from(o);
  30465. if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$1(o, minLen);
  30466. }
  30467. function _arrayLikeToArray$1(arr, len) {
  30468. if (len == null || len > arr.length) len = arr.length;
  30469. for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  30470. return arr2;
  30471. }
  30472. function _nonIterableSpread$1() {
  30473. throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  30474. }
  30475. function _nonIterableRest$1() {
  30476. throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  30477. }
  30478. var materialDispose = function materialDispose(material) {
  30479. if (material instanceof Array) {
  30480. material.forEach(materialDispose);
  30481. } else {
  30482. if (material.map) {
  30483. material.map.dispose();
  30484. }
  30485. material.dispose();
  30486. }
  30487. };
  30488. var deallocate = function deallocate(obj) {
  30489. if (obj.geometry) {
  30490. obj.geometry.dispose();
  30491. }
  30492. if (obj.material) {
  30493. materialDispose(obj.material);
  30494. }
  30495. if (obj.texture) {
  30496. obj.texture.dispose();
  30497. }
  30498. if (obj.children) {
  30499. obj.children.forEach(deallocate);
  30500. }
  30501. };
  30502. var emptyObject = function emptyObject(obj) {
  30503. while (obj.children.length) {
  30504. var childObj = obj.children[0];
  30505. obj.remove(childObj);
  30506. deallocate(childObj);
  30507. }
  30508. };
  30509. var _excluded = ["objFilter"];
  30510. function threeDigest(data, scene) {
  30511. var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  30512. var _ref$objFilter = _ref.objFilter,
  30513. objFilter = _ref$objFilter === void 0 ? function () {
  30514. return true;
  30515. } : _ref$objFilter,
  30516. options = _objectWithoutProperties(_ref, _excluded);
  30517. return viewDigest(data, scene.children.filter(objFilter), function (obj) {
  30518. return scene.add(obj);
  30519. }, function (obj) {
  30520. scene.remove(obj);
  30521. emptyObject(obj);
  30522. }, _objectSpread2({
  30523. objBindAttr: '__threeObj'
  30524. }, options));
  30525. }
  30526. var colorStr2Hex = function colorStr2Hex(str) {
  30527. return isNaN(str) ? parseInt(tinyColor(str).toHex(), 16) : str;
  30528. };
  30529. var colorAlpha = function colorAlpha(str) {
  30530. return isNaN(str) ? tinyColor(str).getAlpha() : 1;
  30531. };
  30532. var autoColorScale = ordinal(schemePaired); // Autoset attribute colorField by colorByAccessor property
  30533. // If an object has already a color, don't set it
  30534. // Objects can be nodes or links
  30535. function autoColorObjects(objects, colorByAccessor, colorField) {
  30536. if (!colorByAccessor || typeof colorField !== 'string') return;
  30537. objects.filter(function (obj) {
  30538. return !obj[colorField];
  30539. }).forEach(function (obj) {
  30540. obj[colorField] = autoColorScale(colorByAccessor(obj));
  30541. });
  30542. }
  30543. function getDagDepths (_ref, idAccessor) {
  30544. var nodes = _ref.nodes,
  30545. links = _ref.links;
  30546. var _ref2 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},
  30547. _ref2$nodeFilter = _ref2.nodeFilter,
  30548. nodeFilter = _ref2$nodeFilter === void 0 ? function () {
  30549. return true;
  30550. } : _ref2$nodeFilter,
  30551. _ref2$onLoopError = _ref2.onLoopError,
  30552. onLoopError = _ref2$onLoopError === void 0 ? function (loopIds) {
  30553. throw "Invalid DAG structure! Found cycle in node path: ".concat(loopIds.join(' -> '), ".");
  30554. } : _ref2$onLoopError;
  30555. // linked graph
  30556. var graph = {};
  30557. nodes.forEach(function (node) {
  30558. return graph[idAccessor(node)] = {
  30559. data: node,
  30560. out: [],
  30561. depth: -1,
  30562. skip: !nodeFilter(node)
  30563. };
  30564. });
  30565. links.forEach(function (_ref3) {
  30566. var source = _ref3.source,
  30567. target = _ref3.target;
  30568. var sourceId = getNodeId(source);
  30569. var targetId = getNodeId(target);
  30570. if (!graph.hasOwnProperty(sourceId)) throw "Missing source node with id: ".concat(sourceId);
  30571. if (!graph.hasOwnProperty(targetId)) throw "Missing target node with id: ".concat(targetId);
  30572. var sourceNode = graph[sourceId];
  30573. var targetNode = graph[targetId];
  30574. sourceNode.out.push(targetNode);
  30575. function getNodeId(node) {
  30576. return _typeof(node) === 'object' ? idAccessor(node) : node;
  30577. }
  30578. });
  30579. var foundLoops = [];
  30580. traverse(Object.values(graph));
  30581. var nodeDepths = Object.assign.apply(Object, [{}].concat(_toConsumableArray$1(Object.entries(graph).filter(function (_ref4) {
  30582. var _ref5 = _slicedToArray$1(_ref4, 2),
  30583. node = _ref5[1];
  30584. return !node.skip;
  30585. }).map(function (_ref6) {
  30586. var _ref7 = _slicedToArray$1(_ref6, 2),
  30587. id = _ref7[0],
  30588. node = _ref7[1];
  30589. return _defineProperty$1({}, id, node.depth);
  30590. }))));
  30591. return nodeDepths;
  30592. function traverse(nodes) {
  30593. var nodeStack = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  30594. var currentDepth = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
  30595. for (var i = 0, l = nodes.length; i < l; i++) {
  30596. var node = nodes[i];
  30597. if (nodeStack.indexOf(node) !== -1) {
  30598. var _ret = function () {
  30599. var loop = [].concat(_toConsumableArray$1(nodeStack.slice(nodeStack.indexOf(node))), [node]).map(function (d) {
  30600. return idAccessor(d.data);
  30601. });
  30602. if (!foundLoops.some(function (foundLoop) {
  30603. return foundLoop.length === loop.length && foundLoop.every(function (id, idx) {
  30604. return id === loop[idx];
  30605. });
  30606. })) {
  30607. foundLoops.push(loop);
  30608. onLoopError(loop);
  30609. }
  30610. return "continue";
  30611. }();
  30612. if (_ret === "continue") continue;
  30613. }
  30614. if (currentDepth > node.depth) {
  30615. // Don't unnecessarily revisit chunks of the graph
  30616. node.depth = currentDepth;
  30617. traverse(node.out, [].concat(_toConsumableArray$1(nodeStack), [node]), currentDepth + (node.skip ? 0 : 1));
  30618. }
  30619. }
  30620. }
  30621. }
  30622. var three$1$1 = window.THREE ? window.THREE // Prefer consumption from global THREE, if exists
  30623. : {
  30624. Group: Group$1,
  30625. Mesh: Mesh,
  30626. MeshLambertMaterial: MeshLambertMaterial,
  30627. Color: Color,
  30628. BufferGeometry: BufferGeometry,
  30629. BufferAttribute: BufferAttribute,
  30630. Matrix4: Matrix4,
  30631. Vector3: Vector3,
  30632. SphereBufferGeometry: SphereGeometry,
  30633. CylinderBufferGeometry: CylinderGeometry,
  30634. TubeBufferGeometry: TubeGeometry,
  30635. ConeBufferGeometry: ConeGeometry,
  30636. Line: Line,
  30637. LineBasicMaterial: LineBasicMaterial,
  30638. QuadraticBezierCurve3: QuadraticBezierCurve3,
  30639. CubicBezierCurve3: CubicBezierCurve3,
  30640. Box3: Box3
  30641. };
  30642. var ngraph = {
  30643. graph: ngraph_graph,
  30644. forcelayout: forcelayout
  30645. };
  30646. var DAG_LEVEL_NODE_RATIO = 2; // support multiple method names for backwards threejs compatibility
  30647. var setAttributeFn = new three$1$1.BufferGeometry().setAttribute ? 'setAttribute' : 'addAttribute';
  30648. var applyMatrix4Fn = new three$1$1.BufferGeometry().applyMatrix4 ? 'applyMatrix4' : 'applyMatrix';
  30649. var ForceGraph = index$2({
  30650. props: {
  30651. jsonUrl: {
  30652. onChange: function onChange(jsonUrl, state) {
  30653. var _this = this;
  30654. if (jsonUrl && !state.fetchingJson) {
  30655. // Load data asynchronously
  30656. state.fetchingJson = true;
  30657. state.onLoading();
  30658. fetch(jsonUrl).then(function (r) {
  30659. return r.json();
  30660. }).then(function (json) {
  30661. state.fetchingJson = false;
  30662. state.onFinishLoading(json);
  30663. _this.graphData(json);
  30664. });
  30665. }
  30666. },
  30667. triggerUpdate: false
  30668. },
  30669. graphData: {
  30670. "default": {
  30671. nodes: [],
  30672. links: []
  30673. },
  30674. onChange: function onChange(graphData, state) {
  30675. state.engineRunning = false; // Pause simulation immediately
  30676. }
  30677. },
  30678. numDimensions: {
  30679. "default": 3,
  30680. onChange: function onChange(numDim, state) {
  30681. var chargeForce = state.d3ForceLayout.force('charge'); // Increase repulsion on 3D mode for improved spatial separation
  30682. if (chargeForce) {
  30683. chargeForce.strength(numDim > 2 ? -60 : -30);
  30684. }
  30685. if (numDim < 3) {
  30686. eraseDimension(state.graphData.nodes, 'z');
  30687. }
  30688. if (numDim < 2) {
  30689. eraseDimension(state.graphData.nodes, 'y');
  30690. }
  30691. function eraseDimension(nodes, dim) {
  30692. nodes.forEach(function (d) {
  30693. delete d[dim]; // position
  30694. delete d["v".concat(dim)]; // velocity
  30695. });
  30696. }
  30697. }
  30698. },
  30699. dagMode: {
  30700. onChange: function onChange(dagMode, state) {
  30701. // td, bu, lr, rl, zin, zout, radialin, radialout
  30702. !dagMode && state.forceEngine === 'd3' && (state.graphData.nodes || []).forEach(function (n) {
  30703. return n.fx = n.fy = n.fz = undefined;
  30704. }); // unfix nodes when disabling dag mode
  30705. }
  30706. },
  30707. dagLevelDistance: {},
  30708. dagNodeFilter: {
  30709. "default": function _default(node) {
  30710. return true;
  30711. }
  30712. },
  30713. onDagError: {
  30714. triggerUpdate: false
  30715. },
  30716. nodeRelSize: {
  30717. "default": 4
  30718. },
  30719. // volume per val unit
  30720. nodeId: {
  30721. "default": 'id'
  30722. },
  30723. nodeVal: {
  30724. "default": 'val'
  30725. },
  30726. nodeResolution: {
  30727. "default": 8
  30728. },
  30729. // how many slice segments in the sphere's circumference
  30730. nodeColor: {
  30731. "default": 'color'
  30732. },
  30733. nodeAutoColorBy: {},
  30734. nodeOpacity: {
  30735. "default": 0.75
  30736. },
  30737. nodeVisibility: {
  30738. "default": true
  30739. },
  30740. nodeThreeObject: {},
  30741. nodeThreeObjectExtend: {
  30742. "default": false
  30743. },
  30744. linkSource: {
  30745. "default": 'source'
  30746. },
  30747. linkTarget: {
  30748. "default": 'target'
  30749. },
  30750. linkVisibility: {
  30751. "default": true
  30752. },
  30753. linkColor: {
  30754. "default": 'color'
  30755. },
  30756. linkAutoColorBy: {},
  30757. linkOpacity: {
  30758. "default": 0.2
  30759. },
  30760. linkWidth: {},
  30761. // Rounded to nearest decimal. For falsy values use dimensionless line with 1px regardless of distance.
  30762. linkResolution: {
  30763. "default": 6
  30764. },
  30765. // how many radial segments in each line tube's geometry
  30766. linkCurvature: {
  30767. "default": 0,
  30768. triggerUpdate: false
  30769. },
  30770. // line curvature radius (0: straight, 1: semi-circle)
  30771. linkCurveRotation: {
  30772. "default": 0,
  30773. triggerUpdate: false
  30774. },
  30775. // line curve rotation along the line axis (0: interection with XY plane, PI: upside down)
  30776. linkMaterial: {},
  30777. linkThreeObject: {},
  30778. linkThreeObjectExtend: {
  30779. "default": false
  30780. },
  30781. linkPositionUpdate: {
  30782. triggerUpdate: false
  30783. },
  30784. // custom function to call for updating the link's position. Signature: (threeObj, { start: { x, y, z}, end: { x, y, z }}, link). If the function returns a truthy value, the regular link position update will not run.
  30785. linkDirectionalArrowLength: {
  30786. "default": 0
  30787. },
  30788. linkDirectionalArrowColor: {},
  30789. linkDirectionalArrowRelPos: {
  30790. "default": 0.5,
  30791. triggerUpdate: false
  30792. },
  30793. // value between 0<>1 indicating the relative pos along the (exposed) line
  30794. linkDirectionalArrowResolution: {
  30795. "default": 8
  30796. },
  30797. // how many slice segments in the arrow's conic circumference
  30798. linkDirectionalParticles: {
  30799. "default": 0
  30800. },
  30801. // animate photons travelling in the link direction
  30802. linkDirectionalParticleSpeed: {
  30803. "default": 0.01,
  30804. triggerUpdate: false
  30805. },
  30806. // in link length ratio per frame
  30807. linkDirectionalParticleWidth: {
  30808. "default": 0.5
  30809. },
  30810. linkDirectionalParticleColor: {},
  30811. linkDirectionalParticleResolution: {
  30812. "default": 4
  30813. },
  30814. // how many slice segments in the particle sphere's circumference
  30815. forceEngine: {
  30816. "default": 'd3'
  30817. },
  30818. // d3 or ngraph
  30819. d3AlphaMin: {
  30820. "default": 0
  30821. },
  30822. d3AlphaDecay: {
  30823. "default": 0.0228,
  30824. triggerUpdate: false,
  30825. onChange: function onChange(alphaDecay, state) {
  30826. state.d3ForceLayout.alphaDecay(alphaDecay);
  30827. }
  30828. },
  30829. d3AlphaTarget: {
  30830. "default": 0,
  30831. triggerUpdate: false,
  30832. onChange: function onChange(alphaTarget, state) {
  30833. state.d3ForceLayout.alphaTarget(alphaTarget);
  30834. }
  30835. },
  30836. d3VelocityDecay: {
  30837. "default": 0.4,
  30838. triggerUpdate: false,
  30839. onChange: function onChange(velocityDecay, state) {
  30840. state.d3ForceLayout.velocityDecay(velocityDecay);
  30841. }
  30842. },
  30843. ngraphPhysics: {
  30844. "default": {
  30845. // defaults from https://github.com/anvaka/ngraph.physics.simulator/blob/master/index.js
  30846. timeStep: 20,
  30847. gravity: -1.2,
  30848. theta: 0.8,
  30849. springLength: 30,
  30850. springCoefficient: 0.0008,
  30851. dragCoefficient: 0.02
  30852. }
  30853. },
  30854. warmupTicks: {
  30855. "default": 0,
  30856. triggerUpdate: false
  30857. },
  30858. // how many times to tick the force engine at init before starting to render
  30859. cooldownTicks: {
  30860. "default": Infinity,
  30861. triggerUpdate: false
  30862. },
  30863. cooldownTime: {
  30864. "default": 15000,
  30865. triggerUpdate: false
  30866. },
  30867. // ms
  30868. onLoading: {
  30869. "default": function _default() {},
  30870. triggerUpdate: false
  30871. },
  30872. onFinishLoading: {
  30873. "default": function _default() {},
  30874. triggerUpdate: false
  30875. },
  30876. onUpdate: {
  30877. "default": function _default() {},
  30878. triggerUpdate: false
  30879. },
  30880. onFinishUpdate: {
  30881. "default": function _default() {},
  30882. triggerUpdate: false
  30883. },
  30884. onEngineTick: {
  30885. "default": function _default() {},
  30886. triggerUpdate: false
  30887. },
  30888. onEngineStop: {
  30889. "default": function _default() {},
  30890. triggerUpdate: false
  30891. }
  30892. },
  30893. methods: {
  30894. refresh: function refresh(state) {
  30895. state._flushObjects = true;
  30896. state._rerender();
  30897. return this;
  30898. },
  30899. // Expose d3 forces for external manipulation
  30900. d3Force: function d3Force(state, forceName, forceFn) {
  30901. if (forceFn === undefined) {
  30902. return state.d3ForceLayout.force(forceName); // Force getter
  30903. }
  30904. state.d3ForceLayout.force(forceName, forceFn); // Force setter
  30905. return this;
  30906. },
  30907. d3ReheatSimulation: function d3ReheatSimulation(state) {
  30908. state.d3ForceLayout.alpha(1);
  30909. this.resetCountdown();
  30910. return this;
  30911. },
  30912. // reset cooldown state
  30913. resetCountdown: function resetCountdown(state) {
  30914. state.cntTicks = 0;
  30915. state.startTickTime = new Date();
  30916. state.engineRunning = true;
  30917. return this;
  30918. },
  30919. tickFrame: function tickFrame(state) {
  30920. var isD3Sim = state.forceEngine !== 'ngraph';
  30921. if (state.engineRunning) {
  30922. layoutTick();
  30923. }
  30924. updateArrows();
  30925. updatePhotons();
  30926. return this; //
  30927. function layoutTick() {
  30928. if (++state.cntTicks > state.cooldownTicks || new Date() - state.startTickTime > state.cooldownTime || isD3Sim && state.d3AlphaMin > 0 && state.d3ForceLayout.alpha() < state.d3AlphaMin) {
  30929. state.engineRunning = false; // Stop ticking graph
  30930. state.onEngineStop();
  30931. } else {
  30932. state.layout[isD3Sim ? 'tick' : 'step'](); // Tick it
  30933. state.onEngineTick();
  30934. } // Update nodes position
  30935. state.graphData.nodes.forEach(function (node) {
  30936. var obj = node.__threeObj;
  30937. if (!obj) return;
  30938. var pos = isD3Sim ? node : state.layout.getNodePosition(node[state.nodeId]);
  30939. obj.position.x = pos.x;
  30940. obj.position.y = pos.y || 0;
  30941. obj.position.z = pos.z || 0;
  30942. }); // Update links position
  30943. var linkWidthAccessor = index$1(state.linkWidth);
  30944. var linkCurvatureAccessor = index$1(state.linkCurvature);
  30945. var linkCurveRotationAccessor = index$1(state.linkCurveRotation);
  30946. var linkThreeObjectExtendAccessor = index$1(state.linkThreeObjectExtend);
  30947. state.graphData.links.forEach(function (link) {
  30948. var lineObj = link.__lineObj;
  30949. if (!lineObj) return;
  30950. var pos = isD3Sim ? link : state.layout.getLinkPosition(state.layout.graph.getLink(link.source, link.target).id);
  30951. var start = pos[isD3Sim ? 'source' : 'from'];
  30952. var end = pos[isD3Sim ? 'target' : 'to'];
  30953. if (!start || !end || !start.hasOwnProperty('x') || !end.hasOwnProperty('x')) return; // skip invalid link
  30954. calcLinkCurve(link); // calculate link curve for all links, including custom replaced, so it can be used in directional functionality
  30955. var extendedObj = linkThreeObjectExtendAccessor(link);
  30956. if (state.linkPositionUpdate && state.linkPositionUpdate(extendedObj ? lineObj.children[1] : lineObj, // pass child custom object if extending the default
  30957. {
  30958. start: {
  30959. x: start.x,
  30960. y: start.y,
  30961. z: start.z
  30962. },
  30963. end: {
  30964. x: end.x,
  30965. y: end.y,
  30966. z: end.z
  30967. }
  30968. }, link) && !extendedObj) {
  30969. // exit if successfully custom updated position of non-extended obj
  30970. return;
  30971. }
  30972. var curveResolution = 30; // # line segments
  30973. var curve = link.__curve; // select default line obj if it's an extended group
  30974. var line = lineObj.children.length ? lineObj.children[0] : lineObj;
  30975. if (line.type === 'Line') {
  30976. // Update line geometry
  30977. if (!curve) {
  30978. // straight line
  30979. var linePos = line.geometry.getAttribute('position');
  30980. if (!linePos || !linePos.array || linePos.array.length !== 6) {
  30981. line.geometry[setAttributeFn]('position', linePos = new three$1$1.BufferAttribute(new Float32Array(2 * 3), 3));
  30982. }
  30983. linePos.array[0] = start.x;
  30984. linePos.array[1] = start.y || 0;
  30985. linePos.array[2] = start.z || 0;
  30986. linePos.array[3] = end.x;
  30987. linePos.array[4] = end.y || 0;
  30988. linePos.array[5] = end.z || 0;
  30989. linePos.needsUpdate = true;
  30990. } else {
  30991. // bezier curve line
  30992. line.geometry.setFromPoints(curve.getPoints(curveResolution));
  30993. }
  30994. line.geometry.computeBoundingSphere();
  30995. } else if (line.type === 'Mesh') {
  30996. // Update cylinder geometry
  30997. if (!curve) {
  30998. // straight tube
  30999. if (!line.geometry.type.match(/^Cylinder(Buffer)?Geometry$/)) {
  31000. var linkWidth = Math.ceil(linkWidthAccessor(link) * 10) / 10;
  31001. var r = linkWidth / 2;
  31002. var geometry = new three$1$1.CylinderBufferGeometry(r, r, 1, state.linkResolution, 1, false);
  31003. geometry[applyMatrix4Fn](new three$1$1.Matrix4().makeTranslation(0, 1 / 2, 0));
  31004. geometry[applyMatrix4Fn](new three$1$1.Matrix4().makeRotationX(Math.PI / 2));
  31005. line.geometry.dispose();
  31006. line.geometry = geometry;
  31007. }
  31008. var vStart = new three$1$1.Vector3(start.x, start.y || 0, start.z || 0);
  31009. var vEnd = new three$1$1.Vector3(end.x, end.y || 0, end.z || 0);
  31010. var distance = vStart.distanceTo(vEnd);
  31011. line.position.x = vStart.x;
  31012. line.position.y = vStart.y;
  31013. line.position.z = vStart.z;
  31014. line.scale.z = distance;
  31015. line.parent.localToWorld(vEnd); // lookAt requires world coords
  31016. line.lookAt(vEnd);
  31017. } else {
  31018. // curved tube
  31019. if (!line.geometry.type.match(/^Tube(Buffer)?Geometry$/)) {
  31020. // reset object positioning
  31021. line.position.set(0, 0, 0);
  31022. line.rotation.set(0, 0, 0);
  31023. line.scale.set(1, 1, 1);
  31024. }
  31025. var _linkWidth = Math.ceil(linkWidthAccessor(link) * 10) / 10;
  31026. var _r = _linkWidth / 2;
  31027. var _geometry = new three$1$1.TubeBufferGeometry(curve, curveResolution, _r, state.linkResolution, false);
  31028. line.geometry.dispose();
  31029. line.geometry = _geometry;
  31030. }
  31031. }
  31032. }); //
  31033. function calcLinkCurve(link) {
  31034. var pos = isD3Sim ? link : state.layout.getLinkPosition(state.layout.graph.getLink(link.source, link.target).id);
  31035. var start = pos[isD3Sim ? 'source' : 'from'];
  31036. var end = pos[isD3Sim ? 'target' : 'to'];
  31037. if (!start || !end || !start.hasOwnProperty('x') || !end.hasOwnProperty('x')) return; // skip invalid link
  31038. var curvature = linkCurvatureAccessor(link);
  31039. if (!curvature) {
  31040. link.__curve = null; // Straight line
  31041. } else {
  31042. // bezier curve line (only for line types)
  31043. var vStart = new three$1$1.Vector3(start.x, start.y || 0, start.z || 0);
  31044. var vEnd = new three$1$1.Vector3(end.x, end.y || 0, end.z || 0);
  31045. var l = vStart.distanceTo(vEnd); // line length
  31046. var curve;
  31047. var curveRotation = linkCurveRotationAccessor(link);
  31048. if (l > 0) {
  31049. var dx = end.x - start.x;
  31050. var dy = end.y - start.y || 0;
  31051. var vLine = new three$1$1.Vector3().subVectors(vEnd, vStart);
  31052. var cp = vLine.clone().multiplyScalar(curvature).cross(dx !== 0 || dy !== 0 ? new three$1$1.Vector3(0, 0, 1) : new three$1$1.Vector3(0, 1, 0)) // avoid cross-product of parallel vectors (prefer Z, fallback to Y)
  31053. .applyAxisAngle(vLine.normalize(), curveRotation) // rotate along line axis according to linkCurveRotation
  31054. .add(new three$1$1.Vector3().addVectors(vStart, vEnd).divideScalar(2));
  31055. curve = new three$1$1.QuadraticBezierCurve3(vStart, cp, vEnd);
  31056. } else {
  31057. // Same point, draw a loop
  31058. var d = curvature * 70;
  31059. var endAngle = -curveRotation; // Rotate clockwise (from Z angle perspective)
  31060. var startAngle = endAngle + Math.PI / 2;
  31061. curve = new three$1$1.CubicBezierCurve3(vStart, new three$1$1.Vector3(d * Math.cos(startAngle), d * Math.sin(startAngle), 0).add(vStart), new three$1$1.Vector3(d * Math.cos(endAngle), d * Math.sin(endAngle), 0).add(vStart), vEnd);
  31062. }
  31063. link.__curve = curve;
  31064. }
  31065. }
  31066. }
  31067. function updateArrows() {
  31068. // update link arrow position
  31069. var arrowRelPosAccessor = index$1(state.linkDirectionalArrowRelPos);
  31070. var arrowLengthAccessor = index$1(state.linkDirectionalArrowLength);
  31071. var nodeValAccessor = index$1(state.nodeVal);
  31072. state.graphData.links.forEach(function (link) {
  31073. var arrowObj = link.__arrowObj;
  31074. if (!arrowObj) return;
  31075. var pos = isD3Sim ? link : state.layout.getLinkPosition(state.layout.graph.getLink(link.source, link.target).id);
  31076. var start = pos[isD3Sim ? 'source' : 'from'];
  31077. var end = pos[isD3Sim ? 'target' : 'to'];
  31078. if (!start || !end || !start.hasOwnProperty('x') || !end.hasOwnProperty('x')) return; // skip invalid link
  31079. var startR = Math.sqrt(Math.max(0, nodeValAccessor(start) || 1)) * state.nodeRelSize;
  31080. var endR = Math.sqrt(Math.max(0, nodeValAccessor(end) || 1)) * state.nodeRelSize;
  31081. var arrowLength = arrowLengthAccessor(link);
  31082. var arrowRelPos = arrowRelPosAccessor(link);
  31083. var getPosAlongLine = link.__curve ? function (t) {
  31084. return link.__curve.getPoint(t);
  31085. } // interpolate along bezier curve
  31086. : function (t) {
  31087. // straight line: interpolate linearly
  31088. var iplt = function iplt(dim, start, end, t) {
  31089. return start[dim] + (end[dim] - start[dim]) * t || 0;
  31090. };
  31091. return {
  31092. x: iplt('x', start, end, t),
  31093. y: iplt('y', start, end, t),
  31094. z: iplt('z', start, end, t)
  31095. };
  31096. };
  31097. var lineLen = link.__curve ? link.__curve.getLength() : Math.sqrt(['x', 'y', 'z'].map(function (dim) {
  31098. return Math.pow((end[dim] || 0) - (start[dim] || 0), 2);
  31099. }).reduce(function (acc, v) {
  31100. return acc + v;
  31101. }, 0));
  31102. var posAlongLine = startR + arrowLength + (lineLen - startR - endR - arrowLength) * arrowRelPos;
  31103. var arrowHead = getPosAlongLine(posAlongLine / lineLen);
  31104. var arrowTail = getPosAlongLine((posAlongLine - arrowLength) / lineLen);
  31105. ['x', 'y', 'z'].forEach(function (dim) {
  31106. return arrowObj.position[dim] = arrowTail[dim];
  31107. });
  31108. var headVec = _construct$1(three$1$1.Vector3, _toConsumableArray$1(['x', 'y', 'z'].map(function (c) {
  31109. return arrowHead[c];
  31110. })));
  31111. arrowObj.parent.localToWorld(headVec); // lookAt requires world coords
  31112. arrowObj.lookAt(headVec);
  31113. });
  31114. }
  31115. function updatePhotons() {
  31116. // update link particle positions
  31117. var particleSpeedAccessor = index$1(state.linkDirectionalParticleSpeed);
  31118. state.graphData.links.forEach(function (link) {
  31119. var cyclePhotons = link.__photonsObj && link.__photonsObj.children;
  31120. var singleHopPhotons = link.__singleHopPhotonsObj && link.__singleHopPhotonsObj.children;
  31121. if ((!singleHopPhotons || !singleHopPhotons.length) && (!cyclePhotons || !cyclePhotons.length)) return;
  31122. var pos = isD3Sim ? link : state.layout.getLinkPosition(state.layout.graph.getLink(link.source, link.target).id);
  31123. var start = pos[isD3Sim ? 'source' : 'from'];
  31124. var end = pos[isD3Sim ? 'target' : 'to'];
  31125. if (!start || !end || !start.hasOwnProperty('x') || !end.hasOwnProperty('x')) return; // skip invalid link
  31126. var particleSpeed = particleSpeedAccessor(link);
  31127. var getPhotonPos = link.__curve ? function (t) {
  31128. return link.__curve.getPoint(t);
  31129. } // interpolate along bezier curve
  31130. : function (t) {
  31131. // straight line: interpolate linearly
  31132. var iplt = function iplt(dim, start, end, t) {
  31133. return start[dim] + (end[dim] - start[dim]) * t || 0;
  31134. };
  31135. return {
  31136. x: iplt('x', start, end, t),
  31137. y: iplt('y', start, end, t),
  31138. z: iplt('z', start, end, t)
  31139. };
  31140. };
  31141. var photons = [].concat(_toConsumableArray$1(cyclePhotons || []), _toConsumableArray$1(singleHopPhotons || []));
  31142. photons.forEach(function (photon, idx) {
  31143. var singleHop = photon.parent.__linkThreeObjType === 'singleHopPhotons';
  31144. if (!photon.hasOwnProperty('__progressRatio')) {
  31145. photon.__progressRatio = singleHop ? 0 : idx / cyclePhotons.length;
  31146. }
  31147. photon.__progressRatio += particleSpeed;
  31148. if (photon.__progressRatio >= 1) {
  31149. if (!singleHop) {
  31150. photon.__progressRatio = photon.__progressRatio % 1;
  31151. } else {
  31152. // remove particle
  31153. photon.parent.remove(photon);
  31154. emptyObject(photon);
  31155. return;
  31156. }
  31157. }
  31158. var photonPosRatio = photon.__progressRatio;
  31159. var pos = getPhotonPos(photonPosRatio);
  31160. ['x', 'y', 'z'].forEach(function (dim) {
  31161. return photon.position[dim] = pos[dim];
  31162. });
  31163. });
  31164. });
  31165. }
  31166. },
  31167. emitParticle: function emitParticle(state, link) {
  31168. if (link) {
  31169. if (!link.__singleHopPhotonsObj) {
  31170. var obj = new three$1$1.Group();
  31171. obj.__linkThreeObjType = 'singleHopPhotons';
  31172. link.__singleHopPhotonsObj = obj;
  31173. state.graphScene.add(obj);
  31174. }
  31175. var particleWidthAccessor = index$1(state.linkDirectionalParticleWidth);
  31176. var photonR = Math.ceil(particleWidthAccessor(link) * 10) / 10 / 2;
  31177. var numSegments = state.linkDirectionalParticleResolution;
  31178. var particleGeometry = new three$1$1.SphereBufferGeometry(photonR, numSegments, numSegments);
  31179. var linkColorAccessor = index$1(state.linkColor);
  31180. var particleColorAccessor = index$1(state.linkDirectionalParticleColor);
  31181. var photonColor = particleColorAccessor(link) || linkColorAccessor(link) || '#f0f0f0';
  31182. var materialColor = new three$1$1.Color(colorStr2Hex(photonColor));
  31183. var opacity = state.linkOpacity * 3;
  31184. var particleMaterial = new three$1$1.MeshLambertMaterial({
  31185. color: materialColor,
  31186. transparent: true,
  31187. opacity: opacity
  31188. }); // add a single hop particle
  31189. link.__singleHopPhotonsObj.add(new three$1$1.Mesh(particleGeometry, particleMaterial));
  31190. }
  31191. return this;
  31192. },
  31193. getGraphBbox: function getGraphBbox(state) {
  31194. var nodeFilter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {
  31195. return true;
  31196. };
  31197. if (!state.initialised) return null; // recursively collect all nested geometries bboxes
  31198. var bboxes = function getBboxes(obj) {
  31199. var bboxes = [];
  31200. if (obj.geometry) {
  31201. obj.geometry.computeBoundingBox();
  31202. var box = new three$1$1.Box3();
  31203. box.copy(obj.geometry.boundingBox).applyMatrix4(obj.matrixWorld);
  31204. bboxes.push(box);
  31205. }
  31206. return bboxes.concat.apply(bboxes, _toConsumableArray$1((obj.children || []).filter(function (obj) {
  31207. return !obj.hasOwnProperty('__graphObjType') || obj.__graphObjType === 'node' && nodeFilter(obj.__data);
  31208. } // exclude filtered out nodes
  31209. ).map(getBboxes)));
  31210. }(state.graphScene);
  31211. if (!bboxes.length) return null; // extract global x,y,z min/max
  31212. return Object.assign.apply(Object, _toConsumableArray$1(['x', 'y', 'z'].map(function (c) {
  31213. return _defineProperty$1({}, c, [min(bboxes, function (bb) {
  31214. return bb.min[c];
  31215. }), max(bboxes, function (bb) {
  31216. return bb.max[c];
  31217. })]);
  31218. })));
  31219. }
  31220. },
  31221. stateInit: function stateInit() {
  31222. return {
  31223. d3ForceLayout: forceSimulation().force('link', forceLink()).force('charge', forceManyBody()).force('center', forceCenter()).force('dagRadial', null).stop(),
  31224. engineRunning: false
  31225. };
  31226. },
  31227. init: function init(threeObj, state) {
  31228. // Main three object to manipulate
  31229. state.graphScene = threeObj;
  31230. },
  31231. update: function update(state, changedProps) {
  31232. var hasAnyPropChanged = function hasAnyPropChanged(propList) {
  31233. return propList.some(function (p) {
  31234. return changedProps.hasOwnProperty(p);
  31235. });
  31236. };
  31237. state.engineRunning = false; // pause simulation
  31238. state.onUpdate();
  31239. if (state.nodeAutoColorBy !== null && hasAnyPropChanged(['nodeAutoColorBy', 'graphData', 'nodeColor'])) {
  31240. // Auto add color to uncolored nodes
  31241. autoColorObjects(state.graphData.nodes, index$1(state.nodeAutoColorBy), state.nodeColor);
  31242. }
  31243. if (state.linkAutoColorBy !== null && hasAnyPropChanged(['linkAutoColorBy', 'graphData', 'linkColor'])) {
  31244. // Auto add color to uncolored links
  31245. autoColorObjects(state.graphData.links, index$1(state.linkAutoColorBy), state.linkColor);
  31246. } // Digest nodes WebGL objects
  31247. if (state._flushObjects || hasAnyPropChanged(['graphData', 'nodeThreeObject', 'nodeThreeObjectExtend', 'nodeVal', 'nodeColor', 'nodeVisibility', 'nodeRelSize', 'nodeResolution', 'nodeOpacity'])) {
  31248. var customObjectAccessor = index$1(state.nodeThreeObject);
  31249. var customObjectExtendAccessor = index$1(state.nodeThreeObjectExtend);
  31250. var valAccessor = index$1(state.nodeVal);
  31251. var colorAccessor = index$1(state.nodeColor);
  31252. var visibilityAccessor = index$1(state.nodeVisibility);
  31253. var sphereGeometries = {}; // indexed by node value
  31254. var sphereMaterials = {}; // indexed by color
  31255. threeDigest(state.graphData.nodes.filter(visibilityAccessor), state.graphScene, {
  31256. purge: state._flushObjects || hasAnyPropChanged([// recreate objects if any of these props have changed
  31257. 'nodeThreeObject', 'nodeThreeObjectExtend']),
  31258. objFilter: function objFilter(obj) {
  31259. return obj.__graphObjType === 'node';
  31260. },
  31261. createObj: function createObj(node) {
  31262. var customObj = customObjectAccessor(node);
  31263. var extendObj = customObjectExtendAccessor(node);
  31264. if (customObj && state.nodeThreeObject === customObj) {
  31265. // clone object if it's a shared object among all nodes
  31266. customObj = customObj.clone();
  31267. }
  31268. var obj;
  31269. if (customObj && !extendObj) {
  31270. obj = customObj;
  31271. } else {
  31272. // Add default object (sphere mesh)
  31273. obj = new three$1$1.Mesh();
  31274. obj.__graphDefaultObj = true;
  31275. if (customObj && extendObj) {
  31276. obj.add(customObj); // extend default with custom
  31277. }
  31278. }
  31279. obj.__graphObjType = 'node'; // Add object type
  31280. return obj;
  31281. },
  31282. updateObj: function updateObj(obj, node) {
  31283. if (obj.__graphDefaultObj) {
  31284. // bypass internal updates for custom node objects
  31285. var val = valAccessor(node) || 1;
  31286. var radius = Math.cbrt(val) * state.nodeRelSize;
  31287. var numSegments = state.nodeResolution;
  31288. if (!obj.geometry.type.match(/^Sphere(Buffer)?Geometry$/) || obj.geometry.parameters.radius !== radius || obj.geometry.parameters.widthSegments !== numSegments) {
  31289. if (!sphereGeometries.hasOwnProperty(val)) {
  31290. sphereGeometries[val] = new three$1$1.SphereBufferGeometry(radius, numSegments, numSegments);
  31291. }
  31292. obj.geometry.dispose();
  31293. obj.geometry = sphereGeometries[val];
  31294. }
  31295. var color = colorAccessor(node);
  31296. var materialColor = new three$1$1.Color(colorStr2Hex(color || '#ffffaa'));
  31297. var opacity = state.nodeOpacity * colorAlpha(color);
  31298. if (obj.material.type !== 'MeshLambertMaterial' || !obj.material.color.equals(materialColor) || obj.material.opacity !== opacity) {
  31299. if (!sphereMaterials.hasOwnProperty(color)) {
  31300. sphereMaterials[color] = new three$1$1.MeshLambertMaterial({
  31301. color: materialColor,
  31302. transparent: true,
  31303. opacity: opacity
  31304. });
  31305. }
  31306. obj.material.dispose();
  31307. obj.material = sphereMaterials[color];
  31308. }
  31309. }
  31310. }
  31311. });
  31312. } // Digest links WebGL objects
  31313. if (state._flushObjects || hasAnyPropChanged(['graphData', 'linkThreeObject', 'linkThreeObjectExtend', 'linkMaterial', 'linkColor', 'linkWidth', 'linkVisibility', 'linkResolution', 'linkOpacity', 'linkDirectionalArrowLength', 'linkDirectionalArrowColor', 'linkDirectionalArrowResolution', 'linkDirectionalParticles', 'linkDirectionalParticleWidth', 'linkDirectionalParticleColor', 'linkDirectionalParticleResolution'])) {
  31314. var _customObjectAccessor = index$1(state.linkThreeObject);
  31315. var _customObjectExtendAccessor = index$1(state.linkThreeObjectExtend);
  31316. var customMaterialAccessor = index$1(state.linkMaterial);
  31317. var _visibilityAccessor = index$1(state.linkVisibility);
  31318. var _colorAccessor = index$1(state.linkColor);
  31319. var widthAccessor = index$1(state.linkWidth);
  31320. var cylinderGeometries = {}; // indexed by link width
  31321. var lambertLineMaterials = {}; // for cylinder objects, indexed by link color
  31322. var basicLineMaterials = {}; // for line objects, indexed by link color
  31323. var visibleLinks = state.graphData.links.filter(_visibilityAccessor); // lines digest cycle
  31324. threeDigest(visibleLinks, state.graphScene, {
  31325. objBindAttr: '__lineObj',
  31326. purge: state._flushObjects || hasAnyPropChanged([// recreate objects if any of these props have changed
  31327. 'linkThreeObject', 'linkThreeObjectExtend', 'linkWidth']),
  31328. objFilter: function objFilter(obj) {
  31329. return obj.__graphObjType === 'link';
  31330. },
  31331. createObj: function createObj(link) {
  31332. var customObj = _customObjectAccessor(link);
  31333. var extendObj = _customObjectExtendAccessor(link);
  31334. if (customObj && state.linkThreeObject === customObj) {
  31335. // clone object if it's a shared object among all links
  31336. customObj = customObj.clone();
  31337. }
  31338. var defaultObj;
  31339. if (!customObj || extendObj) {
  31340. // construct default line obj
  31341. var useCylinder = !!widthAccessor(link);
  31342. if (useCylinder) {
  31343. defaultObj = new three$1$1.Mesh();
  31344. } else {
  31345. // Use plain line (constant width)
  31346. var lineGeometry = new three$1$1.BufferGeometry();
  31347. lineGeometry[setAttributeFn]('position', new three$1$1.BufferAttribute(new Float32Array(2 * 3), 3));
  31348. defaultObj = new three$1$1.Line(lineGeometry);
  31349. }
  31350. }
  31351. var obj;
  31352. if (!customObj) {
  31353. obj = defaultObj;
  31354. obj.__graphDefaultObj = true;
  31355. } else {
  31356. if (!extendObj) {
  31357. // use custom object
  31358. obj = customObj;
  31359. } else {
  31360. // extend default with custom in a group
  31361. obj = new three$1$1.Group();
  31362. obj.__graphDefaultObj = true;
  31363. obj.add(defaultObj);
  31364. obj.add(customObj);
  31365. }
  31366. }
  31367. obj.renderOrder = 10; // Prevent visual glitches of dark lines on top of nodes by rendering them last
  31368. obj.__graphObjType = 'link'; // Add object type
  31369. return obj;
  31370. },
  31371. updateObj: function updateObj(updObj, link) {
  31372. if (updObj.__graphDefaultObj) {
  31373. // bypass internal updates for custom link objects
  31374. // select default object if it's an extended group
  31375. var obj = updObj.children.length ? updObj.children[0] : updObj;
  31376. var linkWidth = Math.ceil(widthAccessor(link) * 10) / 10;
  31377. var useCylinder = !!linkWidth;
  31378. if (useCylinder) {
  31379. var r = linkWidth / 2;
  31380. var numSegments = state.linkResolution;
  31381. if (!obj.geometry.type.match(/^Cylinder(Buffer)?Geometry$/) || obj.geometry.parameters.radiusTop !== r || obj.geometry.parameters.radialSegments !== numSegments) {
  31382. if (!cylinderGeometries.hasOwnProperty(linkWidth)) {
  31383. var geometry = new three$1$1.CylinderBufferGeometry(r, r, 1, numSegments, 1, false);
  31384. geometry[applyMatrix4Fn](new three$1$1.Matrix4().makeTranslation(0, 1 / 2, 0));
  31385. geometry[applyMatrix4Fn](new three$1$1.Matrix4().makeRotationX(Math.PI / 2));
  31386. cylinderGeometries[linkWidth] = geometry;
  31387. }
  31388. obj.geometry.dispose();
  31389. obj.geometry = cylinderGeometries[linkWidth];
  31390. }
  31391. }
  31392. var customMaterial = customMaterialAccessor(link);
  31393. if (customMaterial) {
  31394. obj.material = customMaterial;
  31395. } else {
  31396. var color = _colorAccessor(link);
  31397. var materialColor = new three$1$1.Color(colorStr2Hex(color || '#f0f0f0'));
  31398. var opacity = state.linkOpacity * colorAlpha(color);
  31399. var materialType = useCylinder ? 'MeshLambertMaterial' : 'LineBasicMaterial';
  31400. if (obj.material.type !== materialType || !obj.material.color.equals(materialColor) || obj.material.opacity !== opacity) {
  31401. var lineMaterials = useCylinder ? lambertLineMaterials : basicLineMaterials;
  31402. if (!lineMaterials.hasOwnProperty(color)) {
  31403. lineMaterials[color] = new three$1$1[materialType]({
  31404. color: materialColor,
  31405. transparent: opacity < 1,
  31406. opacity: opacity,
  31407. depthWrite: opacity >= 1 // Prevent transparency issues
  31408. });
  31409. }
  31410. obj.material.dispose();
  31411. obj.material = lineMaterials[color];
  31412. }
  31413. }
  31414. }
  31415. }
  31416. }); // Arrows digest cycle
  31417. if (state.linkDirectionalArrowLength || changedProps.hasOwnProperty('linkDirectionalArrowLength')) {
  31418. var arrowLengthAccessor = index$1(state.linkDirectionalArrowLength);
  31419. var arrowColorAccessor = index$1(state.linkDirectionalArrowColor);
  31420. threeDigest(visibleLinks.filter(arrowLengthAccessor), state.graphScene, {
  31421. objBindAttr: '__arrowObj',
  31422. objFilter: function objFilter(obj) {
  31423. return obj.__linkThreeObjType === 'arrow';
  31424. },
  31425. createObj: function createObj() {
  31426. var obj = new three$1$1.Mesh(undefined, new three$1$1.MeshLambertMaterial({
  31427. transparent: true
  31428. }));
  31429. obj.__linkThreeObjType = 'arrow'; // Add object type
  31430. return obj;
  31431. },
  31432. updateObj: function updateObj(obj, link) {
  31433. var arrowLength = arrowLengthAccessor(link);
  31434. var numSegments = state.linkDirectionalArrowResolution;
  31435. if (!obj.geometry.type.match(/^Cone(Buffer)?Geometry$/) || obj.geometry.parameters.height !== arrowLength || obj.geometry.parameters.radialSegments !== numSegments) {
  31436. var coneGeometry = new three$1$1.ConeBufferGeometry(arrowLength * 0.25, arrowLength, numSegments); // Correct orientation
  31437. coneGeometry.translate(0, arrowLength / 2, 0);
  31438. coneGeometry.rotateX(Math.PI / 2);
  31439. obj.geometry.dispose();
  31440. obj.geometry = coneGeometry;
  31441. }
  31442. obj.material.color = new three$1$1.Color(arrowColorAccessor(link) || _colorAccessor(link) || '#f0f0f0');
  31443. obj.material.opacity = state.linkOpacity * 3;
  31444. }
  31445. });
  31446. } // Photon particles digest cycle
  31447. if (state.linkDirectionalParticles || changedProps.hasOwnProperty('linkDirectionalParticles')) {
  31448. var particlesAccessor = index$1(state.linkDirectionalParticles);
  31449. var particleWidthAccessor = index$1(state.linkDirectionalParticleWidth);
  31450. var particleColorAccessor = index$1(state.linkDirectionalParticleColor);
  31451. var particleMaterials = {}; // indexed by link color
  31452. var particleGeometries = {}; // indexed by particle width
  31453. threeDigest(visibleLinks.filter(particlesAccessor), state.graphScene, {
  31454. objBindAttr: '__photonsObj',
  31455. objFilter: function objFilter(obj) {
  31456. return obj.__linkThreeObjType === 'photons';
  31457. },
  31458. createObj: function createObj() {
  31459. var obj = new three$1$1.Group();
  31460. obj.__linkThreeObjType = 'photons'; // Add object type
  31461. return obj;
  31462. },
  31463. updateObj: function updateObj(obj, link) {
  31464. var numPhotons = Math.round(Math.abs(particlesAccessor(link)));
  31465. var curPhoton = !!obj.children.length && obj.children[0];
  31466. var photonR = Math.ceil(particleWidthAccessor(link) * 10) / 10 / 2;
  31467. var numSegments = state.linkDirectionalParticleResolution;
  31468. var particleGeometry;
  31469. if (curPhoton && curPhoton.geometry.parameters.radius === photonR && curPhoton.geometry.parameters.widthSegments === numSegments) {
  31470. particleGeometry = curPhoton.geometry;
  31471. } else {
  31472. if (!particleGeometries.hasOwnProperty(photonR)) {
  31473. particleGeometries[photonR] = new three$1$1.SphereBufferGeometry(photonR, numSegments, numSegments);
  31474. }
  31475. particleGeometry = particleGeometries[photonR];
  31476. curPhoton && curPhoton.geometry.dispose();
  31477. }
  31478. var photonColor = particleColorAccessor(link) || _colorAccessor(link) || '#f0f0f0';
  31479. var materialColor = new three$1$1.Color(colorStr2Hex(photonColor));
  31480. var opacity = state.linkOpacity * 3;
  31481. var particleMaterial;
  31482. if (curPhoton && curPhoton.material.color.equals(materialColor) && curPhoton.material.opacity === opacity) {
  31483. particleMaterial = curPhoton.material;
  31484. } else {
  31485. if (!particleMaterials.hasOwnProperty(photonColor)) {
  31486. particleMaterials[photonColor] = new three$1$1.MeshLambertMaterial({
  31487. color: materialColor,
  31488. transparent: true,
  31489. opacity: opacity
  31490. });
  31491. }
  31492. particleMaterial = particleMaterials[photonColor];
  31493. curPhoton && curPhoton.material.dispose();
  31494. } // digest cycle for each photon
  31495. threeDigest(_toConsumableArray$1(new Array(numPhotons)).map(function (_, idx) {
  31496. return {
  31497. idx: idx
  31498. };
  31499. }), obj, {
  31500. idAccessor: function idAccessor(d) {
  31501. return d.idx;
  31502. },
  31503. createObj: function createObj() {
  31504. return new three$1$1.Mesh(particleGeometry, particleMaterial);
  31505. },
  31506. updateObj: function updateObj(obj) {
  31507. obj.geometry = particleGeometry;
  31508. obj.material = particleMaterial;
  31509. }
  31510. });
  31511. }
  31512. });
  31513. }
  31514. }
  31515. state._flushObjects = false; // reset objects refresh flag
  31516. // simulation engine
  31517. if (hasAnyPropChanged(['graphData', 'nodeId', 'linkSource', 'linkTarget', 'numDimensions', 'forceEngine', 'dagMode', 'dagNodeFilter', 'dagLevelDistance'])) {
  31518. state.engineRunning = false; // Pause simulation
  31519. // parse links
  31520. state.graphData.links.forEach(function (link) {
  31521. link.source = link[state.linkSource];
  31522. link.target = link[state.linkTarget];
  31523. }); // Feed data to force-directed layout
  31524. var isD3Sim = state.forceEngine !== 'ngraph';
  31525. var layout;
  31526. if (isD3Sim) {
  31527. // D3-force
  31528. (layout = state.d3ForceLayout).stop().alpha(1) // re-heat the simulation
  31529. .numDimensions(state.numDimensions).nodes(state.graphData.nodes); // add links (if link force is still active)
  31530. var linkForce = state.d3ForceLayout.force('link');
  31531. if (linkForce) {
  31532. linkForce.id(function (d) {
  31533. return d[state.nodeId];
  31534. }).links(state.graphData.links);
  31535. } // setup dag force constraints
  31536. var nodeDepths = state.dagMode && getDagDepths(state.graphData, function (node) {
  31537. return node[state.nodeId];
  31538. }, {
  31539. nodeFilter: state.dagNodeFilter,
  31540. onLoopError: state.onDagError || undefined
  31541. });
  31542. var maxDepth = Math.max.apply(Math, _toConsumableArray$1(Object.values(nodeDepths || [])));
  31543. var dagLevelDistance = state.dagLevelDistance || state.graphData.nodes.length / (maxDepth || 1) * DAG_LEVEL_NODE_RATIO * (['radialin', 'radialout'].indexOf(state.dagMode) !== -1 ? 0.7 : 1); // Fix nodes to x,y,z for dag mode
  31544. if (state.dagMode) {
  31545. var getFFn = function getFFn(fix, invert) {
  31546. return function (node) {
  31547. return !fix ? undefined : (nodeDepths[node[state.nodeId]] - maxDepth / 2) * dagLevelDistance * (invert ? -1 : 1);
  31548. };
  31549. };
  31550. var fxFn = getFFn(['lr', 'rl'].indexOf(state.dagMode) !== -1, state.dagMode === 'rl');
  31551. var fyFn = getFFn(['td', 'bu'].indexOf(state.dagMode) !== -1, state.dagMode === 'td');
  31552. var fzFn = getFFn(['zin', 'zout'].indexOf(state.dagMode) !== -1, state.dagMode === 'zout');
  31553. state.graphData.nodes.filter(state.dagNodeFilter).forEach(function (node) {
  31554. node.fx = fxFn(node);
  31555. node.fy = fyFn(node);
  31556. node.fz = fzFn(node);
  31557. });
  31558. } // Use radial force for radial dags
  31559. state.d3ForceLayout.force('dagRadial', ['radialin', 'radialout'].indexOf(state.dagMode) !== -1 ? forceRadial(function (node) {
  31560. var nodeDepth = nodeDepths[node[state.nodeId]] || -1;
  31561. return (state.dagMode === 'radialin' ? maxDepth - nodeDepth : nodeDepth) * dagLevelDistance;
  31562. }).strength(function (node) {
  31563. return state.dagNodeFilter(node) ? 1 : 0;
  31564. }) : null);
  31565. } else {
  31566. // ngraph
  31567. var _graph = ngraph.graph();
  31568. state.graphData.nodes.forEach(function (node) {
  31569. _graph.addNode(node[state.nodeId]);
  31570. });
  31571. state.graphData.links.forEach(function (link) {
  31572. _graph.addLink(link.source, link.target);
  31573. });
  31574. layout = ngraph.forcelayout(_graph, _objectSpread2({
  31575. dimensions: state.numDimensions
  31576. }, state.ngraphPhysics));
  31577. layout.graph = _graph; // Attach graph reference to layout
  31578. }
  31579. for (var i = 0; i < state.warmupTicks && !(isD3Sim && state.d3AlphaMin > 0 && state.d3ForceLayout.alpha() < state.d3AlphaMin); i++) {
  31580. layout[isD3Sim ? "tick" : "step"]();
  31581. } // Initial ticks before starting to render
  31582. state.layout = layout;
  31583. this.resetCountdown();
  31584. }
  31585. state.engineRunning = true; // resume simulation
  31586. state.onFinishUpdate();
  31587. }
  31588. });
  31589. function fromKapsule (kapsule) {
  31590. var baseClass = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Object;
  31591. var initKapsuleWithSelf = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  31592. var FromKapsule = /*#__PURE__*/function (_baseClass) {
  31593. _inherits(FromKapsule, _baseClass);
  31594. var _super = _createSuper(FromKapsule);
  31595. function FromKapsule() {
  31596. var _this;
  31597. _classCallCheck(this, FromKapsule);
  31598. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  31599. args[_key] = arguments[_key];
  31600. }
  31601. _this = _super.call.apply(_super, [this].concat(args));
  31602. _this.__kapsuleInstance = kapsule().apply(void 0, [].concat(_toConsumableArray$1(initKapsuleWithSelf ? [_assertThisInitialized$1(_this)] : []), args));
  31603. return _this;
  31604. }
  31605. return FromKapsule;
  31606. }(baseClass); // attach kapsule props/methods to class prototype
  31607. Object.keys(kapsule()).forEach(function (m) {
  31608. return FromKapsule.prototype[m] = function () {
  31609. var _this$__kapsuleInstan;
  31610. var returnVal = (_this$__kapsuleInstan = this.__kapsuleInstance)[m].apply(_this$__kapsuleInstan, arguments);
  31611. return returnVal === this.__kapsuleInstance ? this // chain based on this class, not the kapsule obj
  31612. : returnVal;
  31613. };
  31614. });
  31615. return FromKapsule;
  31616. }
  31617. var three$2 = window.THREE ? window.THREE : {
  31618. Group: Group$1
  31619. }; // Prefer consumption from global THREE, if exists
  31620. var threeForcegraph = fromKapsule(ForceGraph, three$2.Group, true);
  31621. const _changeEvent$2 = { type: 'change' };
  31622. const _startEvent$1 = { type: 'start' };
  31623. const _endEvent$1 = { type: 'end' };
  31624. class TrackballControls extends EventDispatcher {
  31625. constructor( object, domElement ) {
  31626. super();
  31627. if ( domElement === undefined ) console.warn( 'THREE.TrackballControls: The second parameter "domElement" is now mandatory.' );
  31628. if ( domElement === document ) console.error( 'THREE.TrackballControls: "document" should not be used as the target "domElement". Please use "renderer.domElement" instead.' );
  31629. const scope = this;
  31630. const STATE = { NONE: - 1, ROTATE: 0, ZOOM: 1, PAN: 2, TOUCH_ROTATE: 3, TOUCH_ZOOM_PAN: 4 };
  31631. this.object = object;
  31632. this.domElement = domElement;
  31633. this.domElement.style.touchAction = 'none'; // disable touch scroll
  31634. // API
  31635. this.enabled = true;
  31636. this.screen = { left: 0, top: 0, width: 0, height: 0 };
  31637. this.rotateSpeed = 1.0;
  31638. this.zoomSpeed = 1.2;
  31639. this.panSpeed = 0.3;
  31640. this.noRotate = false;
  31641. this.noZoom = false;
  31642. this.noPan = false;
  31643. this.staticMoving = false;
  31644. this.dynamicDampingFactor = 0.2;
  31645. this.minDistance = 0;
  31646. this.maxDistance = Infinity;
  31647. this.keys = [ 'KeyA' /*A*/, 'KeyS' /*S*/, 'KeyD' /*D*/ ];
  31648. this.mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN };
  31649. // internals
  31650. this.target = new Vector3();
  31651. const EPS = 0.000001;
  31652. const lastPosition = new Vector3();
  31653. let lastZoom = 1;
  31654. let _state = STATE.NONE,
  31655. _keyState = STATE.NONE,
  31656. _touchZoomDistanceStart = 0,
  31657. _touchZoomDistanceEnd = 0,
  31658. _lastAngle = 0;
  31659. const _eye = new Vector3(),
  31660. _movePrev = new Vector2(),
  31661. _moveCurr = new Vector2(),
  31662. _lastAxis = new Vector3(),
  31663. _zoomStart = new Vector2(),
  31664. _zoomEnd = new Vector2(),
  31665. _panStart = new Vector2(),
  31666. _panEnd = new Vector2(),
  31667. _pointers = [],
  31668. _pointerPositions = {};
  31669. // for reset
  31670. this.target0 = this.target.clone();
  31671. this.position0 = this.object.position.clone();
  31672. this.up0 = this.object.up.clone();
  31673. this.zoom0 = this.object.zoom;
  31674. // methods
  31675. this.handleResize = function () {
  31676. const box = scope.domElement.getBoundingClientRect();
  31677. // adjustments come from similar code in the jquery offset() function
  31678. const d = scope.domElement.ownerDocument.documentElement;
  31679. scope.screen.left = box.left + window.pageXOffset - d.clientLeft;
  31680. scope.screen.top = box.top + window.pageYOffset - d.clientTop;
  31681. scope.screen.width = box.width;
  31682. scope.screen.height = box.height;
  31683. };
  31684. const getMouseOnScreen = ( function () {
  31685. const vector = new Vector2();
  31686. return function getMouseOnScreen( pageX, pageY ) {
  31687. vector.set(
  31688. ( pageX - scope.screen.left ) / scope.screen.width,
  31689. ( pageY - scope.screen.top ) / scope.screen.height
  31690. );
  31691. return vector;
  31692. };
  31693. }() );
  31694. const getMouseOnCircle = ( function () {
  31695. const vector = new Vector2();
  31696. return function getMouseOnCircle( pageX, pageY ) {
  31697. vector.set(
  31698. ( ( pageX - scope.screen.width * 0.5 - scope.screen.left ) / ( scope.screen.width * 0.5 ) ),
  31699. ( ( scope.screen.height + 2 * ( scope.screen.top - pageY ) ) / scope.screen.width ) // screen.width intentional
  31700. );
  31701. return vector;
  31702. };
  31703. }() );
  31704. this.rotateCamera = ( function () {
  31705. const axis = new Vector3(),
  31706. quaternion = new Quaternion(),
  31707. eyeDirection = new Vector3(),
  31708. objectUpDirection = new Vector3(),
  31709. objectSidewaysDirection = new Vector3(),
  31710. moveDirection = new Vector3();
  31711. return function rotateCamera() {
  31712. moveDirection.set( _moveCurr.x - _movePrev.x, _moveCurr.y - _movePrev.y, 0 );
  31713. let angle = moveDirection.length();
  31714. if ( angle ) {
  31715. _eye.copy( scope.object.position ).sub( scope.target );
  31716. eyeDirection.copy( _eye ).normalize();
  31717. objectUpDirection.copy( scope.object.up ).normalize();
  31718. objectSidewaysDirection.crossVectors( objectUpDirection, eyeDirection ).normalize();
  31719. objectUpDirection.setLength( _moveCurr.y - _movePrev.y );
  31720. objectSidewaysDirection.setLength( _moveCurr.x - _movePrev.x );
  31721. moveDirection.copy( objectUpDirection.add( objectSidewaysDirection ) );
  31722. axis.crossVectors( moveDirection, _eye ).normalize();
  31723. angle *= scope.rotateSpeed;
  31724. quaternion.setFromAxisAngle( axis, angle );
  31725. _eye.applyQuaternion( quaternion );
  31726. scope.object.up.applyQuaternion( quaternion );
  31727. _lastAxis.copy( axis );
  31728. _lastAngle = angle;
  31729. } else if ( ! scope.staticMoving && _lastAngle ) {
  31730. _lastAngle *= Math.sqrt( 1.0 - scope.dynamicDampingFactor );
  31731. _eye.copy( scope.object.position ).sub( scope.target );
  31732. quaternion.setFromAxisAngle( _lastAxis, _lastAngle );
  31733. _eye.applyQuaternion( quaternion );
  31734. scope.object.up.applyQuaternion( quaternion );
  31735. }
  31736. _movePrev.copy( _moveCurr );
  31737. };
  31738. }() );
  31739. this.zoomCamera = function () {
  31740. let factor;
  31741. if ( _state === STATE.TOUCH_ZOOM_PAN ) {
  31742. factor = _touchZoomDistanceStart / _touchZoomDistanceEnd;
  31743. _touchZoomDistanceStart = _touchZoomDistanceEnd;
  31744. if ( scope.object.isPerspectiveCamera ) {
  31745. _eye.multiplyScalar( factor );
  31746. } else if ( scope.object.isOrthographicCamera ) {
  31747. scope.object.zoom *= factor;
  31748. scope.object.updateProjectionMatrix();
  31749. } else {
  31750. console.warn( 'THREE.TrackballControls: Unsupported camera type' );
  31751. }
  31752. } else {
  31753. factor = 1.0 + ( _zoomEnd.y - _zoomStart.y ) * scope.zoomSpeed;
  31754. if ( factor !== 1.0 && factor > 0.0 ) {
  31755. if ( scope.object.isPerspectiveCamera ) {
  31756. _eye.multiplyScalar( factor );
  31757. } else if ( scope.object.isOrthographicCamera ) {
  31758. scope.object.zoom /= factor;
  31759. scope.object.updateProjectionMatrix();
  31760. } else {
  31761. console.warn( 'THREE.TrackballControls: Unsupported camera type' );
  31762. }
  31763. }
  31764. if ( scope.staticMoving ) {
  31765. _zoomStart.copy( _zoomEnd );
  31766. } else {
  31767. _zoomStart.y += ( _zoomEnd.y - _zoomStart.y ) * this.dynamicDampingFactor;
  31768. }
  31769. }
  31770. };
  31771. this.panCamera = ( function () {
  31772. const mouseChange = new Vector2(),
  31773. objectUp = new Vector3(),
  31774. pan = new Vector3();
  31775. return function panCamera() {
  31776. mouseChange.copy( _panEnd ).sub( _panStart );
  31777. if ( mouseChange.lengthSq() ) {
  31778. if ( scope.object.isOrthographicCamera ) {
  31779. const scale_x = ( scope.object.right - scope.object.left ) / scope.object.zoom / scope.domElement.clientWidth;
  31780. const scale_y = ( scope.object.top - scope.object.bottom ) / scope.object.zoom / scope.domElement.clientWidth;
  31781. mouseChange.x *= scale_x;
  31782. mouseChange.y *= scale_y;
  31783. }
  31784. mouseChange.multiplyScalar( _eye.length() * scope.panSpeed );
  31785. pan.copy( _eye ).cross( scope.object.up ).setLength( mouseChange.x );
  31786. pan.add( objectUp.copy( scope.object.up ).setLength( mouseChange.y ) );
  31787. scope.object.position.add( pan );
  31788. scope.target.add( pan );
  31789. if ( scope.staticMoving ) {
  31790. _panStart.copy( _panEnd );
  31791. } else {
  31792. _panStart.add( mouseChange.subVectors( _panEnd, _panStart ).multiplyScalar( scope.dynamicDampingFactor ) );
  31793. }
  31794. }
  31795. };
  31796. }() );
  31797. this.checkDistances = function () {
  31798. if ( ! scope.noZoom || ! scope.noPan ) {
  31799. if ( _eye.lengthSq() > scope.maxDistance * scope.maxDistance ) {
  31800. scope.object.position.addVectors( scope.target, _eye.setLength( scope.maxDistance ) );
  31801. _zoomStart.copy( _zoomEnd );
  31802. }
  31803. if ( _eye.lengthSq() < scope.minDistance * scope.minDistance ) {
  31804. scope.object.position.addVectors( scope.target, _eye.setLength( scope.minDistance ) );
  31805. _zoomStart.copy( _zoomEnd );
  31806. }
  31807. }
  31808. };
  31809. this.update = function () {
  31810. _eye.subVectors( scope.object.position, scope.target );
  31811. if ( ! scope.noRotate ) {
  31812. scope.rotateCamera();
  31813. }
  31814. if ( ! scope.noZoom ) {
  31815. scope.zoomCamera();
  31816. }
  31817. if ( ! scope.noPan ) {
  31818. scope.panCamera();
  31819. }
  31820. scope.object.position.addVectors( scope.target, _eye );
  31821. if ( scope.object.isPerspectiveCamera ) {
  31822. scope.checkDistances();
  31823. scope.object.lookAt( scope.target );
  31824. if ( lastPosition.distanceToSquared( scope.object.position ) > EPS ) {
  31825. scope.dispatchEvent( _changeEvent$2 );
  31826. lastPosition.copy( scope.object.position );
  31827. }
  31828. } else if ( scope.object.isOrthographicCamera ) {
  31829. scope.object.lookAt( scope.target );
  31830. if ( lastPosition.distanceToSquared( scope.object.position ) > EPS || lastZoom !== scope.object.zoom ) {
  31831. scope.dispatchEvent( _changeEvent$2 );
  31832. lastPosition.copy( scope.object.position );
  31833. lastZoom = scope.object.zoom;
  31834. }
  31835. } else {
  31836. console.warn( 'THREE.TrackballControls: Unsupported camera type' );
  31837. }
  31838. };
  31839. this.reset = function () {
  31840. _state = STATE.NONE;
  31841. _keyState = STATE.NONE;
  31842. scope.target.copy( scope.target0 );
  31843. scope.object.position.copy( scope.position0 );
  31844. scope.object.up.copy( scope.up0 );
  31845. scope.object.zoom = scope.zoom0;
  31846. scope.object.updateProjectionMatrix();
  31847. _eye.subVectors( scope.object.position, scope.target );
  31848. scope.object.lookAt( scope.target );
  31849. scope.dispatchEvent( _changeEvent$2 );
  31850. lastPosition.copy( scope.object.position );
  31851. lastZoom = scope.object.zoom;
  31852. };
  31853. // listeners
  31854. function onPointerDown( event ) {
  31855. if ( scope.enabled === false ) return;
  31856. if ( _pointers.length === 0 ) {
  31857. scope.domElement.ownerDocument.addEventListener( 'pointermove', onPointerMove );
  31858. scope.domElement.ownerDocument.addEventListener( 'pointerup', onPointerUp );
  31859. }
  31860. //
  31861. addPointer( event );
  31862. if ( event.pointerType === 'touch' ) {
  31863. onTouchStart( event );
  31864. } else {
  31865. onMouseDown( event );
  31866. }
  31867. }
  31868. function onPointerMove( event ) {
  31869. if ( scope.enabled === false ) return;
  31870. if ( event.pointerType === 'touch' ) {
  31871. onTouchMove( event );
  31872. } else {
  31873. onMouseMove( event );
  31874. }
  31875. }
  31876. function onPointerUp( event ) {
  31877. if ( scope.enabled === false ) return;
  31878. if ( event.pointerType === 'touch' ) {
  31879. onTouchEnd( event );
  31880. } else {
  31881. onMouseUp();
  31882. }
  31883. //
  31884. removePointer( event );
  31885. if ( _pointers.length === 0 ) {
  31886. scope.domElement.ownerDocument.removeEventListener( 'pointermove', onPointerMove );
  31887. scope.domElement.ownerDocument.removeEventListener( 'pointerup', onPointerUp );
  31888. }
  31889. }
  31890. function onPointerCancel( event ) {
  31891. removePointer( event );
  31892. }
  31893. function keydown( event ) {
  31894. if ( scope.enabled === false ) return;
  31895. window.removeEventListener( 'keydown', keydown );
  31896. if ( _keyState !== STATE.NONE ) {
  31897. return;
  31898. } else if ( event.code === scope.keys[ STATE.ROTATE ] && ! scope.noRotate ) {
  31899. _keyState = STATE.ROTATE;
  31900. } else if ( event.code === scope.keys[ STATE.ZOOM ] && ! scope.noZoom ) {
  31901. _keyState = STATE.ZOOM;
  31902. } else if ( event.code === scope.keys[ STATE.PAN ] && ! scope.noPan ) {
  31903. _keyState = STATE.PAN;
  31904. }
  31905. }
  31906. function keyup() {
  31907. if ( scope.enabled === false ) return;
  31908. _keyState = STATE.NONE;
  31909. window.addEventListener( 'keydown', keydown );
  31910. }
  31911. function onMouseDown( event ) {
  31912. if ( _state === STATE.NONE ) {
  31913. switch ( event.button ) {
  31914. case scope.mouseButtons.LEFT:
  31915. _state = STATE.ROTATE;
  31916. break;
  31917. case scope.mouseButtons.MIDDLE:
  31918. _state = STATE.ZOOM;
  31919. break;
  31920. case scope.mouseButtons.RIGHT:
  31921. _state = STATE.PAN;
  31922. break;
  31923. default:
  31924. _state = STATE.NONE;
  31925. }
  31926. }
  31927. const state = ( _keyState !== STATE.NONE ) ? _keyState : _state;
  31928. if ( state === STATE.ROTATE && ! scope.noRotate ) {
  31929. _moveCurr.copy( getMouseOnCircle( event.pageX, event.pageY ) );
  31930. _movePrev.copy( _moveCurr );
  31931. } else if ( state === STATE.ZOOM && ! scope.noZoom ) {
  31932. _zoomStart.copy( getMouseOnScreen( event.pageX, event.pageY ) );
  31933. _zoomEnd.copy( _zoomStart );
  31934. } else if ( state === STATE.PAN && ! scope.noPan ) {
  31935. _panStart.copy( getMouseOnScreen( event.pageX, event.pageY ) );
  31936. _panEnd.copy( _panStart );
  31937. }
  31938. scope.domElement.ownerDocument.addEventListener( 'pointermove', onPointerMove );
  31939. scope.domElement.ownerDocument.addEventListener( 'pointerup', onPointerUp );
  31940. scope.dispatchEvent( _startEvent$1 );
  31941. }
  31942. function onMouseMove( event ) {
  31943. const state = ( _keyState !== STATE.NONE ) ? _keyState : _state;
  31944. if ( state === STATE.ROTATE && ! scope.noRotate ) {
  31945. _movePrev.copy( _moveCurr );
  31946. _moveCurr.copy( getMouseOnCircle( event.pageX, event.pageY ) );
  31947. } else if ( state === STATE.ZOOM && ! scope.noZoom ) {
  31948. _zoomEnd.copy( getMouseOnScreen( event.pageX, event.pageY ) );
  31949. } else if ( state === STATE.PAN && ! scope.noPan ) {
  31950. _panEnd.copy( getMouseOnScreen( event.pageX, event.pageY ) );
  31951. }
  31952. }
  31953. function onMouseUp() {
  31954. _state = STATE.NONE;
  31955. scope.domElement.ownerDocument.removeEventListener( 'pointermove', onPointerMove );
  31956. scope.domElement.ownerDocument.removeEventListener( 'pointerup', onPointerUp );
  31957. scope.dispatchEvent( _endEvent$1 );
  31958. }
  31959. function onMouseWheel( event ) {
  31960. if ( scope.enabled === false ) return;
  31961. if ( scope.noZoom === true ) return;
  31962. event.preventDefault();
  31963. switch ( event.deltaMode ) {
  31964. case 2:
  31965. // Zoom in pages
  31966. _zoomStart.y -= event.deltaY * 0.025;
  31967. break;
  31968. case 1:
  31969. // Zoom in lines
  31970. _zoomStart.y -= event.deltaY * 0.01;
  31971. break;
  31972. default:
  31973. // undefined, 0, assume pixels
  31974. _zoomStart.y -= event.deltaY * 0.00025;
  31975. break;
  31976. }
  31977. scope.dispatchEvent( _startEvent$1 );
  31978. scope.dispatchEvent( _endEvent$1 );
  31979. }
  31980. function onTouchStart( event ) {
  31981. trackPointer( event );
  31982. switch ( _pointers.length ) {
  31983. case 1:
  31984. _state = STATE.TOUCH_ROTATE;
  31985. _moveCurr.copy( getMouseOnCircle( _pointers[ 0 ].pageX, _pointers[ 0 ].pageY ) );
  31986. _movePrev.copy( _moveCurr );
  31987. break;
  31988. default: // 2 or more
  31989. _state = STATE.TOUCH_ZOOM_PAN;
  31990. const dx = _pointers[ 0 ].pageX - _pointers[ 1 ].pageX;
  31991. const dy = _pointers[ 0 ].pageY - _pointers[ 1 ].pageY;
  31992. _touchZoomDistanceEnd = _touchZoomDistanceStart = Math.sqrt( dx * dx + dy * dy );
  31993. const x = ( _pointers[ 0 ].pageX + _pointers[ 1 ].pageX ) / 2;
  31994. const y = ( _pointers[ 0 ].pageY + _pointers[ 1 ].pageY ) / 2;
  31995. _panStart.copy( getMouseOnScreen( x, y ) );
  31996. _panEnd.copy( _panStart );
  31997. break;
  31998. }
  31999. scope.dispatchEvent( _startEvent$1 );
  32000. }
  32001. function onTouchMove( event ) {
  32002. trackPointer( event );
  32003. switch ( _pointers.length ) {
  32004. case 1:
  32005. _movePrev.copy( _moveCurr );
  32006. _moveCurr.copy( getMouseOnCircle( event.pageX, event.pageY ) );
  32007. break;
  32008. default: // 2 or more
  32009. const position = getSecondPointerPosition( event );
  32010. const dx = event.pageX - position.x;
  32011. const dy = event.pageY - position.y;
  32012. _touchZoomDistanceEnd = Math.sqrt( dx * dx + dy * dy );
  32013. const x = ( event.pageX + position.x ) / 2;
  32014. const y = ( event.pageY + position.y ) / 2;
  32015. _panEnd.copy( getMouseOnScreen( x, y ) );
  32016. break;
  32017. }
  32018. }
  32019. function onTouchEnd( event ) {
  32020. switch ( _pointers.length ) {
  32021. case 0:
  32022. _state = STATE.NONE;
  32023. break;
  32024. case 1:
  32025. _state = STATE.TOUCH_ROTATE;
  32026. _moveCurr.copy( getMouseOnCircle( event.pageX, event.pageY ) );
  32027. _movePrev.copy( _moveCurr );
  32028. break;
  32029. }
  32030. scope.dispatchEvent( _endEvent$1 );
  32031. }
  32032. function contextmenu( event ) {
  32033. if ( scope.enabled === false ) return;
  32034. event.preventDefault();
  32035. }
  32036. function addPointer( event ) {
  32037. _pointers.push( event );
  32038. }
  32039. function removePointer( event ) {
  32040. delete _pointerPositions[ event.pointerId ];
  32041. for ( let i = 0; i < _pointers.length; i ++ ) {
  32042. if ( _pointers[ i ].pointerId == event.pointerId ) {
  32043. _pointers.splice( i, 1 );
  32044. return;
  32045. }
  32046. }
  32047. }
  32048. function trackPointer( event ) {
  32049. let position = _pointerPositions[ event.pointerId ];
  32050. if ( position === undefined ) {
  32051. position = new Vector2();
  32052. _pointerPositions[ event.pointerId ] = position;
  32053. }
  32054. position.set( event.pageX, event.pageY );
  32055. }
  32056. function getSecondPointerPosition( event ) {
  32057. const pointer = ( event.pointerId === _pointers[ 0 ].pointerId ) ? _pointers[ 1 ] : _pointers[ 0 ];
  32058. return _pointerPositions[ pointer.pointerId ];
  32059. }
  32060. this.dispose = function () {
  32061. scope.domElement.removeEventListener( 'contextmenu', contextmenu );
  32062. scope.domElement.removeEventListener( 'pointerdown', onPointerDown );
  32063. scope.domElement.removeEventListener( 'pointercancel', onPointerCancel );
  32064. scope.domElement.removeEventListener( 'wheel', onMouseWheel );
  32065. window.removeEventListener( 'keydown', keydown );
  32066. window.removeEventListener( 'keyup', keyup );
  32067. };
  32068. this.domElement.addEventListener( 'contextmenu', contextmenu );
  32069. this.domElement.addEventListener( 'pointerdown', onPointerDown );
  32070. this.domElement.addEventListener( 'pointercancel', onPointerCancel );
  32071. this.domElement.addEventListener( 'wheel', onMouseWheel, { passive: false } );
  32072. window.addEventListener( 'keydown', keydown );
  32073. window.addEventListener( 'keyup', keyup );
  32074. this.handleResize();
  32075. // force an update at start
  32076. this.update();
  32077. }
  32078. }
  32079. // This set of controls performs orbiting, dollying (zooming), and panning.
  32080. // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
  32081. //
  32082. // Orbit - left mouse / touch: one-finger move
  32083. // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
  32084. // Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move
  32085. const _changeEvent$1 = { type: 'change' };
  32086. const _startEvent = { type: 'start' };
  32087. const _endEvent = { type: 'end' };
  32088. class OrbitControls extends EventDispatcher {
  32089. constructor( object, domElement ) {
  32090. super();
  32091. if ( domElement === undefined ) console.warn( 'THREE.OrbitControls: The second parameter "domElement" is now mandatory.' );
  32092. if ( domElement === document ) console.error( 'THREE.OrbitControls: "document" should not be used as the target "domElement". Please use "renderer.domElement" instead.' );
  32093. this.object = object;
  32094. this.domElement = domElement;
  32095. this.domElement.style.touchAction = 'none'; // disable touch scroll
  32096. // Set to false to disable this control
  32097. this.enabled = true;
  32098. // "target" sets the location of focus, where the object orbits around
  32099. this.target = new Vector3();
  32100. // How far you can dolly in and out ( PerspectiveCamera only )
  32101. this.minDistance = 0;
  32102. this.maxDistance = Infinity;
  32103. // How far you can zoom in and out ( OrthographicCamera only )
  32104. this.minZoom = 0;
  32105. this.maxZoom = Infinity;
  32106. // How far you can orbit vertically, upper and lower limits.
  32107. // Range is 0 to Math.PI radians.
  32108. this.minPolarAngle = 0; // radians
  32109. this.maxPolarAngle = Math.PI; // radians
  32110. // How far you can orbit horizontally, upper and lower limits.
  32111. // If set, the interval [ min, max ] must be a sub-interval of [ - 2 PI, 2 PI ], with ( max - min < 2 PI )
  32112. this.minAzimuthAngle = - Infinity; // radians
  32113. this.maxAzimuthAngle = Infinity; // radians
  32114. // Set to true to enable damping (inertia)
  32115. // If damping is enabled, you must call controls.update() in your animation loop
  32116. this.enableDamping = false;
  32117. this.dampingFactor = 0.05;
  32118. // This option actually enables dollying in and out; left as "zoom" for backwards compatibility.
  32119. // Set to false to disable zooming
  32120. this.enableZoom = true;
  32121. this.zoomSpeed = 1.0;
  32122. // Set to false to disable rotating
  32123. this.enableRotate = true;
  32124. this.rotateSpeed = 1.0;
  32125. // Set to false to disable panning
  32126. this.enablePan = true;
  32127. this.panSpeed = 1.0;
  32128. this.screenSpacePanning = true; // if false, pan orthogonal to world-space direction camera.up
  32129. this.keyPanSpeed = 7.0; // pixels moved per arrow key push
  32130. // Set to true to automatically rotate around the target
  32131. // If auto-rotate is enabled, you must call controls.update() in your animation loop
  32132. this.autoRotate = false;
  32133. this.autoRotateSpeed = 2.0; // 30 seconds per orbit when fps is 60
  32134. // The four arrow keys
  32135. this.keys = { LEFT: 'ArrowLeft', UP: 'ArrowUp', RIGHT: 'ArrowRight', BOTTOM: 'ArrowDown' };
  32136. // Mouse buttons
  32137. this.mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN };
  32138. // Touch fingers
  32139. this.touches = { ONE: TOUCH.ROTATE, TWO: TOUCH.DOLLY_PAN };
  32140. // for reset
  32141. this.target0 = this.target.clone();
  32142. this.position0 = this.object.position.clone();
  32143. this.zoom0 = this.object.zoom;
  32144. // the target DOM element for key events
  32145. this._domElementKeyEvents = null;
  32146. //
  32147. // public methods
  32148. //
  32149. this.getPolarAngle = function () {
  32150. return spherical.phi;
  32151. };
  32152. this.getAzimuthalAngle = function () {
  32153. return spherical.theta;
  32154. };
  32155. this.listenToKeyEvents = function ( domElement ) {
  32156. domElement.addEventListener( 'keydown', onKeyDown );
  32157. this._domElementKeyEvents = domElement;
  32158. };
  32159. this.saveState = function () {
  32160. scope.target0.copy( scope.target );
  32161. scope.position0.copy( scope.object.position );
  32162. scope.zoom0 = scope.object.zoom;
  32163. };
  32164. this.reset = function () {
  32165. scope.target.copy( scope.target0 );
  32166. scope.object.position.copy( scope.position0 );
  32167. scope.object.zoom = scope.zoom0;
  32168. scope.object.updateProjectionMatrix();
  32169. scope.dispatchEvent( _changeEvent$1 );
  32170. scope.update();
  32171. state = STATE.NONE;
  32172. };
  32173. // this method is exposed, but perhaps it would be better if we can make it private...
  32174. this.update = function () {
  32175. const offset = new Vector3();
  32176. // so camera.up is the orbit axis
  32177. const quat = new Quaternion().setFromUnitVectors( object.up, new Vector3( 0, 1, 0 ) );
  32178. const quatInverse = quat.clone().invert();
  32179. const lastPosition = new Vector3();
  32180. const lastQuaternion = new Quaternion();
  32181. const twoPI = 2 * Math.PI;
  32182. return function update() {
  32183. const position = scope.object.position;
  32184. offset.copy( position ).sub( scope.target );
  32185. // rotate offset to "y-axis-is-up" space
  32186. offset.applyQuaternion( quat );
  32187. // angle from z-axis around y-axis
  32188. spherical.setFromVector3( offset );
  32189. if ( scope.autoRotate && state === STATE.NONE ) {
  32190. rotateLeft( getAutoRotationAngle() );
  32191. }
  32192. if ( scope.enableDamping ) {
  32193. spherical.theta += sphericalDelta.theta * scope.dampingFactor;
  32194. spherical.phi += sphericalDelta.phi * scope.dampingFactor;
  32195. } else {
  32196. spherical.theta += sphericalDelta.theta;
  32197. spherical.phi += sphericalDelta.phi;
  32198. }
  32199. // restrict theta to be between desired limits
  32200. let min = scope.minAzimuthAngle;
  32201. let max = scope.maxAzimuthAngle;
  32202. if ( isFinite( min ) && isFinite( max ) ) {
  32203. if ( min < - Math.PI ) min += twoPI; else if ( min > Math.PI ) min -= twoPI;
  32204. if ( max < - Math.PI ) max += twoPI; else if ( max > Math.PI ) max -= twoPI;
  32205. if ( min <= max ) {
  32206. spherical.theta = Math.max( min, Math.min( max, spherical.theta ) );
  32207. } else {
  32208. spherical.theta = ( spherical.theta > ( min + max ) / 2 ) ?
  32209. Math.max( min, spherical.theta ) :
  32210. Math.min( max, spherical.theta );
  32211. }
  32212. }
  32213. // restrict phi to be between desired limits
  32214. spherical.phi = Math.max( scope.minPolarAngle, Math.min( scope.maxPolarAngle, spherical.phi ) );
  32215. spherical.makeSafe();
  32216. spherical.radius *= scale;
  32217. // restrict radius to be between desired limits
  32218. spherical.radius = Math.max( scope.minDistance, Math.min( scope.maxDistance, spherical.radius ) );
  32219. // move target to panned location
  32220. if ( scope.enableDamping === true ) {
  32221. scope.target.addScaledVector( panOffset, scope.dampingFactor );
  32222. } else {
  32223. scope.target.add( panOffset );
  32224. }
  32225. offset.setFromSpherical( spherical );
  32226. // rotate offset back to "camera-up-vector-is-up" space
  32227. offset.applyQuaternion( quatInverse );
  32228. position.copy( scope.target ).add( offset );
  32229. scope.object.lookAt( scope.target );
  32230. if ( scope.enableDamping === true ) {
  32231. sphericalDelta.theta *= ( 1 - scope.dampingFactor );
  32232. sphericalDelta.phi *= ( 1 - scope.dampingFactor );
  32233. panOffset.multiplyScalar( 1 - scope.dampingFactor );
  32234. } else {
  32235. sphericalDelta.set( 0, 0, 0 );
  32236. panOffset.set( 0, 0, 0 );
  32237. }
  32238. scale = 1;
  32239. // update condition is:
  32240. // min(camera displacement, camera rotation in radians)^2 > EPS
  32241. // using small-angle approximation cos(x/2) = 1 - x^2 / 8
  32242. if ( zoomChanged ||
  32243. lastPosition.distanceToSquared( scope.object.position ) > EPS ||
  32244. 8 * ( 1 - lastQuaternion.dot( scope.object.quaternion ) ) > EPS ) {
  32245. scope.dispatchEvent( _changeEvent$1 );
  32246. lastPosition.copy( scope.object.position );
  32247. lastQuaternion.copy( scope.object.quaternion );
  32248. zoomChanged = false;
  32249. return true;
  32250. }
  32251. return false;
  32252. };
  32253. }();
  32254. this.dispose = function () {
  32255. scope.domElement.removeEventListener( 'contextmenu', onContextMenu );
  32256. scope.domElement.removeEventListener( 'pointerdown', onPointerDown );
  32257. scope.domElement.removeEventListener( 'pointercancel', onPointerCancel );
  32258. scope.domElement.removeEventListener( 'wheel', onMouseWheel );
  32259. scope.domElement.ownerDocument.removeEventListener( 'pointermove', onPointerMove );
  32260. scope.domElement.ownerDocument.removeEventListener( 'pointerup', onPointerUp );
  32261. if ( scope._domElementKeyEvents !== null ) {
  32262. scope._domElementKeyEvents.removeEventListener( 'keydown', onKeyDown );
  32263. }
  32264. //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here?
  32265. };
  32266. //
  32267. // internals
  32268. //
  32269. const scope = this;
  32270. const STATE = {
  32271. NONE: - 1,
  32272. ROTATE: 0,
  32273. DOLLY: 1,
  32274. PAN: 2,
  32275. TOUCH_ROTATE: 3,
  32276. TOUCH_PAN: 4,
  32277. TOUCH_DOLLY_PAN: 5,
  32278. TOUCH_DOLLY_ROTATE: 6
  32279. };
  32280. let state = STATE.NONE;
  32281. const EPS = 0.000001;
  32282. // current position in spherical coordinates
  32283. const spherical = new Spherical();
  32284. const sphericalDelta = new Spherical();
  32285. let scale = 1;
  32286. const panOffset = new Vector3();
  32287. let zoomChanged = false;
  32288. const rotateStart = new Vector2();
  32289. const rotateEnd = new Vector2();
  32290. const rotateDelta = new Vector2();
  32291. const panStart = new Vector2();
  32292. const panEnd = new Vector2();
  32293. const panDelta = new Vector2();
  32294. const dollyStart = new Vector2();
  32295. const dollyEnd = new Vector2();
  32296. const dollyDelta = new Vector2();
  32297. const pointers = [];
  32298. const pointerPositions = {};
  32299. function getAutoRotationAngle() {
  32300. return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;
  32301. }
  32302. function getZoomScale() {
  32303. return Math.pow( 0.95, scope.zoomSpeed );
  32304. }
  32305. function rotateLeft( angle ) {
  32306. sphericalDelta.theta -= angle;
  32307. }
  32308. function rotateUp( angle ) {
  32309. sphericalDelta.phi -= angle;
  32310. }
  32311. const panLeft = function () {
  32312. const v = new Vector3();
  32313. return function panLeft( distance, objectMatrix ) {
  32314. v.setFromMatrixColumn( objectMatrix, 0 ); // get X column of objectMatrix
  32315. v.multiplyScalar( - distance );
  32316. panOffset.add( v );
  32317. };
  32318. }();
  32319. const panUp = function () {
  32320. const v = new Vector3();
  32321. return function panUp( distance, objectMatrix ) {
  32322. if ( scope.screenSpacePanning === true ) {
  32323. v.setFromMatrixColumn( objectMatrix, 1 );
  32324. } else {
  32325. v.setFromMatrixColumn( objectMatrix, 0 );
  32326. v.crossVectors( scope.object.up, v );
  32327. }
  32328. v.multiplyScalar( distance );
  32329. panOffset.add( v );
  32330. };
  32331. }();
  32332. // deltaX and deltaY are in pixels; right and down are positive
  32333. const pan = function () {
  32334. const offset = new Vector3();
  32335. return function pan( deltaX, deltaY ) {
  32336. const element = scope.domElement;
  32337. if ( scope.object.isPerspectiveCamera ) {
  32338. // perspective
  32339. const position = scope.object.position;
  32340. offset.copy( position ).sub( scope.target );
  32341. let targetDistance = offset.length();
  32342. // half of the fov is center to top of screen
  32343. targetDistance *= Math.tan( ( scope.object.fov / 2 ) * Math.PI / 180.0 );
  32344. // we use only clientHeight here so aspect ratio does not distort speed
  32345. panLeft( 2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix );
  32346. panUp( 2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix );
  32347. } else if ( scope.object.isOrthographicCamera ) {
  32348. // orthographic
  32349. panLeft( deltaX * ( scope.object.right - scope.object.left ) / scope.object.zoom / element.clientWidth, scope.object.matrix );
  32350. panUp( deltaY * ( scope.object.top - scope.object.bottom ) / scope.object.zoom / element.clientHeight, scope.object.matrix );
  32351. } else {
  32352. // camera neither orthographic nor perspective
  32353. console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' );
  32354. scope.enablePan = false;
  32355. }
  32356. };
  32357. }();
  32358. function dollyOut( dollyScale ) {
  32359. if ( scope.object.isPerspectiveCamera ) {
  32360. scale /= dollyScale;
  32361. } else if ( scope.object.isOrthographicCamera ) {
  32362. scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom * dollyScale ) );
  32363. scope.object.updateProjectionMatrix();
  32364. zoomChanged = true;
  32365. } else {
  32366. console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' );
  32367. scope.enableZoom = false;
  32368. }
  32369. }
  32370. function dollyIn( dollyScale ) {
  32371. if ( scope.object.isPerspectiveCamera ) {
  32372. scale *= dollyScale;
  32373. } else if ( scope.object.isOrthographicCamera ) {
  32374. scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom / dollyScale ) );
  32375. scope.object.updateProjectionMatrix();
  32376. zoomChanged = true;
  32377. } else {
  32378. console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' );
  32379. scope.enableZoom = false;
  32380. }
  32381. }
  32382. //
  32383. // event callbacks - update the object state
  32384. //
  32385. function handleMouseDownRotate( event ) {
  32386. rotateStart.set( event.clientX, event.clientY );
  32387. }
  32388. function handleMouseDownDolly( event ) {
  32389. dollyStart.set( event.clientX, event.clientY );
  32390. }
  32391. function handleMouseDownPan( event ) {
  32392. panStart.set( event.clientX, event.clientY );
  32393. }
  32394. function handleMouseMoveRotate( event ) {
  32395. rotateEnd.set( event.clientX, event.clientY );
  32396. rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed );
  32397. const element = scope.domElement;
  32398. rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height
  32399. rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight );
  32400. rotateStart.copy( rotateEnd );
  32401. scope.update();
  32402. }
  32403. function handleMouseMoveDolly( event ) {
  32404. dollyEnd.set( event.clientX, event.clientY );
  32405. dollyDelta.subVectors( dollyEnd, dollyStart );
  32406. if ( dollyDelta.y > 0 ) {
  32407. dollyOut( getZoomScale() );
  32408. } else if ( dollyDelta.y < 0 ) {
  32409. dollyIn( getZoomScale() );
  32410. }
  32411. dollyStart.copy( dollyEnd );
  32412. scope.update();
  32413. }
  32414. function handleMouseMovePan( event ) {
  32415. panEnd.set( event.clientX, event.clientY );
  32416. panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed );
  32417. pan( panDelta.x, panDelta.y );
  32418. panStart.copy( panEnd );
  32419. scope.update();
  32420. }
  32421. function handleMouseWheel( event ) {
  32422. if ( event.deltaY < 0 ) {
  32423. dollyIn( getZoomScale() );
  32424. } else if ( event.deltaY > 0 ) {
  32425. dollyOut( getZoomScale() );
  32426. }
  32427. scope.update();
  32428. }
  32429. function handleKeyDown( event ) {
  32430. let needsUpdate = false;
  32431. switch ( event.code ) {
  32432. case scope.keys.UP:
  32433. pan( 0, scope.keyPanSpeed );
  32434. needsUpdate = true;
  32435. break;
  32436. case scope.keys.BOTTOM:
  32437. pan( 0, - scope.keyPanSpeed );
  32438. needsUpdate = true;
  32439. break;
  32440. case scope.keys.LEFT:
  32441. pan( scope.keyPanSpeed, 0 );
  32442. needsUpdate = true;
  32443. break;
  32444. case scope.keys.RIGHT:
  32445. pan( - scope.keyPanSpeed, 0 );
  32446. needsUpdate = true;
  32447. break;
  32448. }
  32449. if ( needsUpdate ) {
  32450. // prevent the browser from scrolling on cursor keys
  32451. event.preventDefault();
  32452. scope.update();
  32453. }
  32454. }
  32455. function handleTouchStartRotate() {
  32456. if ( pointers.length === 1 ) {
  32457. rotateStart.set( pointers[ 0 ].pageX, pointers[ 0 ].pageY );
  32458. } else {
  32459. const x = 0.5 * ( pointers[ 0 ].pageX + pointers[ 1 ].pageX );
  32460. const y = 0.5 * ( pointers[ 0 ].pageY + pointers[ 1 ].pageY );
  32461. rotateStart.set( x, y );
  32462. }
  32463. }
  32464. function handleTouchStartPan() {
  32465. if ( pointers.length === 1 ) {
  32466. panStart.set( pointers[ 0 ].pageX, pointers[ 0 ].pageY );
  32467. } else {
  32468. const x = 0.5 * ( pointers[ 0 ].pageX + pointers[ 1 ].pageX );
  32469. const y = 0.5 * ( pointers[ 0 ].pageY + pointers[ 1 ].pageY );
  32470. panStart.set( x, y );
  32471. }
  32472. }
  32473. function handleTouchStartDolly() {
  32474. const dx = pointers[ 0 ].pageX - pointers[ 1 ].pageX;
  32475. const dy = pointers[ 0 ].pageY - pointers[ 1 ].pageY;
  32476. const distance = Math.sqrt( dx * dx + dy * dy );
  32477. dollyStart.set( 0, distance );
  32478. }
  32479. function handleTouchStartDollyPan() {
  32480. if ( scope.enableZoom ) handleTouchStartDolly();
  32481. if ( scope.enablePan ) handleTouchStartPan();
  32482. }
  32483. function handleTouchStartDollyRotate() {
  32484. if ( scope.enableZoom ) handleTouchStartDolly();
  32485. if ( scope.enableRotate ) handleTouchStartRotate();
  32486. }
  32487. function handleTouchMoveRotate( event ) {
  32488. if ( pointers.length == 1 ) {
  32489. rotateEnd.set( event.pageX, event.pageY );
  32490. } else {
  32491. const position = getSecondPointerPosition( event );
  32492. const x = 0.5 * ( event.pageX + position.x );
  32493. const y = 0.5 * ( event.pageY + position.y );
  32494. rotateEnd.set( x, y );
  32495. }
  32496. rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed );
  32497. const element = scope.domElement;
  32498. rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height
  32499. rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight );
  32500. rotateStart.copy( rotateEnd );
  32501. }
  32502. function handleTouchMovePan( event ) {
  32503. if ( pointers.length === 1 ) {
  32504. panEnd.set( event.pageX, event.pageY );
  32505. } else {
  32506. const position = getSecondPointerPosition( event );
  32507. const x = 0.5 * ( event.pageX + position.x );
  32508. const y = 0.5 * ( event.pageY + position.y );
  32509. panEnd.set( x, y );
  32510. }
  32511. panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed );
  32512. pan( panDelta.x, panDelta.y );
  32513. panStart.copy( panEnd );
  32514. }
  32515. function handleTouchMoveDolly( event ) {
  32516. const position = getSecondPointerPosition( event );
  32517. const dx = event.pageX - position.x;
  32518. const dy = event.pageY - position.y;
  32519. const distance = Math.sqrt( dx * dx + dy * dy );
  32520. dollyEnd.set( 0, distance );
  32521. dollyDelta.set( 0, Math.pow( dollyEnd.y / dollyStart.y, scope.zoomSpeed ) );
  32522. dollyOut( dollyDelta.y );
  32523. dollyStart.copy( dollyEnd );
  32524. }
  32525. function handleTouchMoveDollyPan( event ) {
  32526. if ( scope.enableZoom ) handleTouchMoveDolly( event );
  32527. if ( scope.enablePan ) handleTouchMovePan( event );
  32528. }
  32529. function handleTouchMoveDollyRotate( event ) {
  32530. if ( scope.enableZoom ) handleTouchMoveDolly( event );
  32531. if ( scope.enableRotate ) handleTouchMoveRotate( event );
  32532. }
  32533. //
  32534. // event handlers - FSM: listen for events and reset state
  32535. //
  32536. function onPointerDown( event ) {
  32537. if ( scope.enabled === false ) return;
  32538. if ( pointers.length === 0 ) {
  32539. scope.domElement.ownerDocument.addEventListener( 'pointermove', onPointerMove );
  32540. scope.domElement.ownerDocument.addEventListener( 'pointerup', onPointerUp );
  32541. }
  32542. //
  32543. addPointer( event );
  32544. if ( event.pointerType === 'touch' ) {
  32545. onTouchStart( event );
  32546. } else {
  32547. onMouseDown( event );
  32548. }
  32549. }
  32550. function onPointerMove( event ) {
  32551. if ( scope.enabled === false ) return;
  32552. if ( event.pointerType === 'touch' ) {
  32553. onTouchMove( event );
  32554. } else {
  32555. onMouseMove( event );
  32556. }
  32557. }
  32558. function onPointerUp( event ) {
  32559. if ( scope.enabled === false ) return;
  32560. if ( event.pointerType === 'touch' ) {
  32561. onTouchEnd();
  32562. } else {
  32563. onMouseUp();
  32564. }
  32565. removePointer( event );
  32566. //
  32567. if ( pointers.length === 0 ) {
  32568. scope.domElement.ownerDocument.removeEventListener( 'pointermove', onPointerMove );
  32569. scope.domElement.ownerDocument.removeEventListener( 'pointerup', onPointerUp );
  32570. }
  32571. }
  32572. function onPointerCancel( event ) {
  32573. removePointer( event );
  32574. }
  32575. function onMouseDown( event ) {
  32576. let mouseAction;
  32577. switch ( event.button ) {
  32578. case 0:
  32579. mouseAction = scope.mouseButtons.LEFT;
  32580. break;
  32581. case 1:
  32582. mouseAction = scope.mouseButtons.MIDDLE;
  32583. break;
  32584. case 2:
  32585. mouseAction = scope.mouseButtons.RIGHT;
  32586. break;
  32587. default:
  32588. mouseAction = - 1;
  32589. }
  32590. switch ( mouseAction ) {
  32591. case MOUSE.DOLLY:
  32592. if ( scope.enableZoom === false ) return;
  32593. handleMouseDownDolly( event );
  32594. state = STATE.DOLLY;
  32595. break;
  32596. case MOUSE.ROTATE:
  32597. if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
  32598. if ( scope.enablePan === false ) return;
  32599. handleMouseDownPan( event );
  32600. state = STATE.PAN;
  32601. } else {
  32602. if ( scope.enableRotate === false ) return;
  32603. handleMouseDownRotate( event );
  32604. state = STATE.ROTATE;
  32605. }
  32606. break;
  32607. case MOUSE.PAN:
  32608. if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
  32609. if ( scope.enableRotate === false ) return;
  32610. handleMouseDownRotate( event );
  32611. state = STATE.ROTATE;
  32612. } else {
  32613. if ( scope.enablePan === false ) return;
  32614. handleMouseDownPan( event );
  32615. state = STATE.PAN;
  32616. }
  32617. break;
  32618. default:
  32619. state = STATE.NONE;
  32620. }
  32621. if ( state !== STATE.NONE ) {
  32622. scope.dispatchEvent( _startEvent );
  32623. }
  32624. }
  32625. function onMouseMove( event ) {
  32626. if ( scope.enabled === false ) return;
  32627. switch ( state ) {
  32628. case STATE.ROTATE:
  32629. if ( scope.enableRotate === false ) return;
  32630. handleMouseMoveRotate( event );
  32631. break;
  32632. case STATE.DOLLY:
  32633. if ( scope.enableZoom === false ) return;
  32634. handleMouseMoveDolly( event );
  32635. break;
  32636. case STATE.PAN:
  32637. if ( scope.enablePan === false ) return;
  32638. handleMouseMovePan( event );
  32639. break;
  32640. }
  32641. }
  32642. function onMouseUp( event ) {
  32643. scope.dispatchEvent( _endEvent );
  32644. state = STATE.NONE;
  32645. }
  32646. function onMouseWheel( event ) {
  32647. if ( scope.enabled === false || scope.enableZoom === false || ( state !== STATE.NONE && state !== STATE.ROTATE ) ) return;
  32648. event.preventDefault();
  32649. scope.dispatchEvent( _startEvent );
  32650. handleMouseWheel( event );
  32651. scope.dispatchEvent( _endEvent );
  32652. }
  32653. function onKeyDown( event ) {
  32654. if ( scope.enabled === false || scope.enablePan === false ) return;
  32655. handleKeyDown( event );
  32656. }
  32657. function onTouchStart( event ) {
  32658. trackPointer( event );
  32659. switch ( pointers.length ) {
  32660. case 1:
  32661. switch ( scope.touches.ONE ) {
  32662. case TOUCH.ROTATE:
  32663. if ( scope.enableRotate === false ) return;
  32664. handleTouchStartRotate();
  32665. state = STATE.TOUCH_ROTATE;
  32666. break;
  32667. case TOUCH.PAN:
  32668. if ( scope.enablePan === false ) return;
  32669. handleTouchStartPan();
  32670. state = STATE.TOUCH_PAN;
  32671. break;
  32672. default:
  32673. state = STATE.NONE;
  32674. }
  32675. break;
  32676. case 2:
  32677. switch ( scope.touches.TWO ) {
  32678. case TOUCH.DOLLY_PAN:
  32679. if ( scope.enableZoom === false && scope.enablePan === false ) return;
  32680. handleTouchStartDollyPan();
  32681. state = STATE.TOUCH_DOLLY_PAN;
  32682. break;
  32683. case TOUCH.DOLLY_ROTATE:
  32684. if ( scope.enableZoom === false && scope.enableRotate === false ) return;
  32685. handleTouchStartDollyRotate();
  32686. state = STATE.TOUCH_DOLLY_ROTATE;
  32687. break;
  32688. default:
  32689. state = STATE.NONE;
  32690. }
  32691. break;
  32692. default:
  32693. state = STATE.NONE;
  32694. }
  32695. if ( state !== STATE.NONE ) {
  32696. scope.dispatchEvent( _startEvent );
  32697. }
  32698. }
  32699. function onTouchMove( event ) {
  32700. trackPointer( event );
  32701. switch ( state ) {
  32702. case STATE.TOUCH_ROTATE:
  32703. if ( scope.enableRotate === false ) return;
  32704. handleTouchMoveRotate( event );
  32705. scope.update();
  32706. break;
  32707. case STATE.TOUCH_PAN:
  32708. if ( scope.enablePan === false ) return;
  32709. handleTouchMovePan( event );
  32710. scope.update();
  32711. break;
  32712. case STATE.TOUCH_DOLLY_PAN:
  32713. if ( scope.enableZoom === false && scope.enablePan === false ) return;
  32714. handleTouchMoveDollyPan( event );
  32715. scope.update();
  32716. break;
  32717. case STATE.TOUCH_DOLLY_ROTATE:
  32718. if ( scope.enableZoom === false && scope.enableRotate === false ) return;
  32719. handleTouchMoveDollyRotate( event );
  32720. scope.update();
  32721. break;
  32722. default:
  32723. state = STATE.NONE;
  32724. }
  32725. }
  32726. function onTouchEnd( event ) {
  32727. scope.dispatchEvent( _endEvent );
  32728. state = STATE.NONE;
  32729. }
  32730. function onContextMenu( event ) {
  32731. if ( scope.enabled === false ) return;
  32732. event.preventDefault();
  32733. }
  32734. function addPointer( event ) {
  32735. pointers.push( event );
  32736. }
  32737. function removePointer( event ) {
  32738. delete pointerPositions[ event.pointerId ];
  32739. for ( let i = 0; i < pointers.length; i ++ ) {
  32740. if ( pointers[ i ].pointerId == event.pointerId ) {
  32741. pointers.splice( i, 1 );
  32742. return;
  32743. }
  32744. }
  32745. }
  32746. function trackPointer( event ) {
  32747. let position = pointerPositions[ event.pointerId ];
  32748. if ( position === undefined ) {
  32749. position = new Vector2();
  32750. pointerPositions[ event.pointerId ] = position;
  32751. }
  32752. position.set( event.pageX, event.pageY );
  32753. }
  32754. function getSecondPointerPosition( event ) {
  32755. const pointer = ( event.pointerId === pointers[ 0 ].pointerId ) ? pointers[ 1 ] : pointers[ 0 ];
  32756. return pointerPositions[ pointer.pointerId ];
  32757. }
  32758. //
  32759. scope.domElement.addEventListener( 'contextmenu', onContextMenu );
  32760. scope.domElement.addEventListener( 'pointerdown', onPointerDown );
  32761. scope.domElement.addEventListener( 'pointercancel', onPointerCancel );
  32762. scope.domElement.addEventListener( 'wheel', onMouseWheel, { passive: false } );
  32763. // force an update at start
  32764. this.update();
  32765. }
  32766. }
  32767. const _changeEvent = { type: 'change' };
  32768. class FlyControls extends EventDispatcher {
  32769. constructor( object, domElement ) {
  32770. super();
  32771. if ( domElement === undefined ) {
  32772. console.warn( 'THREE.FlyControls: The second parameter "domElement" is now mandatory.' );
  32773. domElement = document;
  32774. }
  32775. this.object = object;
  32776. this.domElement = domElement;
  32777. // API
  32778. this.movementSpeed = 1.0;
  32779. this.rollSpeed = 0.005;
  32780. this.dragToLook = false;
  32781. this.autoForward = false;
  32782. // disable default target object behavior
  32783. // internals
  32784. const scope = this;
  32785. const EPS = 0.000001;
  32786. const lastQuaternion = new Quaternion();
  32787. const lastPosition = new Vector3();
  32788. this.tmpQuaternion = new Quaternion();
  32789. this.mouseStatus = 0;
  32790. this.moveState = { up: 0, down: 0, left: 0, right: 0, forward: 0, back: 0, pitchUp: 0, pitchDown: 0, yawLeft: 0, yawRight: 0, rollLeft: 0, rollRight: 0 };
  32791. this.moveVector = new Vector3( 0, 0, 0 );
  32792. this.rotationVector = new Vector3( 0, 0, 0 );
  32793. this.keydown = function ( event ) {
  32794. if ( event.altKey ) {
  32795. return;
  32796. }
  32797. switch ( event.code ) {
  32798. case 'ShiftLeft':
  32799. case 'ShiftRight': this.movementSpeedMultiplier = .1; break;
  32800. case 'KeyW': this.moveState.forward = 1; break;
  32801. case 'KeyS': this.moveState.back = 1; break;
  32802. case 'KeyA': this.moveState.left = 1; break;
  32803. case 'KeyD': this.moveState.right = 1; break;
  32804. case 'KeyR': this.moveState.up = 1; break;
  32805. case 'KeyF': this.moveState.down = 1; break;
  32806. case 'ArrowUp': this.moveState.pitchUp = 1; break;
  32807. case 'ArrowDown': this.moveState.pitchDown = 1; break;
  32808. case 'ArrowLeft': this.moveState.yawLeft = 1; break;
  32809. case 'ArrowRight': this.moveState.yawRight = 1; break;
  32810. case 'KeyQ': this.moveState.rollLeft = 1; break;
  32811. case 'KeyE': this.moveState.rollRight = 1; break;
  32812. }
  32813. this.updateMovementVector();
  32814. this.updateRotationVector();
  32815. };
  32816. this.keyup = function ( event ) {
  32817. switch ( event.code ) {
  32818. case 'ShiftLeft':
  32819. case 'ShiftRight': this.movementSpeedMultiplier = 1; break;
  32820. case 'KeyW': this.moveState.forward = 0; break;
  32821. case 'KeyS': this.moveState.back = 0; break;
  32822. case 'KeyA': this.moveState.left = 0; break;
  32823. case 'KeyD': this.moveState.right = 0; break;
  32824. case 'KeyR': this.moveState.up = 0; break;
  32825. case 'KeyF': this.moveState.down = 0; break;
  32826. case 'ArrowUp': this.moveState.pitchUp = 0; break;
  32827. case 'ArrowDown': this.moveState.pitchDown = 0; break;
  32828. case 'ArrowLeft': this.moveState.yawLeft = 0; break;
  32829. case 'ArrowRight': this.moveState.yawRight = 0; break;
  32830. case 'KeyQ': this.moveState.rollLeft = 0; break;
  32831. case 'KeyE': this.moveState.rollRight = 0; break;
  32832. }
  32833. this.updateMovementVector();
  32834. this.updateRotationVector();
  32835. };
  32836. this.mousedown = function ( event ) {
  32837. if ( this.dragToLook ) {
  32838. this.mouseStatus ++;
  32839. } else {
  32840. switch ( event.button ) {
  32841. case 0: this.moveState.forward = 1; break;
  32842. case 2: this.moveState.back = 1; break;
  32843. }
  32844. this.updateMovementVector();
  32845. }
  32846. };
  32847. this.mousemove = function ( event ) {
  32848. if ( ! this.dragToLook || this.mouseStatus > 0 ) {
  32849. const container = this.getContainerDimensions();
  32850. const halfWidth = container.size[ 0 ] / 2;
  32851. const halfHeight = container.size[ 1 ] / 2;
  32852. this.moveState.yawLeft = - ( ( event.pageX - container.offset[ 0 ] ) - halfWidth ) / halfWidth;
  32853. this.moveState.pitchDown = ( ( event.pageY - container.offset[ 1 ] ) - halfHeight ) / halfHeight;
  32854. this.updateRotationVector();
  32855. }
  32856. };
  32857. this.mouseup = function ( event ) {
  32858. if ( this.dragToLook ) {
  32859. this.mouseStatus --;
  32860. this.moveState.yawLeft = this.moveState.pitchDown = 0;
  32861. } else {
  32862. switch ( event.button ) {
  32863. case 0: this.moveState.forward = 0; break;
  32864. case 2: this.moveState.back = 0; break;
  32865. }
  32866. this.updateMovementVector();
  32867. }
  32868. this.updateRotationVector();
  32869. };
  32870. this.update = function ( delta ) {
  32871. const moveMult = delta * scope.movementSpeed;
  32872. const rotMult = delta * scope.rollSpeed;
  32873. scope.object.translateX( scope.moveVector.x * moveMult );
  32874. scope.object.translateY( scope.moveVector.y * moveMult );
  32875. scope.object.translateZ( scope.moveVector.z * moveMult );
  32876. scope.tmpQuaternion.set( scope.rotationVector.x * rotMult, scope.rotationVector.y * rotMult, scope.rotationVector.z * rotMult, 1 ).normalize();
  32877. scope.object.quaternion.multiply( scope.tmpQuaternion );
  32878. if (
  32879. lastPosition.distanceToSquared( scope.object.position ) > EPS ||
  32880. 8 * ( 1 - lastQuaternion.dot( scope.object.quaternion ) ) > EPS
  32881. ) {
  32882. scope.dispatchEvent( _changeEvent );
  32883. lastQuaternion.copy( scope.object.quaternion );
  32884. lastPosition.copy( scope.object.position );
  32885. }
  32886. };
  32887. this.updateMovementVector = function () {
  32888. const forward = ( this.moveState.forward || ( this.autoForward && ! this.moveState.back ) ) ? 1 : 0;
  32889. this.moveVector.x = ( - this.moveState.left + this.moveState.right );
  32890. this.moveVector.y = ( - this.moveState.down + this.moveState.up );
  32891. this.moveVector.z = ( - forward + this.moveState.back );
  32892. //console.log( 'move:', [ this.moveVector.x, this.moveVector.y, this.moveVector.z ] );
  32893. };
  32894. this.updateRotationVector = function () {
  32895. this.rotationVector.x = ( - this.moveState.pitchDown + this.moveState.pitchUp );
  32896. this.rotationVector.y = ( - this.moveState.yawRight + this.moveState.yawLeft );
  32897. this.rotationVector.z = ( - this.moveState.rollRight + this.moveState.rollLeft );
  32898. //console.log( 'rotate:', [ this.rotationVector.x, this.rotationVector.y, this.rotationVector.z ] );
  32899. };
  32900. this.getContainerDimensions = function () {
  32901. if ( this.domElement != document ) {
  32902. return {
  32903. size: [ this.domElement.offsetWidth, this.domElement.offsetHeight ],
  32904. offset: [ this.domElement.offsetLeft, this.domElement.offsetTop ]
  32905. };
  32906. } else {
  32907. return {
  32908. size: [ window.innerWidth, window.innerHeight ],
  32909. offset: [ 0, 0 ]
  32910. };
  32911. }
  32912. };
  32913. this.dispose = function () {
  32914. this.domElement.removeEventListener( 'contextmenu', contextmenu );
  32915. this.domElement.removeEventListener( 'mousedown', _mousedown );
  32916. this.domElement.removeEventListener( 'mousemove', _mousemove );
  32917. this.domElement.removeEventListener( 'mouseup', _mouseup );
  32918. window.removeEventListener( 'keydown', _keydown );
  32919. window.removeEventListener( 'keyup', _keyup );
  32920. };
  32921. const _mousemove = this.mousemove.bind( this );
  32922. const _mousedown = this.mousedown.bind( this );
  32923. const _mouseup = this.mouseup.bind( this );
  32924. const _keydown = this.keydown.bind( this );
  32925. const _keyup = this.keyup.bind( this );
  32926. this.domElement.addEventListener( 'contextmenu', contextmenu );
  32927. this.domElement.addEventListener( 'mousemove', _mousemove );
  32928. this.domElement.addEventListener( 'mousedown', _mousedown );
  32929. this.domElement.addEventListener( 'mouseup', _mouseup );
  32930. window.addEventListener( 'keydown', _keydown );
  32931. window.addEventListener( 'keyup', _keyup );
  32932. this.updateMovementVector();
  32933. this.updateRotationVector();
  32934. }
  32935. }
  32936. function contextmenu( event ) {
  32937. event.preventDefault();
  32938. }
  32939. /**
  32940. * Full-screen textured quad shader
  32941. */
  32942. var CopyShader = {
  32943. uniforms: {
  32944. 'tDiffuse': { value: null },
  32945. 'opacity': { value: 1.0 }
  32946. },
  32947. vertexShader: /* glsl */`
  32948. varying vec2 vUv;
  32949. void main() {
  32950. vUv = uv;
  32951. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  32952. }`,
  32953. fragmentShader: /* glsl */`
  32954. uniform float opacity;
  32955. uniform sampler2D tDiffuse;
  32956. varying vec2 vUv;
  32957. void main() {
  32958. vec4 texel = texture2D( tDiffuse, vUv );
  32959. gl_FragColor = opacity * texel;
  32960. }`
  32961. };
  32962. class Pass {
  32963. constructor() {
  32964. // if set to true, the pass is processed by the composer
  32965. this.enabled = true;
  32966. // if set to true, the pass indicates to swap read and write buffer after rendering
  32967. this.needsSwap = true;
  32968. // if set to true, the pass clears its buffer before rendering
  32969. this.clear = false;
  32970. // if set to true, the result of the pass is rendered to screen. This is set automatically by EffectComposer.
  32971. this.renderToScreen = false;
  32972. }
  32973. setSize( /* width, height */ ) {}
  32974. render( /* renderer, writeBuffer, readBuffer, deltaTime, maskActive */ ) {
  32975. console.error( 'THREE.Pass: .render() must be implemented in derived pass.' );
  32976. }
  32977. }
  32978. // Helper for passes that need to fill the viewport with a single quad.
  32979. const _camera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  32980. // https://github.com/mrdoob/three.js/pull/21358
  32981. const _geometry$1 = new BufferGeometry();
  32982. _geometry$1.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
  32983. _geometry$1.setAttribute( 'uv', new Float32BufferAttribute( [ 0, 2, 0, 0, 2, 0 ], 2 ) );
  32984. class FullScreenQuad {
  32985. constructor( material ) {
  32986. this._mesh = new Mesh( _geometry$1, material );
  32987. }
  32988. dispose() {
  32989. this._mesh.geometry.dispose();
  32990. }
  32991. render( renderer ) {
  32992. renderer.render( this._mesh, _camera );
  32993. }
  32994. get material() {
  32995. return this._mesh.material;
  32996. }
  32997. set material( value ) {
  32998. this._mesh.material = value;
  32999. }
  33000. }
  33001. class ShaderPass extends Pass {
  33002. constructor( shader, textureID ) {
  33003. super();
  33004. this.textureID = ( textureID !== undefined ) ? textureID : 'tDiffuse';
  33005. if ( shader instanceof ShaderMaterial ) {
  33006. this.uniforms = shader.uniforms;
  33007. this.material = shader;
  33008. } else if ( shader ) {
  33009. this.uniforms = UniformsUtils.clone( shader.uniforms );
  33010. this.material = new ShaderMaterial( {
  33011. defines: Object.assign( {}, shader.defines ),
  33012. uniforms: this.uniforms,
  33013. vertexShader: shader.vertexShader,
  33014. fragmentShader: shader.fragmentShader
  33015. } );
  33016. }
  33017. this.fsQuad = new FullScreenQuad( this.material );
  33018. }
  33019. render( renderer, writeBuffer, readBuffer /*, deltaTime, maskActive */ ) {
  33020. if ( this.uniforms[ this.textureID ] ) {
  33021. this.uniforms[ this.textureID ].value = readBuffer.texture;
  33022. }
  33023. this.fsQuad.material = this.material;
  33024. if ( this.renderToScreen ) {
  33025. renderer.setRenderTarget( null );
  33026. this.fsQuad.render( renderer );
  33027. } else {
  33028. renderer.setRenderTarget( writeBuffer );
  33029. // TODO: Avoid using autoClear properties, see https://github.com/mrdoob/three.js/pull/15571#issuecomment-465669600
  33030. if ( this.clear ) renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  33031. this.fsQuad.render( renderer );
  33032. }
  33033. }
  33034. }
  33035. class MaskPass extends Pass {
  33036. constructor( scene, camera ) {
  33037. super();
  33038. this.scene = scene;
  33039. this.camera = camera;
  33040. this.clear = true;
  33041. this.needsSwap = false;
  33042. this.inverse = false;
  33043. }
  33044. render( renderer, writeBuffer, readBuffer /*, deltaTime, maskActive */ ) {
  33045. const context = renderer.getContext();
  33046. const state = renderer.state;
  33047. // don't update color or depth
  33048. state.buffers.color.setMask( false );
  33049. state.buffers.depth.setMask( false );
  33050. // lock buffers
  33051. state.buffers.color.setLocked( true );
  33052. state.buffers.depth.setLocked( true );
  33053. // set up stencil
  33054. let writeValue, clearValue;
  33055. if ( this.inverse ) {
  33056. writeValue = 0;
  33057. clearValue = 1;
  33058. } else {
  33059. writeValue = 1;
  33060. clearValue = 0;
  33061. }
  33062. state.buffers.stencil.setTest( true );
  33063. state.buffers.stencil.setOp( context.REPLACE, context.REPLACE, context.REPLACE );
  33064. state.buffers.stencil.setFunc( context.ALWAYS, writeValue, 0xffffffff );
  33065. state.buffers.stencil.setClear( clearValue );
  33066. state.buffers.stencil.setLocked( true );
  33067. // draw into the stencil buffer
  33068. renderer.setRenderTarget( readBuffer );
  33069. if ( this.clear ) renderer.clear();
  33070. renderer.render( this.scene, this.camera );
  33071. renderer.setRenderTarget( writeBuffer );
  33072. if ( this.clear ) renderer.clear();
  33073. renderer.render( this.scene, this.camera );
  33074. // unlock color and depth buffer for subsequent rendering
  33075. state.buffers.color.setLocked( false );
  33076. state.buffers.depth.setLocked( false );
  33077. // only render where stencil is set to 1
  33078. state.buffers.stencil.setLocked( false );
  33079. state.buffers.stencil.setFunc( context.EQUAL, 1, 0xffffffff ); // draw if == 1
  33080. state.buffers.stencil.setOp( context.KEEP, context.KEEP, context.KEEP );
  33081. state.buffers.stencil.setLocked( true );
  33082. }
  33083. }
  33084. class ClearMaskPass extends Pass {
  33085. constructor() {
  33086. super();
  33087. this.needsSwap = false;
  33088. }
  33089. render( renderer /*, writeBuffer, readBuffer, deltaTime, maskActive */ ) {
  33090. renderer.state.buffers.stencil.setLocked( false );
  33091. renderer.state.buffers.stencil.setTest( false );
  33092. }
  33093. }
  33094. class EffectComposer {
  33095. constructor( renderer, renderTarget ) {
  33096. this.renderer = renderer;
  33097. if ( renderTarget === undefined ) {
  33098. const parameters = {
  33099. minFilter: LinearFilter,
  33100. magFilter: LinearFilter,
  33101. format: RGBAFormat
  33102. };
  33103. const size = renderer.getSize( new Vector2() );
  33104. this._pixelRatio = renderer.getPixelRatio();
  33105. this._width = size.width;
  33106. this._height = size.height;
  33107. renderTarget = new WebGLRenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, parameters );
  33108. renderTarget.texture.name = 'EffectComposer.rt1';
  33109. } else {
  33110. this._pixelRatio = 1;
  33111. this._width = renderTarget.width;
  33112. this._height = renderTarget.height;
  33113. }
  33114. this.renderTarget1 = renderTarget;
  33115. this.renderTarget2 = renderTarget.clone();
  33116. this.renderTarget2.texture.name = 'EffectComposer.rt2';
  33117. this.writeBuffer = this.renderTarget1;
  33118. this.readBuffer = this.renderTarget2;
  33119. this.renderToScreen = true;
  33120. this.passes = [];
  33121. // dependencies
  33122. if ( CopyShader === undefined ) {
  33123. console.error( 'THREE.EffectComposer relies on CopyShader' );
  33124. }
  33125. if ( ShaderPass === undefined ) {
  33126. console.error( 'THREE.EffectComposer relies on ShaderPass' );
  33127. }
  33128. this.copyPass = new ShaderPass( CopyShader );
  33129. this.clock = new Clock();
  33130. }
  33131. swapBuffers() {
  33132. const tmp = this.readBuffer;
  33133. this.readBuffer = this.writeBuffer;
  33134. this.writeBuffer = tmp;
  33135. }
  33136. addPass( pass ) {
  33137. this.passes.push( pass );
  33138. pass.setSize( this._width * this._pixelRatio, this._height * this._pixelRatio );
  33139. }
  33140. insertPass( pass, index ) {
  33141. this.passes.splice( index, 0, pass );
  33142. pass.setSize( this._width * this._pixelRatio, this._height * this._pixelRatio );
  33143. }
  33144. removePass( pass ) {
  33145. const index = this.passes.indexOf( pass );
  33146. if ( index !== - 1 ) {
  33147. this.passes.splice( index, 1 );
  33148. }
  33149. }
  33150. isLastEnabledPass( passIndex ) {
  33151. for ( let i = passIndex + 1; i < this.passes.length; i ++ ) {
  33152. if ( this.passes[ i ].enabled ) {
  33153. return false;
  33154. }
  33155. }
  33156. return true;
  33157. }
  33158. render( deltaTime ) {
  33159. // deltaTime value is in seconds
  33160. if ( deltaTime === undefined ) {
  33161. deltaTime = this.clock.getDelta();
  33162. }
  33163. const currentRenderTarget = this.renderer.getRenderTarget();
  33164. let maskActive = false;
  33165. for ( let i = 0, il = this.passes.length; i < il; i ++ ) {
  33166. const pass = this.passes[ i ];
  33167. if ( pass.enabled === false ) continue;
  33168. pass.renderToScreen = ( this.renderToScreen && this.isLastEnabledPass( i ) );
  33169. pass.render( this.renderer, this.writeBuffer, this.readBuffer, deltaTime, maskActive );
  33170. if ( pass.needsSwap ) {
  33171. if ( maskActive ) {
  33172. const context = this.renderer.getContext();
  33173. const stencil = this.renderer.state.buffers.stencil;
  33174. //context.stencilFunc( context.NOTEQUAL, 1, 0xffffffff );
  33175. stencil.setFunc( context.NOTEQUAL, 1, 0xffffffff );
  33176. this.copyPass.render( this.renderer, this.writeBuffer, this.readBuffer, deltaTime );
  33177. //context.stencilFunc( context.EQUAL, 1, 0xffffffff );
  33178. stencil.setFunc( context.EQUAL, 1, 0xffffffff );
  33179. }
  33180. this.swapBuffers();
  33181. }
  33182. if ( MaskPass !== undefined ) {
  33183. if ( pass instanceof MaskPass ) {
  33184. maskActive = true;
  33185. } else if ( pass instanceof ClearMaskPass ) {
  33186. maskActive = false;
  33187. }
  33188. }
  33189. }
  33190. this.renderer.setRenderTarget( currentRenderTarget );
  33191. }
  33192. reset( renderTarget ) {
  33193. if ( renderTarget === undefined ) {
  33194. const size = this.renderer.getSize( new Vector2() );
  33195. this._pixelRatio = this.renderer.getPixelRatio();
  33196. this._width = size.width;
  33197. this._height = size.height;
  33198. renderTarget = this.renderTarget1.clone();
  33199. renderTarget.setSize( this._width * this._pixelRatio, this._height * this._pixelRatio );
  33200. }
  33201. this.renderTarget1.dispose();
  33202. this.renderTarget2.dispose();
  33203. this.renderTarget1 = renderTarget;
  33204. this.renderTarget2 = renderTarget.clone();
  33205. this.writeBuffer = this.renderTarget1;
  33206. this.readBuffer = this.renderTarget2;
  33207. }
  33208. setSize( width, height ) {
  33209. this._width = width;
  33210. this._height = height;
  33211. const effectiveWidth = this._width * this._pixelRatio;
  33212. const effectiveHeight = this._height * this._pixelRatio;
  33213. this.renderTarget1.setSize( effectiveWidth, effectiveHeight );
  33214. this.renderTarget2.setSize( effectiveWidth, effectiveHeight );
  33215. for ( let i = 0; i < this.passes.length; i ++ ) {
  33216. this.passes[ i ].setSize( effectiveWidth, effectiveHeight );
  33217. }
  33218. }
  33219. setPixelRatio( pixelRatio ) {
  33220. this._pixelRatio = pixelRatio;
  33221. this.setSize( this._width, this._height );
  33222. }
  33223. }
  33224. // Helper for passes that need to fill the viewport with a single quad.
  33225. new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  33226. // https://github.com/mrdoob/three.js/pull/21358
  33227. const _geometry = new BufferGeometry();
  33228. _geometry.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
  33229. _geometry.setAttribute( 'uv', new Float32BufferAttribute( [ 0, 2, 0, 0, 2, 0 ], 2 ) );
  33230. class RenderPass extends Pass {
  33231. constructor( scene, camera, overrideMaterial, clearColor, clearAlpha ) {
  33232. super();
  33233. this.scene = scene;
  33234. this.camera = camera;
  33235. this.overrideMaterial = overrideMaterial;
  33236. this.clearColor = clearColor;
  33237. this.clearAlpha = ( clearAlpha !== undefined ) ? clearAlpha : 0;
  33238. this.clear = true;
  33239. this.clearDepth = false;
  33240. this.needsSwap = false;
  33241. this._oldClearColor = new Color();
  33242. }
  33243. render( renderer, writeBuffer, readBuffer /*, deltaTime, maskActive */ ) {
  33244. const oldAutoClear = renderer.autoClear;
  33245. renderer.autoClear = false;
  33246. let oldClearAlpha, oldOverrideMaterial;
  33247. if ( this.overrideMaterial !== undefined ) {
  33248. oldOverrideMaterial = this.scene.overrideMaterial;
  33249. this.scene.overrideMaterial = this.overrideMaterial;
  33250. }
  33251. if ( this.clearColor ) {
  33252. renderer.getClearColor( this._oldClearColor );
  33253. oldClearAlpha = renderer.getClearAlpha();
  33254. renderer.setClearColor( this.clearColor, this.clearAlpha );
  33255. }
  33256. if ( this.clearDepth ) {
  33257. renderer.clearDepth();
  33258. }
  33259. renderer.setRenderTarget( this.renderToScreen ? null : readBuffer );
  33260. // TODO: Avoid using autoClear properties, see https://github.com/mrdoob/three.js/pull/15571#issuecomment-465669600
  33261. if ( this.clear ) renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  33262. renderer.render( this.scene, this.camera );
  33263. if ( this.clearColor ) {
  33264. renderer.setClearColor( this._oldClearColor, oldClearAlpha );
  33265. }
  33266. if ( this.overrideMaterial !== undefined ) {
  33267. this.scene.overrideMaterial = oldOverrideMaterial;
  33268. }
  33269. renderer.autoClear = oldAutoClear;
  33270. }
  33271. }
  33272. function _extends() {
  33273. _extends = Object.assign || function (target) {
  33274. for (var i = 1; i < arguments.length; i++) {
  33275. var source = arguments[i];
  33276. for (var key in source) {
  33277. if (Object.prototype.hasOwnProperty.call(source, key)) {
  33278. target[key] = source[key];
  33279. }
  33280. }
  33281. }
  33282. return target;
  33283. };
  33284. return _extends.apply(this, arguments);
  33285. }
  33286. function _assertThisInitialized(self) {
  33287. if (self === void 0) {
  33288. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  33289. }
  33290. return self;
  33291. }
  33292. function _setPrototypeOf(o, p) {
  33293. _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
  33294. o.__proto__ = p;
  33295. return o;
  33296. };
  33297. return _setPrototypeOf(o, p);
  33298. }
  33299. function _inheritsLoose(subClass, superClass) {
  33300. subClass.prototype = Object.create(superClass.prototype);
  33301. subClass.prototype.constructor = subClass;
  33302. _setPrototypeOf(subClass, superClass);
  33303. }
  33304. function _getPrototypeOf(o) {
  33305. _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
  33306. return o.__proto__ || Object.getPrototypeOf(o);
  33307. };
  33308. return _getPrototypeOf(o);
  33309. }
  33310. function _isNativeFunction(fn) {
  33311. return Function.toString.call(fn).indexOf("[native code]") !== -1;
  33312. }
  33313. function _isNativeReflectConstruct() {
  33314. if (typeof Reflect === "undefined" || !Reflect.construct) return false;
  33315. if (Reflect.construct.sham) return false;
  33316. if (typeof Proxy === "function") return true;
  33317. try {
  33318. Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
  33319. return true;
  33320. } catch (e) {
  33321. return false;
  33322. }
  33323. }
  33324. function _construct(Parent, args, Class) {
  33325. if (_isNativeReflectConstruct()) {
  33326. _construct = Reflect.construct;
  33327. } else {
  33328. _construct = function _construct(Parent, args, Class) {
  33329. var a = [null];
  33330. a.push.apply(a, args);
  33331. var Constructor = Function.bind.apply(Parent, a);
  33332. var instance = new Constructor();
  33333. if (Class) _setPrototypeOf(instance, Class.prototype);
  33334. return instance;
  33335. };
  33336. }
  33337. return _construct.apply(null, arguments);
  33338. }
  33339. function _wrapNativeSuper(Class) {
  33340. var _cache = typeof Map === "function" ? new Map() : undefined;
  33341. _wrapNativeSuper = function _wrapNativeSuper(Class) {
  33342. if (Class === null || !_isNativeFunction(Class)) return Class;
  33343. if (typeof Class !== "function") {
  33344. throw new TypeError("Super expression must either be null or a function");
  33345. }
  33346. if (typeof _cache !== "undefined") {
  33347. if (_cache.has(Class)) return _cache.get(Class);
  33348. _cache.set(Class, Wrapper);
  33349. }
  33350. function Wrapper() {
  33351. return _construct(Class, arguments, _getPrototypeOf(this).constructor);
  33352. }
  33353. Wrapper.prototype = Object.create(Class.prototype, {
  33354. constructor: {
  33355. value: Wrapper,
  33356. enumerable: false,
  33357. writable: true,
  33358. configurable: true
  33359. }
  33360. });
  33361. return _setPrototypeOf(Wrapper, Class);
  33362. };
  33363. return _wrapNativeSuper(Class);
  33364. }
  33365. // based on https://github.com/styled-components/styled-components/blob/fcf6f3804c57a14dd7984dfab7bc06ee2edca044/src/utils/error.js
  33366. /**
  33367. * Parse errors.md and turn it into a simple hash of code: message
  33368. * @private
  33369. */
  33370. var ERRORS = {
  33371. "1": "Passed invalid arguments to hsl, please pass multiple numbers e.g. hsl(360, 0.75, 0.4) or an object e.g. rgb({ hue: 255, saturation: 0.4, lightness: 0.75 }).\n\n",
  33372. "2": "Passed invalid arguments to hsla, please pass multiple numbers e.g. hsla(360, 0.75, 0.4, 0.7) or an object e.g. rgb({ hue: 255, saturation: 0.4, lightness: 0.75, alpha: 0.7 }).\n\n",
  33373. "3": "Passed an incorrect argument to a color function, please pass a string representation of a color.\n\n",
  33374. "4": "Couldn't generate valid rgb string from %s, it returned %s.\n\n",
  33375. "5": "Couldn't parse the color string. Please provide the color as a string in hex, rgb, rgba, hsl or hsla notation.\n\n",
  33376. "6": "Passed invalid arguments to rgb, please pass multiple numbers e.g. rgb(255, 205, 100) or an object e.g. rgb({ red: 255, green: 205, blue: 100 }).\n\n",
  33377. "7": "Passed invalid arguments to rgba, please pass multiple numbers e.g. rgb(255, 205, 100, 0.75) or an object e.g. rgb({ red: 255, green: 205, blue: 100, alpha: 0.75 }).\n\n",
  33378. "8": "Passed invalid argument to toColorString, please pass a RgbColor, RgbaColor, HslColor or HslaColor object.\n\n",
  33379. "9": "Please provide a number of steps to the modularScale helper.\n\n",
  33380. "10": "Please pass a number or one of the predefined scales to the modularScale helper as the ratio.\n\n",
  33381. "11": "Invalid value passed as base to modularScale, expected number or em string but got \"%s\"\n\n",
  33382. "12": "Expected a string ending in \"px\" or a number passed as the first argument to %s(), got \"%s\" instead.\n\n",
  33383. "13": "Expected a string ending in \"px\" or a number passed as the second argument to %s(), got \"%s\" instead.\n\n",
  33384. "14": "Passed invalid pixel value (\"%s\") to %s(), please pass a value like \"12px\" or 12.\n\n",
  33385. "15": "Passed invalid base value (\"%s\") to %s(), please pass a value like \"12px\" or 12.\n\n",
  33386. "16": "You must provide a template to this method.\n\n",
  33387. "17": "You passed an unsupported selector state to this method.\n\n",
  33388. "18": "minScreen and maxScreen must be provided as stringified numbers with the same units.\n\n",
  33389. "19": "fromSize and toSize must be provided as stringified numbers with the same units.\n\n",
  33390. "20": "expects either an array of objects or a single object with the properties prop, fromSize, and toSize.\n\n",
  33391. "21": "expects the objects in the first argument array to have the properties `prop`, `fromSize`, and `toSize`.\n\n",
  33392. "22": "expects the first argument object to have the properties `prop`, `fromSize`, and `toSize`.\n\n",
  33393. "23": "fontFace expects a name of a font-family.\n\n",
  33394. "24": "fontFace expects either the path to the font file(s) or a name of a local copy.\n\n",
  33395. "25": "fontFace expects localFonts to be an array.\n\n",
  33396. "26": "fontFace expects fileFormats to be an array.\n\n",
  33397. "27": "radialGradient requries at least 2 color-stops to properly render.\n\n",
  33398. "28": "Please supply a filename to retinaImage() as the first argument.\n\n",
  33399. "29": "Passed invalid argument to triangle, please pass correct pointingDirection e.g. 'right'.\n\n",
  33400. "30": "Passed an invalid value to `height` or `width`. Please provide a pixel based unit.\n\n",
  33401. "31": "The animation shorthand only takes 8 arguments. See the specification for more information: http://mdn.io/animation\n\n",
  33402. "32": "To pass multiple animations please supply them in arrays, e.g. animation(['rotate', '2s'], ['move', '1s'])\nTo pass a single animation please supply them in simple values, e.g. animation('rotate', '2s')\n\n",
  33403. "33": "The animation shorthand arrays can only have 8 elements. See the specification for more information: http://mdn.io/animation\n\n",
  33404. "34": "borderRadius expects a radius value as a string or number as the second argument.\n\n",
  33405. "35": "borderRadius expects one of \"top\", \"bottom\", \"left\" or \"right\" as the first argument.\n\n",
  33406. "36": "Property must be a string value.\n\n",
  33407. "37": "Syntax Error at %s.\n\n",
  33408. "38": "Formula contains a function that needs parentheses at %s.\n\n",
  33409. "39": "Formula is missing closing parenthesis at %s.\n\n",
  33410. "40": "Formula has too many closing parentheses at %s.\n\n",
  33411. "41": "All values in a formula must have the same unit or be unitless.\n\n",
  33412. "42": "Please provide a number of steps to the modularScale helper.\n\n",
  33413. "43": "Please pass a number or one of the predefined scales to the modularScale helper as the ratio.\n\n",
  33414. "44": "Invalid value passed as base to modularScale, expected number or em/rem string but got %s.\n\n",
  33415. "45": "Passed invalid argument to hslToColorString, please pass a HslColor or HslaColor object.\n\n",
  33416. "46": "Passed invalid argument to rgbToColorString, please pass a RgbColor or RgbaColor object.\n\n",
  33417. "47": "minScreen and maxScreen must be provided as stringified numbers with the same units.\n\n",
  33418. "48": "fromSize and toSize must be provided as stringified numbers with the same units.\n\n",
  33419. "49": "Expects either an array of objects or a single object with the properties prop, fromSize, and toSize.\n\n",
  33420. "50": "Expects the objects in the first argument array to have the properties prop, fromSize, and toSize.\n\n",
  33421. "51": "Expects the first argument object to have the properties prop, fromSize, and toSize.\n\n",
  33422. "52": "fontFace expects either the path to the font file(s) or a name of a local copy.\n\n",
  33423. "53": "fontFace expects localFonts to be an array.\n\n",
  33424. "54": "fontFace expects fileFormats to be an array.\n\n",
  33425. "55": "fontFace expects a name of a font-family.\n\n",
  33426. "56": "linearGradient requries at least 2 color-stops to properly render.\n\n",
  33427. "57": "radialGradient requries at least 2 color-stops to properly render.\n\n",
  33428. "58": "Please supply a filename to retinaImage() as the first argument.\n\n",
  33429. "59": "Passed invalid argument to triangle, please pass correct pointingDirection e.g. 'right'.\n\n",
  33430. "60": "Passed an invalid value to `height` or `width`. Please provide a pixel based unit.\n\n",
  33431. "61": "Property must be a string value.\n\n",
  33432. "62": "borderRadius expects a radius value as a string or number as the second argument.\n\n",
  33433. "63": "borderRadius expects one of \"top\", \"bottom\", \"left\" or \"right\" as the first argument.\n\n",
  33434. "64": "The animation shorthand only takes 8 arguments. See the specification for more information: http://mdn.io/animation.\n\n",
  33435. "65": "To pass multiple animations please supply them in arrays, e.g. animation(['rotate', '2s'], ['move', '1s'])\\nTo pass a single animation please supply them in simple values, e.g. animation('rotate', '2s').\n\n",
  33436. "66": "The animation shorthand arrays can only have 8 elements. See the specification for more information: http://mdn.io/animation.\n\n",
  33437. "67": "You must provide a template to this method.\n\n",
  33438. "68": "You passed an unsupported selector state to this method.\n\n",
  33439. "69": "Expected a string ending in \"px\" or a number passed as the first argument to %s(), got %s instead.\n\n",
  33440. "70": "Expected a string ending in \"px\" or a number passed as the second argument to %s(), got %s instead.\n\n",
  33441. "71": "Passed invalid pixel value %s to %s(), please pass a value like \"12px\" or 12.\n\n",
  33442. "72": "Passed invalid base value %s to %s(), please pass a value like \"12px\" or 12.\n\n",
  33443. "73": "Please provide a valid CSS variable.\n\n",
  33444. "74": "CSS variable not found and no default was provided.\n\n",
  33445. "75": "important requires a valid style object, got a %s instead.\n\n",
  33446. "76": "fromSize and toSize must be provided as stringified numbers with the same units as minScreen and maxScreen.\n\n",
  33447. "77": "remToPx expects a value in \"rem\" but you provided it in \"%s\".\n\n",
  33448. "78": "base must be set in \"px\" or \"%\" but you set it in \"%s\".\n"
  33449. };
  33450. /**
  33451. * super basic version of sprintf
  33452. * @private
  33453. */
  33454. function format() {
  33455. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  33456. args[_key] = arguments[_key];
  33457. }
  33458. var a = args[0];
  33459. var b = [];
  33460. var c;
  33461. for (c = 1; c < args.length; c += 1) {
  33462. b.push(args[c]);
  33463. }
  33464. b.forEach(function (d) {
  33465. a = a.replace(/%[a-z]/, d);
  33466. });
  33467. return a;
  33468. }
  33469. /**
  33470. * Create an error file out of errors.md for development and a simple web link to the full errors
  33471. * in production mode.
  33472. * @private
  33473. */
  33474. var PolishedError = /*#__PURE__*/function (_Error) {
  33475. _inheritsLoose(PolishedError, _Error);
  33476. function PolishedError(code) {
  33477. var _this;
  33478. if (process.env.NODE_ENV === 'production') {
  33479. _this = _Error.call(this, "An error occurred. See https://github.com/styled-components/polished/blob/main/src/internalHelpers/errors.md#" + code + " for more information.") || this;
  33480. } else {
  33481. for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  33482. args[_key2 - 1] = arguments[_key2];
  33483. }
  33484. _this = _Error.call(this, format.apply(void 0, [ERRORS[code]].concat(args))) || this;
  33485. }
  33486. return _assertThisInitialized(_this);
  33487. }
  33488. return PolishedError;
  33489. }( /*#__PURE__*/_wrapNativeSuper(Error));
  33490. function colorToInt(color) {
  33491. return Math.round(color * 255);
  33492. }
  33493. function convertToInt(red, green, blue) {
  33494. return colorToInt(red) + "," + colorToInt(green) + "," + colorToInt(blue);
  33495. }
  33496. function hslToRgb(hue, saturation, lightness, convert) {
  33497. if (convert === void 0) {
  33498. convert = convertToInt;
  33499. }
  33500. if (saturation === 0) {
  33501. // achromatic
  33502. return convert(lightness, lightness, lightness);
  33503. } // formulae from https://en.wikipedia.org/wiki/HSL_and_HSV
  33504. var huePrime = (hue % 360 + 360) % 360 / 60;
  33505. var chroma = (1 - Math.abs(2 * lightness - 1)) * saturation;
  33506. var secondComponent = chroma * (1 - Math.abs(huePrime % 2 - 1));
  33507. var red = 0;
  33508. var green = 0;
  33509. var blue = 0;
  33510. if (huePrime >= 0 && huePrime < 1) {
  33511. red = chroma;
  33512. green = secondComponent;
  33513. } else if (huePrime >= 1 && huePrime < 2) {
  33514. red = secondComponent;
  33515. green = chroma;
  33516. } else if (huePrime >= 2 && huePrime < 3) {
  33517. green = chroma;
  33518. blue = secondComponent;
  33519. } else if (huePrime >= 3 && huePrime < 4) {
  33520. green = secondComponent;
  33521. blue = chroma;
  33522. } else if (huePrime >= 4 && huePrime < 5) {
  33523. red = secondComponent;
  33524. blue = chroma;
  33525. } else if (huePrime >= 5 && huePrime < 6) {
  33526. red = chroma;
  33527. blue = secondComponent;
  33528. }
  33529. var lightnessModification = lightness - chroma / 2;
  33530. var finalRed = red + lightnessModification;
  33531. var finalGreen = green + lightnessModification;
  33532. var finalBlue = blue + lightnessModification;
  33533. return convert(finalRed, finalGreen, finalBlue);
  33534. }
  33535. var namedColorMap = {
  33536. aliceblue: 'f0f8ff',
  33537. antiquewhite: 'faebd7',
  33538. aqua: '00ffff',
  33539. aquamarine: '7fffd4',
  33540. azure: 'f0ffff',
  33541. beige: 'f5f5dc',
  33542. bisque: 'ffe4c4',
  33543. black: '000',
  33544. blanchedalmond: 'ffebcd',
  33545. blue: '0000ff',
  33546. blueviolet: '8a2be2',
  33547. brown: 'a52a2a',
  33548. burlywood: 'deb887',
  33549. cadetblue: '5f9ea0',
  33550. chartreuse: '7fff00',
  33551. chocolate: 'd2691e',
  33552. coral: 'ff7f50',
  33553. cornflowerblue: '6495ed',
  33554. cornsilk: 'fff8dc',
  33555. crimson: 'dc143c',
  33556. cyan: '00ffff',
  33557. darkblue: '00008b',
  33558. darkcyan: '008b8b',
  33559. darkgoldenrod: 'b8860b',
  33560. darkgray: 'a9a9a9',
  33561. darkgreen: '006400',
  33562. darkgrey: 'a9a9a9',
  33563. darkkhaki: 'bdb76b',
  33564. darkmagenta: '8b008b',
  33565. darkolivegreen: '556b2f',
  33566. darkorange: 'ff8c00',
  33567. darkorchid: '9932cc',
  33568. darkred: '8b0000',
  33569. darksalmon: 'e9967a',
  33570. darkseagreen: '8fbc8f',
  33571. darkslateblue: '483d8b',
  33572. darkslategray: '2f4f4f',
  33573. darkslategrey: '2f4f4f',
  33574. darkturquoise: '00ced1',
  33575. darkviolet: '9400d3',
  33576. deeppink: 'ff1493',
  33577. deepskyblue: '00bfff',
  33578. dimgray: '696969',
  33579. dimgrey: '696969',
  33580. dodgerblue: '1e90ff',
  33581. firebrick: 'b22222',
  33582. floralwhite: 'fffaf0',
  33583. forestgreen: '228b22',
  33584. fuchsia: 'ff00ff',
  33585. gainsboro: 'dcdcdc',
  33586. ghostwhite: 'f8f8ff',
  33587. gold: 'ffd700',
  33588. goldenrod: 'daa520',
  33589. gray: '808080',
  33590. green: '008000',
  33591. greenyellow: 'adff2f',
  33592. grey: '808080',
  33593. honeydew: 'f0fff0',
  33594. hotpink: 'ff69b4',
  33595. indianred: 'cd5c5c',
  33596. indigo: '4b0082',
  33597. ivory: 'fffff0',
  33598. khaki: 'f0e68c',
  33599. lavender: 'e6e6fa',
  33600. lavenderblush: 'fff0f5',
  33601. lawngreen: '7cfc00',
  33602. lemonchiffon: 'fffacd',
  33603. lightblue: 'add8e6',
  33604. lightcoral: 'f08080',
  33605. lightcyan: 'e0ffff',
  33606. lightgoldenrodyellow: 'fafad2',
  33607. lightgray: 'd3d3d3',
  33608. lightgreen: '90ee90',
  33609. lightgrey: 'd3d3d3',
  33610. lightpink: 'ffb6c1',
  33611. lightsalmon: 'ffa07a',
  33612. lightseagreen: '20b2aa',
  33613. lightskyblue: '87cefa',
  33614. lightslategray: '789',
  33615. lightslategrey: '789',
  33616. lightsteelblue: 'b0c4de',
  33617. lightyellow: 'ffffe0',
  33618. lime: '0f0',
  33619. limegreen: '32cd32',
  33620. linen: 'faf0e6',
  33621. magenta: 'f0f',
  33622. maroon: '800000',
  33623. mediumaquamarine: '66cdaa',
  33624. mediumblue: '0000cd',
  33625. mediumorchid: 'ba55d3',
  33626. mediumpurple: '9370db',
  33627. mediumseagreen: '3cb371',
  33628. mediumslateblue: '7b68ee',
  33629. mediumspringgreen: '00fa9a',
  33630. mediumturquoise: '48d1cc',
  33631. mediumvioletred: 'c71585',
  33632. midnightblue: '191970',
  33633. mintcream: 'f5fffa',
  33634. mistyrose: 'ffe4e1',
  33635. moccasin: 'ffe4b5',
  33636. navajowhite: 'ffdead',
  33637. navy: '000080',
  33638. oldlace: 'fdf5e6',
  33639. olive: '808000',
  33640. olivedrab: '6b8e23',
  33641. orange: 'ffa500',
  33642. orangered: 'ff4500',
  33643. orchid: 'da70d6',
  33644. palegoldenrod: 'eee8aa',
  33645. palegreen: '98fb98',
  33646. paleturquoise: 'afeeee',
  33647. palevioletred: 'db7093',
  33648. papayawhip: 'ffefd5',
  33649. peachpuff: 'ffdab9',
  33650. peru: 'cd853f',
  33651. pink: 'ffc0cb',
  33652. plum: 'dda0dd',
  33653. powderblue: 'b0e0e6',
  33654. purple: '800080',
  33655. rebeccapurple: '639',
  33656. red: 'f00',
  33657. rosybrown: 'bc8f8f',
  33658. royalblue: '4169e1',
  33659. saddlebrown: '8b4513',
  33660. salmon: 'fa8072',
  33661. sandybrown: 'f4a460',
  33662. seagreen: '2e8b57',
  33663. seashell: 'fff5ee',
  33664. sienna: 'a0522d',
  33665. silver: 'c0c0c0',
  33666. skyblue: '87ceeb',
  33667. slateblue: '6a5acd',
  33668. slategray: '708090',
  33669. slategrey: '708090',
  33670. snow: 'fffafa',
  33671. springgreen: '00ff7f',
  33672. steelblue: '4682b4',
  33673. tan: 'd2b48c',
  33674. teal: '008080',
  33675. thistle: 'd8bfd8',
  33676. tomato: 'ff6347',
  33677. turquoise: '40e0d0',
  33678. violet: 'ee82ee',
  33679. wheat: 'f5deb3',
  33680. white: 'fff',
  33681. whitesmoke: 'f5f5f5',
  33682. yellow: 'ff0',
  33683. yellowgreen: '9acd32'
  33684. };
  33685. /**
  33686. * Checks if a string is a CSS named color and returns its equivalent hex value, otherwise returns the original color.
  33687. * @private
  33688. */
  33689. function nameToHex(color) {
  33690. if (typeof color !== 'string') return color;
  33691. var normalizedColorName = color.toLowerCase();
  33692. return namedColorMap[normalizedColorName] ? "#" + namedColorMap[normalizedColorName] : color;
  33693. }
  33694. var hexRegex = /^#[a-fA-F0-9]{6}$/;
  33695. var hexRgbaRegex = /^#[a-fA-F0-9]{8}$/;
  33696. var reducedHexRegex = /^#[a-fA-F0-9]{3}$/;
  33697. var reducedRgbaHexRegex = /^#[a-fA-F0-9]{4}$/;
  33698. var rgbRegex = /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i;
  33699. var rgbaRegex = /^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*([-+]?[0-9]*[.]?[0-9]+)\s*\)$/i;
  33700. var hslRegex = /^hsl\(\s*(\d{0,3}[.]?[0-9]+)\s*,\s*(\d{1,3}[.]?[0-9]?)%\s*,\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i;
  33701. var hslaRegex = /^hsla\(\s*(\d{0,3}[.]?[0-9]+)\s*,\s*(\d{1,3}[.]?[0-9]?)%\s*,\s*(\d{1,3}[.]?[0-9]?)%\s*,\s*([-+]?[0-9]*[.]?[0-9]+)\s*\)$/i;
  33702. /**
  33703. * Returns an RgbColor or RgbaColor object. This utility function is only useful
  33704. * if want to extract a color component. With the color util `toColorString` you
  33705. * can convert a RgbColor or RgbaColor object back to a string.
  33706. *
  33707. * @example
  33708. * // Assigns `{ red: 255, green: 0, blue: 0 }` to color1
  33709. * const color1 = parseToRgb('rgb(255, 0, 0)');
  33710. * // Assigns `{ red: 92, green: 102, blue: 112, alpha: 0.75 }` to color2
  33711. * const color2 = parseToRgb('hsla(210, 10%, 40%, 0.75)');
  33712. */
  33713. function parseToRgb(color) {
  33714. if (typeof color !== 'string') {
  33715. throw new PolishedError(3);
  33716. }
  33717. var normalizedColor = nameToHex(color);
  33718. if (normalizedColor.match(hexRegex)) {
  33719. return {
  33720. red: parseInt("" + normalizedColor[1] + normalizedColor[2], 16),
  33721. green: parseInt("" + normalizedColor[3] + normalizedColor[4], 16),
  33722. blue: parseInt("" + normalizedColor[5] + normalizedColor[6], 16)
  33723. };
  33724. }
  33725. if (normalizedColor.match(hexRgbaRegex)) {
  33726. var alpha = parseFloat((parseInt("" + normalizedColor[7] + normalizedColor[8], 16) / 255).toFixed(2));
  33727. return {
  33728. red: parseInt("" + normalizedColor[1] + normalizedColor[2], 16),
  33729. green: parseInt("" + normalizedColor[3] + normalizedColor[4], 16),
  33730. blue: parseInt("" + normalizedColor[5] + normalizedColor[6], 16),
  33731. alpha: alpha
  33732. };
  33733. }
  33734. if (normalizedColor.match(reducedHexRegex)) {
  33735. return {
  33736. red: parseInt("" + normalizedColor[1] + normalizedColor[1], 16),
  33737. green: parseInt("" + normalizedColor[2] + normalizedColor[2], 16),
  33738. blue: parseInt("" + normalizedColor[3] + normalizedColor[3], 16)
  33739. };
  33740. }
  33741. if (normalizedColor.match(reducedRgbaHexRegex)) {
  33742. var _alpha = parseFloat((parseInt("" + normalizedColor[4] + normalizedColor[4], 16) / 255).toFixed(2));
  33743. return {
  33744. red: parseInt("" + normalizedColor[1] + normalizedColor[1], 16),
  33745. green: parseInt("" + normalizedColor[2] + normalizedColor[2], 16),
  33746. blue: parseInt("" + normalizedColor[3] + normalizedColor[3], 16),
  33747. alpha: _alpha
  33748. };
  33749. }
  33750. var rgbMatched = rgbRegex.exec(normalizedColor);
  33751. if (rgbMatched) {
  33752. return {
  33753. red: parseInt("" + rgbMatched[1], 10),
  33754. green: parseInt("" + rgbMatched[2], 10),
  33755. blue: parseInt("" + rgbMatched[3], 10)
  33756. };
  33757. }
  33758. var rgbaMatched = rgbaRegex.exec(normalizedColor.substring(0, 50));
  33759. if (rgbaMatched) {
  33760. return {
  33761. red: parseInt("" + rgbaMatched[1], 10),
  33762. green: parseInt("" + rgbaMatched[2], 10),
  33763. blue: parseInt("" + rgbaMatched[3], 10),
  33764. alpha: parseFloat("" + rgbaMatched[4])
  33765. };
  33766. }
  33767. var hslMatched = hslRegex.exec(normalizedColor);
  33768. if (hslMatched) {
  33769. var hue = parseInt("" + hslMatched[1], 10);
  33770. var saturation = parseInt("" + hslMatched[2], 10) / 100;
  33771. var lightness = parseInt("" + hslMatched[3], 10) / 100;
  33772. var rgbColorString = "rgb(" + hslToRgb(hue, saturation, lightness) + ")";
  33773. var hslRgbMatched = rgbRegex.exec(rgbColorString);
  33774. if (!hslRgbMatched) {
  33775. throw new PolishedError(4, normalizedColor, rgbColorString);
  33776. }
  33777. return {
  33778. red: parseInt("" + hslRgbMatched[1], 10),
  33779. green: parseInt("" + hslRgbMatched[2], 10),
  33780. blue: parseInt("" + hslRgbMatched[3], 10)
  33781. };
  33782. }
  33783. var hslaMatched = hslaRegex.exec(normalizedColor.substring(0, 50));
  33784. if (hslaMatched) {
  33785. var _hue = parseInt("" + hslaMatched[1], 10);
  33786. var _saturation = parseInt("" + hslaMatched[2], 10) / 100;
  33787. var _lightness = parseInt("" + hslaMatched[3], 10) / 100;
  33788. var _rgbColorString = "rgb(" + hslToRgb(_hue, _saturation, _lightness) + ")";
  33789. var _hslRgbMatched = rgbRegex.exec(_rgbColorString);
  33790. if (!_hslRgbMatched) {
  33791. throw new PolishedError(4, normalizedColor, _rgbColorString);
  33792. }
  33793. return {
  33794. red: parseInt("" + _hslRgbMatched[1], 10),
  33795. green: parseInt("" + _hslRgbMatched[2], 10),
  33796. blue: parseInt("" + _hslRgbMatched[3], 10),
  33797. alpha: parseFloat("" + hslaMatched[4])
  33798. };
  33799. }
  33800. throw new PolishedError(5);
  33801. }
  33802. /**
  33803. * Reduces hex values if possible e.g. #ff8866 to #f86
  33804. * @private
  33805. */
  33806. var reduceHexValue = function reduceHexValue(value) {
  33807. if (value.length === 7 && value[1] === value[2] && value[3] === value[4] && value[5] === value[6]) {
  33808. return "#" + value[1] + value[3] + value[5];
  33809. }
  33810. return value;
  33811. };
  33812. function numberToHex(value) {
  33813. var hex = value.toString(16);
  33814. return hex.length === 1 ? "0" + hex : hex;
  33815. }
  33816. /**
  33817. * Returns a string value for the color. The returned result is the smallest possible hex notation.
  33818. *
  33819. * @example
  33820. * // Styles as object usage
  33821. * const styles = {
  33822. * background: rgb(255, 205, 100),
  33823. * background: rgb({ red: 255, green: 205, blue: 100 }),
  33824. * }
  33825. *
  33826. * // styled-components usage
  33827. * const div = styled.div`
  33828. * background: ${rgb(255, 205, 100)};
  33829. * background: ${rgb({ red: 255, green: 205, blue: 100 })};
  33830. * `
  33831. *
  33832. * // CSS in JS Output
  33833. *
  33834. * element {
  33835. * background: "#ffcd64";
  33836. * background: "#ffcd64";
  33837. * }
  33838. */
  33839. function rgb(value, green, blue) {
  33840. if (typeof value === 'number' && typeof green === 'number' && typeof blue === 'number') {
  33841. return reduceHexValue("#" + numberToHex(value) + numberToHex(green) + numberToHex(blue));
  33842. } else if (typeof value === 'object' && green === undefined && blue === undefined) {
  33843. return reduceHexValue("#" + numberToHex(value.red) + numberToHex(value.green) + numberToHex(value.blue));
  33844. }
  33845. throw new PolishedError(6);
  33846. }
  33847. /**
  33848. * Returns a string value for the color. The returned result is the smallest possible rgba or hex notation.
  33849. *
  33850. * Can also be used to fade a color by passing a hex value or named CSS color along with an alpha value.
  33851. *
  33852. * @example
  33853. * // Styles as object usage
  33854. * const styles = {
  33855. * background: rgba(255, 205, 100, 0.7),
  33856. * background: rgba({ red: 255, green: 205, blue: 100, alpha: 0.7 }),
  33857. * background: rgba(255, 205, 100, 1),
  33858. * background: rgba('#ffffff', 0.4),
  33859. * background: rgba('black', 0.7),
  33860. * }
  33861. *
  33862. * // styled-components usage
  33863. * const div = styled.div`
  33864. * background: ${rgba(255, 205, 100, 0.7)};
  33865. * background: ${rgba({ red: 255, green: 205, blue: 100, alpha: 0.7 })};
  33866. * background: ${rgba(255, 205, 100, 1)};
  33867. * background: ${rgba('#ffffff', 0.4)};
  33868. * background: ${rgba('black', 0.7)};
  33869. * `
  33870. *
  33871. * // CSS in JS Output
  33872. *
  33873. * element {
  33874. * background: "rgba(255,205,100,0.7)";
  33875. * background: "rgba(255,205,100,0.7)";
  33876. * background: "#ffcd64";
  33877. * background: "rgba(255,255,255,0.4)";
  33878. * background: "rgba(0,0,0,0.7)";
  33879. * }
  33880. */
  33881. function rgba(firstValue, secondValue, thirdValue, fourthValue) {
  33882. if (typeof firstValue === 'string' && typeof secondValue === 'number') {
  33883. var rgbValue = parseToRgb(firstValue);
  33884. return "rgba(" + rgbValue.red + "," + rgbValue.green + "," + rgbValue.blue + "," + secondValue + ")";
  33885. } else if (typeof firstValue === 'number' && typeof secondValue === 'number' && typeof thirdValue === 'number' && typeof fourthValue === 'number') {
  33886. return fourthValue >= 1 ? rgb(firstValue, secondValue, thirdValue) : "rgba(" + firstValue + "," + secondValue + "," + thirdValue + "," + fourthValue + ")";
  33887. } else if (typeof firstValue === 'object' && secondValue === undefined && thirdValue === undefined && fourthValue === undefined) {
  33888. return firstValue.alpha >= 1 ? rgb(firstValue.red, firstValue.green, firstValue.blue) : "rgba(" + firstValue.red + "," + firstValue.green + "," + firstValue.blue + "," + firstValue.alpha + ")";
  33889. }
  33890. throw new PolishedError(7);
  33891. }
  33892. // Type definitions taken from https://github.com/gcanti/flow-static-land/blob/master/src/Fun.js
  33893. // eslint-disable-next-line no-unused-vars
  33894. // eslint-disable-next-line no-unused-vars
  33895. // eslint-disable-next-line no-redeclare
  33896. function curried(f, length, acc) {
  33897. return function fn() {
  33898. // eslint-disable-next-line prefer-rest-params
  33899. var combined = acc.concat(Array.prototype.slice.call(arguments));
  33900. return combined.length >= length ? f.apply(this, combined) : curried(f, length, combined);
  33901. };
  33902. } // eslint-disable-next-line no-redeclare
  33903. function curry(f) {
  33904. // eslint-disable-line no-redeclare
  33905. return curried(f, f.length, []);
  33906. }
  33907. function guard(lowerBoundary, upperBoundary, value) {
  33908. return Math.max(lowerBoundary, Math.min(upperBoundary, value));
  33909. }
  33910. /**
  33911. * Increases the opacity of a color. Its range for the amount is between 0 to 1.
  33912. *
  33913. *
  33914. * @example
  33915. * // Styles as object usage
  33916. * const styles = {
  33917. * background: opacify(0.1, 'rgba(255, 255, 255, 0.9)');
  33918. * background: opacify(0.2, 'hsla(0, 0%, 100%, 0.5)'),
  33919. * background: opacify('0.5', 'rgba(255, 0, 0, 0.2)'),
  33920. * }
  33921. *
  33922. * // styled-components usage
  33923. * const div = styled.div`
  33924. * background: ${opacify(0.1, 'rgba(255, 255, 255, 0.9)')};
  33925. * background: ${opacify(0.2, 'hsla(0, 0%, 100%, 0.5)')},
  33926. * background: ${opacify('0.5', 'rgba(255, 0, 0, 0.2)')},
  33927. * `
  33928. *
  33929. * // CSS in JS Output
  33930. *
  33931. * element {
  33932. * background: "#fff";
  33933. * background: "rgba(255,255,255,0.7)";
  33934. * background: "rgba(255,0,0,0.7)";
  33935. * }
  33936. */
  33937. function opacify(amount, color) {
  33938. if (color === 'transparent') return color;
  33939. var parsedColor = parseToRgb(color);
  33940. var alpha = typeof parsedColor.alpha === 'number' ? parsedColor.alpha : 1;
  33941. var colorWithAlpha = _extends({}, parsedColor, {
  33942. alpha: guard(0, 1, (alpha * 100 + parseFloat(amount) * 100) / 100)
  33943. });
  33944. return rgba(colorWithAlpha);
  33945. } // prettier-ignore
  33946. var curriedOpacify = /*#__PURE__*/curry
  33947. /* ::<number | string, string, string> */
  33948. (opacify);
  33949. /**
  33950. * The Ease class provides a collection of easing functions for use with tween.js.
  33951. */
  33952. var Easing = {
  33953. Linear: {
  33954. None: function (amount) {
  33955. return amount;
  33956. },
  33957. },
  33958. Quadratic: {
  33959. In: function (amount) {
  33960. return amount * amount;
  33961. },
  33962. Out: function (amount) {
  33963. return amount * (2 - amount);
  33964. },
  33965. InOut: function (amount) {
  33966. if ((amount *= 2) < 1) {
  33967. return 0.5 * amount * amount;
  33968. }
  33969. return -0.5 * (--amount * (amount - 2) - 1);
  33970. },
  33971. },
  33972. Cubic: {
  33973. In: function (amount) {
  33974. return amount * amount * amount;
  33975. },
  33976. Out: function (amount) {
  33977. return --amount * amount * amount + 1;
  33978. },
  33979. InOut: function (amount) {
  33980. if ((amount *= 2) < 1) {
  33981. return 0.5 * amount * amount * amount;
  33982. }
  33983. return 0.5 * ((amount -= 2) * amount * amount + 2);
  33984. },
  33985. },
  33986. Quartic: {
  33987. In: function (amount) {
  33988. return amount * amount * amount * amount;
  33989. },
  33990. Out: function (amount) {
  33991. return 1 - --amount * amount * amount * amount;
  33992. },
  33993. InOut: function (amount) {
  33994. if ((amount *= 2) < 1) {
  33995. return 0.5 * amount * amount * amount * amount;
  33996. }
  33997. return -0.5 * ((amount -= 2) * amount * amount * amount - 2);
  33998. },
  33999. },
  34000. Quintic: {
  34001. In: function (amount) {
  34002. return amount * amount * amount * amount * amount;
  34003. },
  34004. Out: function (amount) {
  34005. return --amount * amount * amount * amount * amount + 1;
  34006. },
  34007. InOut: function (amount) {
  34008. if ((amount *= 2) < 1) {
  34009. return 0.5 * amount * amount * amount * amount * amount;
  34010. }
  34011. return 0.5 * ((amount -= 2) * amount * amount * amount * amount + 2);
  34012. },
  34013. },
  34014. Sinusoidal: {
  34015. In: function (amount) {
  34016. return 1 - Math.cos((amount * Math.PI) / 2);
  34017. },
  34018. Out: function (amount) {
  34019. return Math.sin((amount * Math.PI) / 2);
  34020. },
  34021. InOut: function (amount) {
  34022. return 0.5 * (1 - Math.cos(Math.PI * amount));
  34023. },
  34024. },
  34025. Exponential: {
  34026. In: function (amount) {
  34027. return amount === 0 ? 0 : Math.pow(1024, amount - 1);
  34028. },
  34029. Out: function (amount) {
  34030. return amount === 1 ? 1 : 1 - Math.pow(2, -10 * amount);
  34031. },
  34032. InOut: function (amount) {
  34033. if (amount === 0) {
  34034. return 0;
  34035. }
  34036. if (amount === 1) {
  34037. return 1;
  34038. }
  34039. if ((amount *= 2) < 1) {
  34040. return 0.5 * Math.pow(1024, amount - 1);
  34041. }
  34042. return 0.5 * (-Math.pow(2, -10 * (amount - 1)) + 2);
  34043. },
  34044. },
  34045. Circular: {
  34046. In: function (amount) {
  34047. return 1 - Math.sqrt(1 - amount * amount);
  34048. },
  34049. Out: function (amount) {
  34050. return Math.sqrt(1 - --amount * amount);
  34051. },
  34052. InOut: function (amount) {
  34053. if ((amount *= 2) < 1) {
  34054. return -0.5 * (Math.sqrt(1 - amount * amount) - 1);
  34055. }
  34056. return 0.5 * (Math.sqrt(1 - (amount -= 2) * amount) + 1);
  34057. },
  34058. },
  34059. Elastic: {
  34060. In: function (amount) {
  34061. if (amount === 0) {
  34062. return 0;
  34063. }
  34064. if (amount === 1) {
  34065. return 1;
  34066. }
  34067. return -Math.pow(2, 10 * (amount - 1)) * Math.sin((amount - 1.1) * 5 * Math.PI);
  34068. },
  34069. Out: function (amount) {
  34070. if (amount === 0) {
  34071. return 0;
  34072. }
  34073. if (amount === 1) {
  34074. return 1;
  34075. }
  34076. return Math.pow(2, -10 * amount) * Math.sin((amount - 0.1) * 5 * Math.PI) + 1;
  34077. },
  34078. InOut: function (amount) {
  34079. if (amount === 0) {
  34080. return 0;
  34081. }
  34082. if (amount === 1) {
  34083. return 1;
  34084. }
  34085. amount *= 2;
  34086. if (amount < 1) {
  34087. return -0.5 * Math.pow(2, 10 * (amount - 1)) * Math.sin((amount - 1.1) * 5 * Math.PI);
  34088. }
  34089. return 0.5 * Math.pow(2, -10 * (amount - 1)) * Math.sin((amount - 1.1) * 5 * Math.PI) + 1;
  34090. },
  34091. },
  34092. Back: {
  34093. In: function (amount) {
  34094. var s = 1.70158;
  34095. return amount * amount * ((s + 1) * amount - s);
  34096. },
  34097. Out: function (amount) {
  34098. var s = 1.70158;
  34099. return --amount * amount * ((s + 1) * amount + s) + 1;
  34100. },
  34101. InOut: function (amount) {
  34102. var s = 1.70158 * 1.525;
  34103. if ((amount *= 2) < 1) {
  34104. return 0.5 * (amount * amount * ((s + 1) * amount - s));
  34105. }
  34106. return 0.5 * ((amount -= 2) * amount * ((s + 1) * amount + s) + 2);
  34107. },
  34108. },
  34109. Bounce: {
  34110. In: function (amount) {
  34111. return 1 - Easing.Bounce.Out(1 - amount);
  34112. },
  34113. Out: function (amount) {
  34114. if (amount < 1 / 2.75) {
  34115. return 7.5625 * amount * amount;
  34116. }
  34117. else if (amount < 2 / 2.75) {
  34118. return 7.5625 * (amount -= 1.5 / 2.75) * amount + 0.75;
  34119. }
  34120. else if (amount < 2.5 / 2.75) {
  34121. return 7.5625 * (amount -= 2.25 / 2.75) * amount + 0.9375;
  34122. }
  34123. else {
  34124. return 7.5625 * (amount -= 2.625 / 2.75) * amount + 0.984375;
  34125. }
  34126. },
  34127. InOut: function (amount) {
  34128. if (amount < 0.5) {
  34129. return Easing.Bounce.In(amount * 2) * 0.5;
  34130. }
  34131. return Easing.Bounce.Out(amount * 2 - 1) * 0.5 + 0.5;
  34132. },
  34133. },
  34134. };
  34135. var now;
  34136. // Include a performance.now polyfill.
  34137. // In node.js, use process.hrtime.
  34138. // eslint-disable-next-line
  34139. // @ts-ignore
  34140. if (typeof self === 'undefined' && typeof process !== 'undefined' && process.hrtime) {
  34141. now = function () {
  34142. // eslint-disable-next-line
  34143. // @ts-ignore
  34144. var time = process.hrtime();
  34145. // Convert [seconds, nanoseconds] to milliseconds.
  34146. return time[0] * 1000 + time[1] / 1000000;
  34147. };
  34148. }
  34149. // In a browser, use self.performance.now if it is available.
  34150. else if (typeof self !== 'undefined' && self.performance !== undefined && self.performance.now !== undefined) {
  34151. // This must be bound, because directly assigning this function
  34152. // leads to an invocation exception in Chrome.
  34153. now = self.performance.now.bind(self.performance);
  34154. }
  34155. // Use Date.now if it is available.
  34156. else if (Date.now !== undefined) {
  34157. now = Date.now;
  34158. }
  34159. // Otherwise, use 'new Date().getTime()'.
  34160. else {
  34161. now = function () {
  34162. return new Date().getTime();
  34163. };
  34164. }
  34165. var now$1 = now;
  34166. /**
  34167. * Controlling groups of tweens
  34168. *
  34169. * Using the TWEEN singleton to manage your tweens can cause issues in large apps with many components.
  34170. * In these cases, you may want to create your own smaller groups of tween
  34171. */
  34172. var Group = /** @class */ (function () {
  34173. function Group() {
  34174. this._tweens = {};
  34175. this._tweensAddedDuringUpdate = {};
  34176. }
  34177. Group.prototype.getAll = function () {
  34178. var _this = this;
  34179. return Object.keys(this._tweens).map(function (tweenId) {
  34180. return _this._tweens[tweenId];
  34181. });
  34182. };
  34183. Group.prototype.removeAll = function () {
  34184. this._tweens = {};
  34185. };
  34186. Group.prototype.add = function (tween) {
  34187. this._tweens[tween.getId()] = tween;
  34188. this._tweensAddedDuringUpdate[tween.getId()] = tween;
  34189. };
  34190. Group.prototype.remove = function (tween) {
  34191. delete this._tweens[tween.getId()];
  34192. delete this._tweensAddedDuringUpdate[tween.getId()];
  34193. };
  34194. Group.prototype.update = function (time, preserve) {
  34195. if (time === void 0) { time = now$1(); }
  34196. if (preserve === void 0) { preserve = false; }
  34197. var tweenIds = Object.keys(this._tweens);
  34198. if (tweenIds.length === 0) {
  34199. return false;
  34200. }
  34201. // Tweens are updated in "batches". If you add a new tween during an
  34202. // update, then the new tween will be updated in the next batch.
  34203. // If you remove a tween during an update, it may or may not be updated.
  34204. // However, if the removed tween was added during the current batch,
  34205. // then it will not be updated.
  34206. while (tweenIds.length > 0) {
  34207. this._tweensAddedDuringUpdate = {};
  34208. for (var i = 0; i < tweenIds.length; i++) {
  34209. var tween = this._tweens[tweenIds[i]];
  34210. var autoStart = !preserve;
  34211. if (tween && tween.update(time, autoStart) === false && !preserve) {
  34212. delete this._tweens[tweenIds[i]];
  34213. }
  34214. }
  34215. tweenIds = Object.keys(this._tweensAddedDuringUpdate);
  34216. }
  34217. return true;
  34218. };
  34219. return Group;
  34220. }());
  34221. /**
  34222. *
  34223. */
  34224. var Interpolation = {
  34225. Linear: function (v, k) {
  34226. var m = v.length - 1;
  34227. var f = m * k;
  34228. var i = Math.floor(f);
  34229. var fn = Interpolation.Utils.Linear;
  34230. if (k < 0) {
  34231. return fn(v[0], v[1], f);
  34232. }
  34233. if (k > 1) {
  34234. return fn(v[m], v[m - 1], m - f);
  34235. }
  34236. return fn(v[i], v[i + 1 > m ? m : i + 1], f - i);
  34237. },
  34238. Bezier: function (v, k) {
  34239. var b = 0;
  34240. var n = v.length - 1;
  34241. var pw = Math.pow;
  34242. var bn = Interpolation.Utils.Bernstein;
  34243. for (var i = 0; i <= n; i++) {
  34244. b += pw(1 - k, n - i) * pw(k, i) * v[i] * bn(n, i);
  34245. }
  34246. return b;
  34247. },
  34248. CatmullRom: function (v, k) {
  34249. var m = v.length - 1;
  34250. var f = m * k;
  34251. var i = Math.floor(f);
  34252. var fn = Interpolation.Utils.CatmullRom;
  34253. if (v[0] === v[m]) {
  34254. if (k < 0) {
  34255. i = Math.floor((f = m * (1 + k)));
  34256. }
  34257. return fn(v[(i - 1 + m) % m], v[i], v[(i + 1) % m], v[(i + 2) % m], f - i);
  34258. }
  34259. else {
  34260. if (k < 0) {
  34261. return v[0] - (fn(v[0], v[0], v[1], v[1], -f) - v[0]);
  34262. }
  34263. if (k > 1) {
  34264. return v[m] - (fn(v[m], v[m], v[m - 1], v[m - 1], f - m) - v[m]);
  34265. }
  34266. return fn(v[i ? i - 1 : 0], v[i], v[m < i + 1 ? m : i + 1], v[m < i + 2 ? m : i + 2], f - i);
  34267. }
  34268. },
  34269. Utils: {
  34270. Linear: function (p0, p1, t) {
  34271. return (p1 - p0) * t + p0;
  34272. },
  34273. Bernstein: function (n, i) {
  34274. var fc = Interpolation.Utils.Factorial;
  34275. return fc(n) / fc(i) / fc(n - i);
  34276. },
  34277. Factorial: (function () {
  34278. var a = [1];
  34279. return function (n) {
  34280. var s = 1;
  34281. if (a[n]) {
  34282. return a[n];
  34283. }
  34284. for (var i = n; i > 1; i--) {
  34285. s *= i;
  34286. }
  34287. a[n] = s;
  34288. return s;
  34289. };
  34290. })(),
  34291. CatmullRom: function (p0, p1, p2, p3, t) {
  34292. var v0 = (p2 - p0) * 0.5;
  34293. var v1 = (p3 - p1) * 0.5;
  34294. var t2 = t * t;
  34295. var t3 = t * t2;
  34296. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  34297. },
  34298. },
  34299. };
  34300. /**
  34301. * Utils
  34302. */
  34303. var Sequence = /** @class */ (function () {
  34304. function Sequence() {
  34305. }
  34306. Sequence.nextId = function () {
  34307. return Sequence._nextId++;
  34308. };
  34309. Sequence._nextId = 0;
  34310. return Sequence;
  34311. }());
  34312. var mainGroup = new Group();
  34313. /**
  34314. * Tween.js - Licensed under the MIT license
  34315. * https://github.com/tweenjs/tween.js
  34316. * ----------------------------------------------
  34317. *
  34318. * See https://github.com/tweenjs/tween.js/graphs/contributors for the full list of contributors.
  34319. * Thank you all, you're awesome!
  34320. */
  34321. var Tween = /** @class */ (function () {
  34322. function Tween(_object, _group) {
  34323. if (_group === void 0) { _group = mainGroup; }
  34324. this._object = _object;
  34325. this._group = _group;
  34326. this._isPaused = false;
  34327. this._pauseStart = 0;
  34328. this._valuesStart = {};
  34329. this._valuesEnd = {};
  34330. this._valuesStartRepeat = {};
  34331. this._duration = 1000;
  34332. this._initialRepeat = 0;
  34333. this._repeat = 0;
  34334. this._yoyo = false;
  34335. this._isPlaying = false;
  34336. this._reversed = false;
  34337. this._delayTime = 0;
  34338. this._startTime = 0;
  34339. this._easingFunction = Easing.Linear.None;
  34340. this._interpolationFunction = Interpolation.Linear;
  34341. this._chainedTweens = [];
  34342. this._onStartCallbackFired = false;
  34343. this._id = Sequence.nextId();
  34344. this._isChainStopped = false;
  34345. this._goToEnd = false;
  34346. }
  34347. Tween.prototype.getId = function () {
  34348. return this._id;
  34349. };
  34350. Tween.prototype.isPlaying = function () {
  34351. return this._isPlaying;
  34352. };
  34353. Tween.prototype.isPaused = function () {
  34354. return this._isPaused;
  34355. };
  34356. Tween.prototype.to = function (properties, duration) {
  34357. // TODO? restore this, then update the 07_dynamic_to example to set fox
  34358. // tween's to on each update. That way the behavior is opt-in (there's
  34359. // currently no opt-out).
  34360. // for (const prop in properties) this._valuesEnd[prop] = properties[prop]
  34361. this._valuesEnd = Object.create(properties);
  34362. if (duration !== undefined) {
  34363. this._duration = duration;
  34364. }
  34365. return this;
  34366. };
  34367. Tween.prototype.duration = function (d) {
  34368. this._duration = d;
  34369. return this;
  34370. };
  34371. Tween.prototype.start = function (time) {
  34372. if (this._isPlaying) {
  34373. return this;
  34374. }
  34375. // eslint-disable-next-line
  34376. this._group && this._group.add(this);
  34377. this._repeat = this._initialRepeat;
  34378. if (this._reversed) {
  34379. // If we were reversed (f.e. using the yoyo feature) then we need to
  34380. // flip the tween direction back to forward.
  34381. this._reversed = false;
  34382. for (var property in this._valuesStartRepeat) {
  34383. this._swapEndStartRepeatValues(property);
  34384. this._valuesStart[property] = this._valuesStartRepeat[property];
  34385. }
  34386. }
  34387. this._isPlaying = true;
  34388. this._isPaused = false;
  34389. this._onStartCallbackFired = false;
  34390. this._isChainStopped = false;
  34391. this._startTime = time !== undefined ? (typeof time === 'string' ? now$1() + parseFloat(time) : time) : now$1();
  34392. this._startTime += this._delayTime;
  34393. this._setupProperties(this._object, this._valuesStart, this._valuesEnd, this._valuesStartRepeat);
  34394. return this;
  34395. };
  34396. Tween.prototype._setupProperties = function (_object, _valuesStart, _valuesEnd, _valuesStartRepeat) {
  34397. for (var property in _valuesEnd) {
  34398. var startValue = _object[property];
  34399. var startValueIsArray = Array.isArray(startValue);
  34400. var propType = startValueIsArray ? 'array' : typeof startValue;
  34401. var isInterpolationList = !startValueIsArray && Array.isArray(_valuesEnd[property]);
  34402. // If `to()` specifies a property that doesn't exist in the source object,
  34403. // we should not set that property in the object
  34404. if (propType === 'undefined' || propType === 'function') {
  34405. continue;
  34406. }
  34407. // Check if an Array was provided as property value
  34408. if (isInterpolationList) {
  34409. var endValues = _valuesEnd[property];
  34410. if (endValues.length === 0) {
  34411. continue;
  34412. }
  34413. // handle an array of relative values
  34414. endValues = endValues.map(this._handleRelativeValue.bind(this, startValue));
  34415. // Create a local copy of the Array with the start value at the front
  34416. _valuesEnd[property] = [startValue].concat(endValues);
  34417. }
  34418. // handle the deepness of the values
  34419. if ((propType === 'object' || startValueIsArray) && startValue && !isInterpolationList) {
  34420. _valuesStart[property] = startValueIsArray ? [] : {};
  34421. // eslint-disable-next-line
  34422. for (var prop in startValue) {
  34423. // eslint-disable-next-line
  34424. // @ts-ignore FIXME?
  34425. _valuesStart[property][prop] = startValue[prop];
  34426. }
  34427. _valuesStartRepeat[property] = startValueIsArray ? [] : {}; // TODO? repeat nested values? And yoyo? And array values?
  34428. // eslint-disable-next-line
  34429. // @ts-ignore FIXME?
  34430. this._setupProperties(startValue, _valuesStart[property], _valuesEnd[property], _valuesStartRepeat[property]);
  34431. }
  34432. else {
  34433. // Save the starting value, but only once.
  34434. if (typeof _valuesStart[property] === 'undefined') {
  34435. _valuesStart[property] = startValue;
  34436. }
  34437. if (!startValueIsArray) {
  34438. // eslint-disable-next-line
  34439. // @ts-ignore FIXME?
  34440. _valuesStart[property] *= 1.0; // Ensures we're using numbers, not strings
  34441. }
  34442. if (isInterpolationList) {
  34443. // eslint-disable-next-line
  34444. // @ts-ignore FIXME?
  34445. _valuesStartRepeat[property] = _valuesEnd[property].slice().reverse();
  34446. }
  34447. else {
  34448. _valuesStartRepeat[property] = _valuesStart[property] || 0;
  34449. }
  34450. }
  34451. }
  34452. };
  34453. Tween.prototype.stop = function () {
  34454. if (!this._isChainStopped) {
  34455. this._isChainStopped = true;
  34456. this.stopChainedTweens();
  34457. }
  34458. if (!this._isPlaying) {
  34459. return this;
  34460. }
  34461. // eslint-disable-next-line
  34462. this._group && this._group.remove(this);
  34463. this._isPlaying = false;
  34464. this._isPaused = false;
  34465. if (this._onStopCallback) {
  34466. this._onStopCallback(this._object);
  34467. }
  34468. return this;
  34469. };
  34470. Tween.prototype.end = function () {
  34471. this._goToEnd = true;
  34472. this.update(Infinity);
  34473. return this;
  34474. };
  34475. Tween.prototype.pause = function (time) {
  34476. if (time === void 0) { time = now$1(); }
  34477. if (this._isPaused || !this._isPlaying) {
  34478. return this;
  34479. }
  34480. this._isPaused = true;
  34481. this._pauseStart = time;
  34482. // eslint-disable-next-line
  34483. this._group && this._group.remove(this);
  34484. return this;
  34485. };
  34486. Tween.prototype.resume = function (time) {
  34487. if (time === void 0) { time = now$1(); }
  34488. if (!this._isPaused || !this._isPlaying) {
  34489. return this;
  34490. }
  34491. this._isPaused = false;
  34492. this._startTime += time - this._pauseStart;
  34493. this._pauseStart = 0;
  34494. // eslint-disable-next-line
  34495. this._group && this._group.add(this);
  34496. return this;
  34497. };
  34498. Tween.prototype.stopChainedTweens = function () {
  34499. for (var i = 0, numChainedTweens = this._chainedTweens.length; i < numChainedTweens; i++) {
  34500. this._chainedTweens[i].stop();
  34501. }
  34502. return this;
  34503. };
  34504. Tween.prototype.group = function (group) {
  34505. this._group = group;
  34506. return this;
  34507. };
  34508. Tween.prototype.delay = function (amount) {
  34509. this._delayTime = amount;
  34510. return this;
  34511. };
  34512. Tween.prototype.repeat = function (times) {
  34513. this._initialRepeat = times;
  34514. this._repeat = times;
  34515. return this;
  34516. };
  34517. Tween.prototype.repeatDelay = function (amount) {
  34518. this._repeatDelayTime = amount;
  34519. return this;
  34520. };
  34521. Tween.prototype.yoyo = function (yoyo) {
  34522. this._yoyo = yoyo;
  34523. return this;
  34524. };
  34525. Tween.prototype.easing = function (easingFunction) {
  34526. this._easingFunction = easingFunction;
  34527. return this;
  34528. };
  34529. Tween.prototype.interpolation = function (interpolationFunction) {
  34530. this._interpolationFunction = interpolationFunction;
  34531. return this;
  34532. };
  34533. Tween.prototype.chain = function () {
  34534. var tweens = [];
  34535. for (var _i = 0; _i < arguments.length; _i++) {
  34536. tweens[_i] = arguments[_i];
  34537. }
  34538. this._chainedTweens = tweens;
  34539. return this;
  34540. };
  34541. Tween.prototype.onStart = function (callback) {
  34542. this._onStartCallback = callback;
  34543. return this;
  34544. };
  34545. Tween.prototype.onUpdate = function (callback) {
  34546. this._onUpdateCallback = callback;
  34547. return this;
  34548. };
  34549. Tween.prototype.onRepeat = function (callback) {
  34550. this._onRepeatCallback = callback;
  34551. return this;
  34552. };
  34553. Tween.prototype.onComplete = function (callback) {
  34554. this._onCompleteCallback = callback;
  34555. return this;
  34556. };
  34557. Tween.prototype.onStop = function (callback) {
  34558. this._onStopCallback = callback;
  34559. return this;
  34560. };
  34561. /**
  34562. * @returns true if the tween is still playing after the update, false
  34563. * otherwise (calling update on a paused tween still returns true because
  34564. * it is still playing, just paused).
  34565. */
  34566. Tween.prototype.update = function (time, autoStart) {
  34567. if (time === void 0) { time = now$1(); }
  34568. if (autoStart === void 0) { autoStart = true; }
  34569. if (this._isPaused)
  34570. return true;
  34571. var property;
  34572. var elapsed;
  34573. var endTime = this._startTime + this._duration;
  34574. if (!this._goToEnd && !this._isPlaying) {
  34575. if (time > endTime)
  34576. return false;
  34577. if (autoStart)
  34578. this.start(time);
  34579. }
  34580. this._goToEnd = false;
  34581. if (time < this._startTime) {
  34582. return true;
  34583. }
  34584. if (this._onStartCallbackFired === false) {
  34585. if (this._onStartCallback) {
  34586. this._onStartCallback(this._object);
  34587. }
  34588. this._onStartCallbackFired = true;
  34589. }
  34590. elapsed = (time - this._startTime) / this._duration;
  34591. elapsed = this._duration === 0 || elapsed > 1 ? 1 : elapsed;
  34592. var value = this._easingFunction(elapsed);
  34593. // properties transformations
  34594. this._updateProperties(this._object, this._valuesStart, this._valuesEnd, value);
  34595. if (this._onUpdateCallback) {
  34596. this._onUpdateCallback(this._object, elapsed);
  34597. }
  34598. if (elapsed === 1) {
  34599. if (this._repeat > 0) {
  34600. if (isFinite(this._repeat)) {
  34601. this._repeat--;
  34602. }
  34603. // Reassign starting values, restart by making startTime = now
  34604. for (property in this._valuesStartRepeat) {
  34605. if (!this._yoyo && typeof this._valuesEnd[property] === 'string') {
  34606. this._valuesStartRepeat[property] =
  34607. // eslint-disable-next-line
  34608. // @ts-ignore FIXME?
  34609. this._valuesStartRepeat[property] + parseFloat(this._valuesEnd[property]);
  34610. }
  34611. if (this._yoyo) {
  34612. this._swapEndStartRepeatValues(property);
  34613. }
  34614. this._valuesStart[property] = this._valuesStartRepeat[property];
  34615. }
  34616. if (this._yoyo) {
  34617. this._reversed = !this._reversed;
  34618. }
  34619. if (this._repeatDelayTime !== undefined) {
  34620. this._startTime = time + this._repeatDelayTime;
  34621. }
  34622. else {
  34623. this._startTime = time + this._delayTime;
  34624. }
  34625. if (this._onRepeatCallback) {
  34626. this._onRepeatCallback(this._object);
  34627. }
  34628. return true;
  34629. }
  34630. else {
  34631. if (this._onCompleteCallback) {
  34632. this._onCompleteCallback(this._object);
  34633. }
  34634. for (var i = 0, numChainedTweens = this._chainedTweens.length; i < numChainedTweens; i++) {
  34635. // Make the chained tweens start exactly at the time they should,
  34636. // even if the `update()` method was called way past the duration of the tween
  34637. this._chainedTweens[i].start(this._startTime + this._duration);
  34638. }
  34639. this._isPlaying = false;
  34640. return false;
  34641. }
  34642. }
  34643. return true;
  34644. };
  34645. Tween.prototype._updateProperties = function (_object, _valuesStart, _valuesEnd, value) {
  34646. for (var property in _valuesEnd) {
  34647. // Don't update properties that do not exist in the source object
  34648. if (_valuesStart[property] === undefined) {
  34649. continue;
  34650. }
  34651. var start = _valuesStart[property] || 0;
  34652. var end = _valuesEnd[property];
  34653. var startIsArray = Array.isArray(_object[property]);
  34654. var endIsArray = Array.isArray(end);
  34655. var isInterpolationList = !startIsArray && endIsArray;
  34656. if (isInterpolationList) {
  34657. _object[property] = this._interpolationFunction(end, value);
  34658. }
  34659. else if (typeof end === 'object' && end) {
  34660. // eslint-disable-next-line
  34661. // @ts-ignore FIXME?
  34662. this._updateProperties(_object[property], start, end, value);
  34663. }
  34664. else {
  34665. // Parses relative end values with start as base (e.g.: +10, -3)
  34666. end = this._handleRelativeValue(start, end);
  34667. // Protect against non numeric properties.
  34668. if (typeof end === 'number') {
  34669. // eslint-disable-next-line
  34670. // @ts-ignore FIXME?
  34671. _object[property] = start + (end - start) * value;
  34672. }
  34673. }
  34674. }
  34675. };
  34676. Tween.prototype._handleRelativeValue = function (start, end) {
  34677. if (typeof end !== 'string') {
  34678. return end;
  34679. }
  34680. if (end.charAt(0) === '+' || end.charAt(0) === '-') {
  34681. return start + parseFloat(end);
  34682. }
  34683. else {
  34684. return parseFloat(end);
  34685. }
  34686. };
  34687. Tween.prototype._swapEndStartRepeatValues = function (property) {
  34688. var tmp = this._valuesStartRepeat[property];
  34689. var endValue = this._valuesEnd[property];
  34690. if (typeof endValue === 'string') {
  34691. this._valuesStartRepeat[property] = this._valuesStartRepeat[property] + parseFloat(endValue);
  34692. }
  34693. else {
  34694. this._valuesStartRepeat[property] = this._valuesEnd[property];
  34695. }
  34696. this._valuesEnd[property] = tmp;
  34697. };
  34698. return Tween;
  34699. }());
  34700. var VERSION = '18.6.4';
  34701. /**
  34702. * Tween.js - Licensed under the MIT license
  34703. * https://github.com/tweenjs/tween.js
  34704. * ----------------------------------------------
  34705. *
  34706. * See https://github.com/tweenjs/tween.js/graphs/contributors for the full list of contributors.
  34707. * Thank you all, you're awesome!
  34708. */
  34709. var nextId = Sequence.nextId;
  34710. /**
  34711. * Controlling groups of tweens
  34712. *
  34713. * Using the TWEEN singleton to manage your tweens can cause issues in large apps with many components.
  34714. * In these cases, you may want to create your own smaller groups of tweens.
  34715. */
  34716. var TWEEN = mainGroup;
  34717. // This is the best way to export things in a way that's compatible with both ES
  34718. // Modules and CommonJS, without build hacks, and so as not to break the
  34719. // existing API.
  34720. // https://github.com/rollup/rollup/issues/1961#issuecomment-423037881
  34721. var getAll = TWEEN.getAll.bind(TWEEN);
  34722. var removeAll = TWEEN.removeAll.bind(TWEEN);
  34723. var add = TWEEN.add.bind(TWEEN);
  34724. var remove = TWEEN.remove.bind(TWEEN);
  34725. var update = TWEEN.update.bind(TWEEN);
  34726. var exports$1 = {
  34727. Easing: Easing,
  34728. Group: Group,
  34729. Interpolation: Interpolation,
  34730. now: now$1,
  34731. Sequence: Sequence,
  34732. nextId: nextId,
  34733. Tween: Tween,
  34734. VERSION: VERSION,
  34735. getAll: getAll,
  34736. removeAll: removeAll,
  34737. add: add,
  34738. remove: remove,
  34739. update: update,
  34740. };
  34741. function styleInject(css, ref) {
  34742. if (ref === void 0) ref = {};
  34743. var insertAt = ref.insertAt;
  34744. if (!css || typeof document === 'undefined') {
  34745. return;
  34746. }
  34747. var head = document.head || document.getElementsByTagName('head')[0];
  34748. var style = document.createElement('style');
  34749. style.type = 'text/css';
  34750. if (insertAt === 'top') {
  34751. if (head.firstChild) {
  34752. head.insertBefore(style, head.firstChild);
  34753. } else {
  34754. head.appendChild(style);
  34755. }
  34756. } else {
  34757. head.appendChild(style);
  34758. }
  34759. if (style.styleSheet) {
  34760. style.styleSheet.cssText = css;
  34761. } else {
  34762. style.appendChild(document.createTextNode(css));
  34763. }
  34764. }
  34765. var css_248z = ".scene-nav-info {\n bottom: 5px;\n width: 100%;\n text-align: center;\n color: slategrey;\n opacity: 0.7;\n font-size: 10px;\n}\n\n.scene-tooltip {\n color: lavender;\n font-size: 15px;\n}\n\n.scene-nav-info, .scene-tooltip {\n position: absolute;\n font-family: sans-serif;\n pointer-events: none;\n}\n\n.scene-container canvas:focus {\n outline: none;\n}";
  34766. styleInject(css_248z);
  34767. function _defineProperty(obj, key, value) {
  34768. if (key in obj) {
  34769. Object.defineProperty(obj, key, {
  34770. value: value,
  34771. enumerable: true,
  34772. configurable: true,
  34773. writable: true
  34774. });
  34775. } else {
  34776. obj[key] = value;
  34777. }
  34778. return obj;
  34779. }
  34780. function _slicedToArray(arr, i) {
  34781. return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
  34782. }
  34783. function _toConsumableArray(arr) {
  34784. return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
  34785. }
  34786. function _arrayWithoutHoles(arr) {
  34787. if (Array.isArray(arr)) return _arrayLikeToArray(arr);
  34788. }
  34789. function _arrayWithHoles(arr) {
  34790. if (Array.isArray(arr)) return arr;
  34791. }
  34792. function _iterableToArray(iter) {
  34793. if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
  34794. }
  34795. function _iterableToArrayLimit(arr, i) {
  34796. var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
  34797. if (_i == null) return;
  34798. var _arr = [];
  34799. var _n = true;
  34800. var _d = false;
  34801. var _s, _e;
  34802. try {
  34803. for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
  34804. _arr.push(_s.value);
  34805. if (i && _arr.length === i) break;
  34806. }
  34807. } catch (err) {
  34808. _d = true;
  34809. _e = err;
  34810. } finally {
  34811. try {
  34812. if (!_n && _i["return"] != null) _i["return"]();
  34813. } finally {
  34814. if (_d) throw _e;
  34815. }
  34816. }
  34817. return _arr;
  34818. }
  34819. function _unsupportedIterableToArray(o, minLen) {
  34820. if (!o) return;
  34821. if (typeof o === "string") return _arrayLikeToArray(o, minLen);
  34822. var n = Object.prototype.toString.call(o).slice(8, -1);
  34823. if (n === "Object" && o.constructor) n = o.constructor.name;
  34824. if (n === "Map" || n === "Set") return Array.from(o);
  34825. if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
  34826. }
  34827. function _arrayLikeToArray(arr, len) {
  34828. if (len == null || len > arr.length) len = arr.length;
  34829. for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  34830. return arr2;
  34831. }
  34832. function _nonIterableSpread() {
  34833. throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  34834. }
  34835. function _nonIterableRest() {
  34836. throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  34837. }
  34838. var three$1 = window.THREE ? window.THREE // Prefer consumption from global THREE, if exists
  34839. : {
  34840. WebGLRenderer: WebGLRenderer,
  34841. Scene: Scene,
  34842. PerspectiveCamera: PerspectiveCamera,
  34843. Raycaster: Raycaster,
  34844. TextureLoader: TextureLoader,
  34845. Vector2: Vector2,
  34846. Vector3: Vector3,
  34847. Box3: Box3,
  34848. Color: Color,
  34849. Mesh: Mesh,
  34850. SphereGeometry: SphereGeometry,
  34851. MeshBasicMaterial: MeshBasicMaterial,
  34852. BackSide: BackSide,
  34853. EventDispatcher: EventDispatcher,
  34854. MOUSE: MOUSE,
  34855. Quaternion: Quaternion,
  34856. Spherical: Spherical,
  34857. Clock: Clock
  34858. };
  34859. var threeRenderObjects = index$2({
  34860. props: {
  34861. width: {
  34862. "default": window.innerWidth,
  34863. onChange: function onChange(width, state, prevWidth) {
  34864. isNaN(width) && (state.width = prevWidth);
  34865. }
  34866. },
  34867. height: {
  34868. "default": window.innerHeight,
  34869. onChange: function onChange(height, state, prevHeight) {
  34870. isNaN(height) && (state.height = prevHeight);
  34871. }
  34872. },
  34873. backgroundColor: {
  34874. "default": '#000011'
  34875. },
  34876. backgroundImageUrl: {},
  34877. onBackgroundImageLoaded: {},
  34878. showNavInfo: {
  34879. "default": true
  34880. },
  34881. skyRadius: {
  34882. "default": 50000
  34883. },
  34884. objects: {
  34885. "default": []
  34886. },
  34887. enablePointerInteraction: {
  34888. "default": true,
  34889. onChange: function onChange(_, state) {
  34890. // Reset hover state
  34891. state.hoverObj = null;
  34892. if (state.toolTipElem) state.toolTipElem.innerHTML = '';
  34893. },
  34894. triggerUpdate: false
  34895. },
  34896. lineHoverPrecision: {
  34897. "default": 1,
  34898. triggerUpdate: false
  34899. },
  34900. hoverOrderComparator: {
  34901. "default": function _default() {
  34902. return -1;
  34903. },
  34904. triggerUpdate: false
  34905. },
  34906. // keep existing order by default
  34907. hoverFilter: {
  34908. "default": function _default() {
  34909. return true;
  34910. },
  34911. triggerUpdate: false
  34912. },
  34913. // exclude objects from interaction
  34914. tooltipContent: {
  34915. triggerUpdate: false
  34916. },
  34917. hoverDuringDrag: {
  34918. "default": false,
  34919. triggerUpdate: false
  34920. },
  34921. clickAfterDrag: {
  34922. "default": false,
  34923. triggerUpdate: false
  34924. },
  34925. onHover: {
  34926. "default": function _default() {},
  34927. triggerUpdate: false
  34928. },
  34929. onClick: {
  34930. "default": function _default() {},
  34931. triggerUpdate: false
  34932. },
  34933. onRightClick: {
  34934. triggerUpdate: false
  34935. }
  34936. },
  34937. methods: {
  34938. tick: function tick(state) {
  34939. if (state.initialised) {
  34940. state.controls.update && state.controls.update(state.clock.getDelta()); // timedelta is required for fly controls
  34941. state.postProcessingComposer ? state.postProcessingComposer.render() // if using postprocessing, switch the output to it
  34942. : state.renderer.render(state.scene, state.camera);
  34943. state.extraRenderers.forEach(function (r) {
  34944. return r.render(state.scene, state.camera);
  34945. });
  34946. if (state.enablePointerInteraction) {
  34947. // Update tooltip and trigger onHover events
  34948. var topObject = null;
  34949. if (state.hoverDuringDrag || !state.isPointerDragging) {
  34950. var intersects = this.intersectingObjects(state.pointerPos.x, state.pointerPos.y).filter(function (d) {
  34951. return state.hoverFilter(d.object);
  34952. }).sort(function (a, b) {
  34953. return state.hoverOrderComparator(a.object, b.object);
  34954. });
  34955. var topIntersect = intersects.length ? intersects[0] : null;
  34956. topObject = topIntersect ? topIntersect.object : null;
  34957. state.intersectionPoint = topIntersect ? topIntersect.point : null;
  34958. }
  34959. if (topObject !== state.hoverObj) {
  34960. state.onHover(topObject, state.hoverObj);
  34961. state.toolTipElem.innerHTML = topObject ? index$1(state.tooltipContent)(topObject) || '' : '';
  34962. state.hoverObj = topObject;
  34963. }
  34964. }
  34965. exports$1.update(); // update camera animation tweens
  34966. }
  34967. return this;
  34968. },
  34969. getPointerPos: function getPointerPos(state) {
  34970. var _state$pointerPos = state.pointerPos,
  34971. x = _state$pointerPos.x,
  34972. y = _state$pointerPos.y;
  34973. return {
  34974. x: x,
  34975. y: y
  34976. };
  34977. },
  34978. cameraPosition: function cameraPosition(state, position, lookAt, transitionDuration) {
  34979. var camera = state.camera; // Setter
  34980. if (position && state.initialised) {
  34981. var finalPos = position;
  34982. var finalLookAt = lookAt || {
  34983. x: 0,
  34984. y: 0,
  34985. z: 0
  34986. };
  34987. if (!transitionDuration) {
  34988. // no animation
  34989. setCameraPos(finalPos);
  34990. setLookAt(finalLookAt);
  34991. } else {
  34992. var camPos = Object.assign({}, camera.position);
  34993. var camLookAt = getLookAt();
  34994. new exports$1.Tween(camPos).to(finalPos, transitionDuration).easing(exports$1.Easing.Quadratic.Out).onUpdate(setCameraPos).start(); // Face direction in 1/3rd of time
  34995. new exports$1.Tween(camLookAt).to(finalLookAt, transitionDuration / 3).easing(exports$1.Easing.Quadratic.Out).onUpdate(setLookAt).start();
  34996. }
  34997. return this;
  34998. } // Getter
  34999. return Object.assign({}, camera.position, {
  35000. lookAt: getLookAt()
  35001. }); //
  35002. function setCameraPos(pos) {
  35003. var x = pos.x,
  35004. y = pos.y,
  35005. z = pos.z;
  35006. if (x !== undefined) camera.position.x = x;
  35007. if (y !== undefined) camera.position.y = y;
  35008. if (z !== undefined) camera.position.z = z;
  35009. }
  35010. function setLookAt(lookAt) {
  35011. state.controls.target = new three$1.Vector3(lookAt.x, lookAt.y, lookAt.z);
  35012. }
  35013. function getLookAt() {
  35014. return Object.assign(new three$1.Vector3(0, 0, -1000).applyQuaternion(camera.quaternion).add(camera.position));
  35015. }
  35016. },
  35017. zoomToFit: function zoomToFit(state) {
  35018. var transitionDuration = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  35019. var padding = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 10;
  35020. for (var _len = arguments.length, bboxArgs = new Array(_len > 3 ? _len - 3 : 0), _key = 3; _key < _len; _key++) {
  35021. bboxArgs[_key - 3] = arguments[_key];
  35022. }
  35023. return this.fitToBbox(this.getBbox.apply(this, bboxArgs), transitionDuration, padding);
  35024. },
  35025. fitToBbox: function fitToBbox(state, bbox) {
  35026. var transitionDuration = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
  35027. var padding = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 10;
  35028. // based on https://discourse.threejs.org/t/camera-zoom-to-fit-object/936/24
  35029. var camera = state.camera;
  35030. if (bbox) {
  35031. var center = new three$1.Vector3(0, 0, 0); // reset camera aim to center
  35032. var maxBoxSide = Math.max.apply(Math, _toConsumableArray(Object.entries(bbox).map(function (_ref) {
  35033. var _ref2 = _slicedToArray(_ref, 2),
  35034. coordType = _ref2[0],
  35035. coords = _ref2[1];
  35036. return Math.max.apply(Math, _toConsumableArray(coords.map(function (c) {
  35037. return Math.abs(center[coordType] - c);
  35038. })));
  35039. }))) * 2; // find distance that fits whole bbox within padded fov
  35040. var paddedFov = (1 - padding * 2 / state.height) * camera.fov;
  35041. var fitHeightDistance = maxBoxSide / Math.atan(paddedFov * Math.PI / 180);
  35042. var fitWidthDistance = fitHeightDistance / camera.aspect;
  35043. var distance = Math.max(fitHeightDistance, fitWidthDistance);
  35044. if (distance > 0) {
  35045. var newCameraPosition = center.clone().sub(camera.position).normalize().multiplyScalar(-distance);
  35046. this.cameraPosition(newCameraPosition, center, transitionDuration);
  35047. }
  35048. }
  35049. return this;
  35050. },
  35051. getBbox: function getBbox(state) {
  35052. var objFilter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {
  35053. return true;
  35054. };
  35055. var box = new three$1.Box3(new three$1.Vector3(0, 0, 0), new three$1.Vector3(0, 0, 0));
  35056. var objs = state.objects.filter(objFilter);
  35057. if (!objs.length) return null;
  35058. objs.forEach(function (obj) {
  35059. return box.expandByObject(obj);
  35060. }); // extract global x,y,z min/max
  35061. return Object.assign.apply(Object, _toConsumableArray(['x', 'y', 'z'].map(function (c) {
  35062. return _defineProperty({}, c, [box.min[c], box.max[c]]);
  35063. })));
  35064. },
  35065. getScreenCoords: function getScreenCoords(state, x, y, z) {
  35066. var vec = new three$1.Vector3(x, y, z);
  35067. vec.project(this.camera()); // project to the camera plane
  35068. return {
  35069. // align relative pos to canvas dimensions
  35070. x: (vec.x + 1) * state.width / 2,
  35071. y: -(vec.y - 1) * state.height / 2
  35072. };
  35073. },
  35074. getSceneCoords: function getSceneCoords(state, screenX, screenY) {
  35075. var distance = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
  35076. var relCoords = new three$1.Vector2(screenX / state.width * 2 - 1, -(screenY / state.height) * 2 + 1);
  35077. var raycaster = new three$1.Raycaster();
  35078. raycaster.setFromCamera(relCoords, state.camera);
  35079. return Object.assign({}, raycaster.ray.at(distance, new three$1.Vector3()));
  35080. },
  35081. intersectingObjects: function intersectingObjects(state, x, y) {
  35082. var relCoords = new three$1.Vector2(x / state.width * 2 - 1, -(y / state.height) * 2 + 1);
  35083. var raycaster = new three$1.Raycaster();
  35084. raycaster.params.Line.threshold = state.lineHoverPrecision; // set linePrecision
  35085. raycaster.setFromCamera(relCoords, state.camera);
  35086. return raycaster.intersectObjects(state.objects, true);
  35087. },
  35088. renderer: function renderer(state) {
  35089. return state.renderer;
  35090. },
  35091. scene: function scene(state) {
  35092. return state.scene;
  35093. },
  35094. camera: function camera(state) {
  35095. return state.camera;
  35096. },
  35097. postProcessingComposer: function postProcessingComposer(state) {
  35098. return state.postProcessingComposer;
  35099. },
  35100. controls: function controls(state) {
  35101. return state.controls;
  35102. },
  35103. tbControls: function tbControls(state) {
  35104. return state.controls;
  35105. } // to be deprecated
  35106. },
  35107. stateInit: function stateInit() {
  35108. return {
  35109. scene: new three$1.Scene(),
  35110. camera: new three$1.PerspectiveCamera(),
  35111. clock: new three$1.Clock()
  35112. };
  35113. },
  35114. init: function init(domNode, state) {
  35115. var _ref4 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},
  35116. _ref4$controlType = _ref4.controlType,
  35117. controlType = _ref4$controlType === void 0 ? 'trackball' : _ref4$controlType,
  35118. _ref4$rendererConfig = _ref4.rendererConfig,
  35119. rendererConfig = _ref4$rendererConfig === void 0 ? {} : _ref4$rendererConfig,
  35120. _ref4$extraRenderers = _ref4.extraRenderers,
  35121. extraRenderers = _ref4$extraRenderers === void 0 ? [] : _ref4$extraRenderers,
  35122. _ref4$waitForLoadComp = _ref4.waitForLoadComplete,
  35123. waitForLoadComplete = _ref4$waitForLoadComp === void 0 ? true : _ref4$waitForLoadComp;
  35124. // Wipe DOM
  35125. domNode.innerHTML = ''; // Add relative container
  35126. domNode.appendChild(state.container = document.createElement('div'));
  35127. state.container.className = 'scene-container';
  35128. state.container.style.position = 'relative'; // Add nav info section
  35129. state.container.appendChild(state.navInfo = document.createElement('div'));
  35130. state.navInfo.className = 'scene-nav-info';
  35131. state.navInfo.textContent = {
  35132. orbit: 'Left-click: rotate, Mouse-wheel/middle-click: zoom, Right-click: pan',
  35133. trackball: 'Left-click: rotate, Mouse-wheel/middle-click: zoom, Right-click: pan',
  35134. fly: 'WASD: move, R|F: up | down, Q|E: roll, up|down: pitch, left|right: yaw'
  35135. }[controlType] || '';
  35136. state.navInfo.style.display = state.showNavInfo ? null : 'none'; // Setup tooltip
  35137. state.toolTipElem = document.createElement('div');
  35138. state.toolTipElem.classList.add('scene-tooltip');
  35139. state.container.appendChild(state.toolTipElem); // Capture pointer coords on move or touchstart
  35140. state.pointerPos = new three$1.Vector2();
  35141. state.pointerPos.x = -2; // Initialize off canvas
  35142. state.pointerPos.y = -2;
  35143. ['pointermove', 'pointerdown'].forEach(function (evType) {
  35144. return state.container.addEventListener(evType, function (ev) {
  35145. // track click state
  35146. evType === 'pointerdown' && (state.isPointerPressed = true); // detect point drag
  35147. !state.isPointerDragging && ev.type === 'pointermove' && (ev.pressure > 0 || state.isPointerPressed) // ev.pressure always 0 on Safari, so we used the isPointerPressed tracker
  35148. && (ev.pointerType !== 'touch' || ev.movementX === undefined || [ev.movementX, ev.movementY].some(function (m) {
  35149. return Math.abs(m) > 1;
  35150. })) // relax drag trigger sensitivity on touch events
  35151. && (state.isPointerDragging = true);
  35152. if (state.enablePointerInteraction) {
  35153. // update the pointer pos
  35154. var offset = getOffset(state.container);
  35155. state.pointerPos.x = ev.pageX - offset.left;
  35156. state.pointerPos.y = ev.pageY - offset.top; // Move tooltip
  35157. state.toolTipElem.style.top = "".concat(state.pointerPos.y, "px");
  35158. state.toolTipElem.style.left = "".concat(state.pointerPos.x, "px");
  35159. state.toolTipElem.style.transform = "translate(-".concat(state.pointerPos.x / state.width * 100, "%, 21px)"); // adjust horizontal position to not exceed canvas boundaries
  35160. }
  35161. function getOffset(el) {
  35162. var rect = el.getBoundingClientRect(),
  35163. scrollLeft = window.pageXOffset || document.documentElement.scrollLeft,
  35164. scrollTop = window.pageYOffset || document.documentElement.scrollTop;
  35165. return {
  35166. top: rect.top + scrollTop,
  35167. left: rect.left + scrollLeft
  35168. };
  35169. }
  35170. }, {
  35171. passive: true
  35172. });
  35173. }); // Handle click events on objs
  35174. state.container.addEventListener('pointerup', function (ev) {
  35175. state.isPointerPressed = false;
  35176. if (state.isPointerDragging) {
  35177. state.isPointerDragging = false;
  35178. if (!state.clickAfterDrag) return; // don't trigger onClick after pointer drag (camera motion via controls)
  35179. }
  35180. requestAnimationFrame(function () {
  35181. // trigger click events asynchronously, to allow hoverObj to be set (on frame)
  35182. if (ev.button === 0) {
  35183. // left-click
  35184. state.onClick(state.hoverObj || null, ev, state.intersectionPoint); // trigger background clicks with null
  35185. }
  35186. if (ev.button === 2 && state.onRightClick) {
  35187. // right-click
  35188. state.onRightClick(state.hoverObj || null, ev, state.intersectionPoint);
  35189. }
  35190. });
  35191. }, {
  35192. passive: true,
  35193. capture: true
  35194. }); // use capture phase to prevent propagation blocking from controls (specifically for fly)
  35195. state.container.addEventListener('contextmenu', function (ev) {
  35196. if (state.onRightClick) ev.preventDefault(); // prevent default contextmenu behavior and allow pointerup to fire instead
  35197. }); // Setup renderer, camera and controls
  35198. state.renderer = new three$1.WebGLRenderer(Object.assign({
  35199. antialias: true,
  35200. alpha: true
  35201. }, rendererConfig));
  35202. state.renderer.setPixelRatio(Math.min(2, window.devicePixelRatio)); // clamp device pixel ratio
  35203. state.container.appendChild(state.renderer.domElement); // Setup extra renderers
  35204. state.extraRenderers = extraRenderers;
  35205. state.extraRenderers.forEach(function (r) {
  35206. // overlay them on top of main renderer
  35207. r.domElement.style.position = 'absolute';
  35208. r.domElement.style.top = '0px';
  35209. r.domElement.style.pointerEvents = 'none';
  35210. state.container.appendChild(r.domElement);
  35211. }); // configure post-processing composer
  35212. state.postProcessingComposer = new EffectComposer(state.renderer);
  35213. state.postProcessingComposer.addPass(new RenderPass(state.scene, state.camera)); // render scene as first pass
  35214. // configure controls
  35215. state.controls = new {
  35216. trackball: TrackballControls,
  35217. orbit: OrbitControls,
  35218. fly: FlyControls
  35219. }[controlType](state.camera, state.renderer.domElement);
  35220. if (controlType === 'fly') {
  35221. state.controls.movementSpeed = 300;
  35222. state.controls.rollSpeed = Math.PI / 6;
  35223. state.controls.dragToLook = true;
  35224. }
  35225. if (controlType === 'trackball' || controlType === 'orbit') {
  35226. state.controls.minDistance = 0.1;
  35227. state.controls.maxDistance = state.skyRadius;
  35228. state.controls.addEventListener('start', function () {
  35229. state.controlsEngaged = true;
  35230. });
  35231. state.controls.addEventListener('change', function () {
  35232. if (state.controlsEngaged) {
  35233. state.controlsDragging = true;
  35234. }
  35235. });
  35236. state.controls.addEventListener('end', function () {
  35237. state.controlsEngaged = false;
  35238. state.controlsDragging = false;
  35239. });
  35240. }
  35241. [state.renderer, state.postProcessingComposer].concat(_toConsumableArray(state.extraRenderers)).forEach(function (r) {
  35242. return r.setSize(state.width, state.height);
  35243. });
  35244. state.camera.aspect = state.width / state.height;
  35245. state.camera.updateProjectionMatrix();
  35246. state.camera.position.z = 1000; // add sky
  35247. state.scene.add(state.skysphere = new three$1.Mesh());
  35248. state.skysphere.visible = false;
  35249. state.loadComplete = state.scene.visible = !waitForLoadComplete;
  35250. window.scene = state.scene;
  35251. },
  35252. update: function update(state, changedProps) {
  35253. // resize canvas
  35254. if (state.width && state.height && (changedProps.hasOwnProperty('width') || changedProps.hasOwnProperty('height'))) {
  35255. state.container.style.width = state.width;
  35256. state.container.style.height = state.height;
  35257. [state.renderer, state.postProcessingComposer].concat(_toConsumableArray(state.extraRenderers)).forEach(function (r) {
  35258. return r.setSize(state.width, state.height);
  35259. });
  35260. state.camera.aspect = state.width / state.height;
  35261. state.camera.updateProjectionMatrix();
  35262. }
  35263. if (changedProps.hasOwnProperty('skyRadius') && state.skyRadius) {
  35264. state.controls.hasOwnProperty('maxDistance') && changedProps.skyRadius && (state.controls.maxDistance = state.skyRadius);
  35265. state.camera.far = state.skyRadius * 2.5;
  35266. state.camera.updateProjectionMatrix();
  35267. state.skysphere.geometry = new three$1.SphereGeometry(state.skyRadius);
  35268. }
  35269. if (changedProps.hasOwnProperty('backgroundColor')) {
  35270. var alpha = parseToRgb(state.backgroundColor).alpha;
  35271. if (alpha === undefined) alpha = 1;
  35272. state.renderer.setClearColor(new three$1.Color(curriedOpacify(1, state.backgroundColor)), alpha);
  35273. }
  35274. if (changedProps.hasOwnProperty('backgroundImageUrl')) {
  35275. if (!state.backgroundImageUrl) {
  35276. state.skysphere.visible = false;
  35277. state.skysphere.material.map = null;
  35278. !state.loadComplete && finishLoad();
  35279. } else {
  35280. new three$1.TextureLoader().load(state.backgroundImageUrl, function (texture) {
  35281. state.skysphere.material = new three$1.MeshBasicMaterial({
  35282. map: texture,
  35283. side: three$1.BackSide
  35284. });
  35285. state.skysphere.visible = true; // triggered when background image finishes loading (asynchronously to allow 1 frame to load texture)
  35286. state.onBackgroundImageLoaded && setTimeout(state.onBackgroundImageLoaded);
  35287. !state.loadComplete && finishLoad();
  35288. });
  35289. }
  35290. }
  35291. changedProps.hasOwnProperty('showNavInfo') && (state.navInfo.style.display = state.showNavInfo ? null : 'none');
  35292. if (changedProps.hasOwnProperty('objects')) {
  35293. (changedProps.objects || []).forEach(function (obj) {
  35294. return state.scene.remove(obj);
  35295. }); // Clear the place
  35296. state.objects.forEach(function (obj) {
  35297. return state.scene.add(obj);
  35298. }); // Add to scene
  35299. } //
  35300. function finishLoad() {
  35301. state.loadComplete = state.scene.visible = true;
  35302. }
  35303. }
  35304. });
  35305. function linkKapsule (kapsulePropName, kapsuleType) {
  35306. var dummyK = new kapsuleType(); // To extract defaults
  35307. return {
  35308. linkProp: function linkProp(prop) {
  35309. // link property config
  35310. return {
  35311. "default": dummyK[prop](),
  35312. onChange: function onChange(v, state) {
  35313. state[kapsulePropName][prop](v);
  35314. },
  35315. triggerUpdate: false
  35316. };
  35317. },
  35318. linkMethod: function linkMethod(method) {
  35319. // link method pass-through
  35320. return function (state) {
  35321. var kapsuleInstance = state[kapsulePropName];
  35322. for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  35323. args[_key - 1] = arguments[_key];
  35324. }
  35325. var returnVal = kapsuleInstance[method].apply(kapsuleInstance, args);
  35326. return returnVal === kapsuleInstance ? this // chain based on the parent object, not the inner kapsule
  35327. : returnVal;
  35328. };
  35329. }
  35330. };
  35331. }
  35332. var three = window.THREE ? window.THREE // Prefer consumption from global THREE, if exists
  35333. : {
  35334. AmbientLight: AmbientLight,
  35335. DirectionalLight: DirectionalLight,
  35336. Vector3: Vector3
  35337. };
  35338. var CAMERA_DISTANCE2NODES_FACTOR = 170; //
  35339. // Expose config from forceGraph
  35340. var bindFG = linkKapsule('forceGraph', threeForcegraph);
  35341. var linkedFGProps = Object.assign.apply(Object, _toConsumableArray$4(['jsonUrl', 'graphData', 'numDimensions', 'dagMode', 'dagLevelDistance', 'dagNodeFilter', 'onDagError', 'nodeRelSize', 'nodeId', 'nodeVal', 'nodeResolution', 'nodeColor', 'nodeAutoColorBy', 'nodeOpacity', 'nodeVisibility', 'nodeThreeObject', 'nodeThreeObjectExtend', 'linkSource', 'linkTarget', 'linkVisibility', 'linkColor', 'linkAutoColorBy', 'linkOpacity', 'linkWidth', 'linkResolution', 'linkCurvature', 'linkCurveRotation', 'linkMaterial', 'linkThreeObject', 'linkThreeObjectExtend', 'linkPositionUpdate', 'linkDirectionalArrowLength', 'linkDirectionalArrowColor', 'linkDirectionalArrowRelPos', 'linkDirectionalArrowResolution', 'linkDirectionalParticles', 'linkDirectionalParticleSpeed', 'linkDirectionalParticleWidth', 'linkDirectionalParticleColor', 'linkDirectionalParticleResolution', 'forceEngine', 'd3AlphaDecay', 'd3VelocityDecay', 'd3AlphaMin', 'ngraphPhysics', 'warmupTicks', 'cooldownTicks', 'cooldownTime', 'onEngineTick', 'onEngineStop'].map(function (p) {
  35342. return _defineProperty$3({}, p, bindFG.linkProp(p));
  35343. })));
  35344. var linkedFGMethods = Object.assign.apply(Object, _toConsumableArray$4(['refresh', 'getGraphBbox', 'd3Force', 'd3ReheatSimulation', 'emitParticle'].map(function (p) {
  35345. return _defineProperty$3({}, p, bindFG.linkMethod(p));
  35346. }))); // Expose config from renderObjs
  35347. var bindRenderObjs = linkKapsule('renderObjs', threeRenderObjects);
  35348. var linkedRenderObjsProps = Object.assign.apply(Object, _toConsumableArray$4(['width', 'height', 'backgroundColor', 'showNavInfo', 'enablePointerInteraction'].map(function (p) {
  35349. return _defineProperty$3({}, p, bindRenderObjs.linkProp(p));
  35350. })));
  35351. var linkedRenderObjsMethods = Object.assign.apply(Object, _toConsumableArray$4(['cameraPosition', 'postProcessingComposer'].map(function (p) {
  35352. return _defineProperty$3({}, p, bindRenderObjs.linkMethod(p));
  35353. })).concat([{
  35354. graph2ScreenCoords: bindRenderObjs.linkMethod('getScreenCoords'),
  35355. screen2GraphCoords: bindRenderObjs.linkMethod('getSceneCoords')
  35356. }])); //
  35357. var _3dForceGraph = index$2({
  35358. props: _objectSpread2$2(_objectSpread2$2({
  35359. nodeLabel: {
  35360. "default": 'name',
  35361. triggerUpdate: false
  35362. },
  35363. linkLabel: {
  35364. "default": 'name',
  35365. triggerUpdate: false
  35366. },
  35367. linkHoverPrecision: {
  35368. "default": 1,
  35369. onChange: function onChange(p, state) {
  35370. return state.renderObjs.lineHoverPrecision(p);
  35371. },
  35372. triggerUpdate: false
  35373. },
  35374. enableNavigationControls: {
  35375. "default": true,
  35376. onChange: function onChange(enable, state) {
  35377. var controls = state.renderObjs.controls();
  35378. if (controls) {
  35379. controls.enabled = enable;
  35380. }
  35381. },
  35382. triggerUpdate: false
  35383. },
  35384. enableNodeDrag: {
  35385. "default": true,
  35386. triggerUpdate: false
  35387. },
  35388. onNodeDrag: {
  35389. "default": function _default() {},
  35390. triggerUpdate: false
  35391. },
  35392. onNodeDragEnd: {
  35393. "default": function _default() {},
  35394. triggerUpdate: false
  35395. },
  35396. onNodeClick: {
  35397. triggerUpdate: false
  35398. },
  35399. onNodeRightClick: {
  35400. triggerUpdate: false
  35401. },
  35402. onNodeHover: {
  35403. triggerUpdate: false
  35404. },
  35405. onLinkClick: {
  35406. triggerUpdate: false
  35407. },
  35408. onLinkRightClick: {
  35409. triggerUpdate: false
  35410. },
  35411. onLinkHover: {
  35412. triggerUpdate: false
  35413. },
  35414. onBackgroundClick: {
  35415. triggerUpdate: false
  35416. },
  35417. onBackgroundRightClick: {
  35418. triggerUpdate: false
  35419. }
  35420. }, linkedFGProps), linkedRenderObjsProps),
  35421. methods: _objectSpread2$2(_objectSpread2$2({
  35422. zoomToFit: function zoomToFit(state, transitionDuration, padding) {
  35423. var _state$forceGraph;
  35424. for (var _len = arguments.length, bboxArgs = new Array(_len > 3 ? _len - 3 : 0), _key = 3; _key < _len; _key++) {
  35425. bboxArgs[_key - 3] = arguments[_key];
  35426. }
  35427. state.renderObjs.fitToBbox((_state$forceGraph = state.forceGraph).getGraphBbox.apply(_state$forceGraph, bboxArgs), transitionDuration, padding);
  35428. return this;
  35429. },
  35430. pauseAnimation: function pauseAnimation(state) {
  35431. if (state.animationFrameRequestId !== null) {
  35432. cancelAnimationFrame(state.animationFrameRequestId);
  35433. state.animationFrameRequestId = null;
  35434. }
  35435. return this;
  35436. },
  35437. resumeAnimation: function resumeAnimation(state) {
  35438. if (state.animationFrameRequestId === null) {
  35439. this._animationCycle();
  35440. }
  35441. return this;
  35442. },
  35443. _animationCycle: function _animationCycle(state) {
  35444. if (state.enablePointerInteraction) {
  35445. // reset canvas cursor (override dragControls cursor)
  35446. this.renderer().domElement.style.cursor = null;
  35447. } // Frame cycle
  35448. state.forceGraph.tickFrame();
  35449. state.renderObjs.tick();
  35450. state.animationFrameRequestId = requestAnimationFrame(this._animationCycle);
  35451. },
  35452. scene: function scene(state) {
  35453. return state.renderObjs.scene();
  35454. },
  35455. // Expose scene
  35456. camera: function camera(state) {
  35457. return state.renderObjs.camera();
  35458. },
  35459. // Expose camera
  35460. renderer: function renderer(state) {
  35461. return state.renderObjs.renderer();
  35462. },
  35463. // Expose renderer
  35464. controls: function controls(state) {
  35465. return state.renderObjs.controls();
  35466. },
  35467. // Expose controls
  35468. tbControls: function tbControls(state) {
  35469. return state.renderObjs.tbControls();
  35470. },
  35471. // To be deprecated
  35472. _destructor: function _destructor() {
  35473. this.pauseAnimation();
  35474. this.graphData({
  35475. nodes: [],
  35476. links: []
  35477. });
  35478. }
  35479. }, linkedFGMethods), linkedRenderObjsMethods),
  35480. stateInit: function stateInit(_ref5) {
  35481. var controlType = _ref5.controlType,
  35482. rendererConfig = _ref5.rendererConfig,
  35483. extraRenderers = _ref5.extraRenderers;
  35484. return {
  35485. forceGraph: new threeForcegraph(),
  35486. renderObjs: threeRenderObjects({
  35487. controlType: controlType,
  35488. rendererConfig: rendererConfig,
  35489. extraRenderers: extraRenderers
  35490. })
  35491. };
  35492. },
  35493. init: function init(domNode, state) {
  35494. // Wipe DOM
  35495. domNode.innerHTML = ''; // Add relative container
  35496. domNode.appendChild(state.container = document.createElement('div'));
  35497. state.container.style.position = 'relative'; // Add renderObjs
  35498. var roDomNode = document.createElement('div');
  35499. state.container.appendChild(roDomNode);
  35500. state.renderObjs(roDomNode);
  35501. var camera = state.renderObjs.camera();
  35502. var renderer = state.renderObjs.renderer();
  35503. var controls = state.renderObjs.controls();
  35504. controls.enabled = !!state.enableNavigationControls;
  35505. state.lastSetCameraZ = camera.position.z; // Add info space
  35506. var infoElem;
  35507. state.container.appendChild(infoElem = document.createElement('div'));
  35508. infoElem.className = 'graph-info-msg';
  35509. infoElem.textContent = ''; // config forcegraph
  35510. state.forceGraph.onLoading(function () {
  35511. infoElem.textContent = 'Loading...';
  35512. }).onFinishLoading(function () {
  35513. infoElem.textContent = '';
  35514. }).onUpdate(function () {
  35515. // sync graph data structures
  35516. state.graphData = state.forceGraph.graphData(); // re-aim camera, if still in default position (not user modified)
  35517. if (camera.position.x === 0 && camera.position.y === 0 && camera.position.z === state.lastSetCameraZ && state.graphData.nodes.length) {
  35518. camera.lookAt(state.forceGraph.position);
  35519. state.lastSetCameraZ = camera.position.z = Math.cbrt(state.graphData.nodes.length) * CAMERA_DISTANCE2NODES_FACTOR;
  35520. }
  35521. }).onFinishUpdate(function () {
  35522. // Setup node drag interaction
  35523. if (state._dragControls) {
  35524. var curNodeDrag = state.graphData.nodes.find(function (node) {
  35525. return node.__initialFixedPos && !node.__disposeControlsAfterDrag;
  35526. }); // detect if there's a node being dragged using the existing drag controls
  35527. if (curNodeDrag) {
  35528. curNodeDrag.__disposeControlsAfterDrag = true; // postpone previous controls disposal until drag ends
  35529. } else {
  35530. state._dragControls.dispose(); // cancel previous drag controls
  35531. }
  35532. state._dragControls = undefined;
  35533. }
  35534. if (state.enableNodeDrag && state.enablePointerInteraction && state.forceEngine === 'd3') {
  35535. // Can't access node positions programatically in ngraph
  35536. var dragControls = state._dragControls = new DragControls(state.graphData.nodes.map(function (node) {
  35537. return node.__threeObj;
  35538. }).filter(function (obj) {
  35539. return obj;
  35540. }), camera, renderer.domElement);
  35541. dragControls.addEventListener('dragstart', function (event) {
  35542. controls.enabled = false; // Disable controls while dragging
  35543. // track drag object movement
  35544. event.object.__initialPos = event.object.position.clone();
  35545. event.object.__prevPos = event.object.position.clone();
  35546. var node = getGraphObj(event.object).__data;
  35547. !node.__initialFixedPos && (node.__initialFixedPos = {
  35548. fx: node.fx,
  35549. fy: node.fy,
  35550. fz: node.fz
  35551. });
  35552. !node.__initialPos && (node.__initialPos = {
  35553. x: node.x,
  35554. y: node.y,
  35555. z: node.z
  35556. }); // lock node
  35557. ['x', 'y', 'z'].forEach(function (c) {
  35558. return node["f".concat(c)] = node[c];
  35559. }); // drag cursor
  35560. renderer.domElement.classList.add('grabbable');
  35561. });
  35562. dragControls.addEventListener('drag', function (event) {
  35563. var nodeObj = getGraphObj(event.object);
  35564. if (!event.object.hasOwnProperty('__graphObjType')) {
  35565. // If dragging a child of the node, update the node object instead
  35566. var initPos = event.object.__initialPos;
  35567. var prevPos = event.object.__prevPos;
  35568. var _newPos = event.object.position;
  35569. nodeObj.position.add(_newPos.clone().sub(prevPos)); // translate node object by the motion delta
  35570. prevPos.copy(_newPos);
  35571. _newPos.copy(initPos); // reset child back to its initial position
  35572. }
  35573. var node = nodeObj.__data;
  35574. var newPos = nodeObj.position;
  35575. var translate = {
  35576. x: newPos.x - node.x,
  35577. y: newPos.y - node.y,
  35578. z: newPos.z - node.z
  35579. }; // Move fx/fy/fz (and x/y/z) of nodes based on object new position
  35580. ['x', 'y', 'z'].forEach(function (c) {
  35581. return node["f".concat(c)] = node[c] = newPos[c];
  35582. });
  35583. state.forceGraph.d3AlphaTarget(0.3) // keep engine running at low intensity throughout drag
  35584. .resetCountdown(); // prevent freeze while dragging
  35585. node.__dragged = true;
  35586. state.onNodeDrag(node, translate);
  35587. });
  35588. dragControls.addEventListener('dragend', function (event) {
  35589. delete event.object.__initialPos; // remove tracking attributes
  35590. delete event.object.__prevPos;
  35591. var node = getGraphObj(event.object).__data; // dispose previous controls if needed
  35592. if (node.__disposeControlsAfterDrag) {
  35593. dragControls.dispose();
  35594. delete node.__disposeControlsAfterDrag;
  35595. }
  35596. var initFixedPos = node.__initialFixedPos;
  35597. var initPos = node.__initialPos;
  35598. var translate = {
  35599. x: initPos.x - node.x,
  35600. y: initPos.y - node.y,
  35601. z: initPos.z - node.z
  35602. };
  35603. if (initFixedPos) {
  35604. ['x', 'y', 'z'].forEach(function (c) {
  35605. var fc = "f".concat(c);
  35606. if (initFixedPos[fc] === undefined) {
  35607. delete node[fc];
  35608. }
  35609. });
  35610. delete node.__initialFixedPos;
  35611. delete node.__initialPos;
  35612. if (node.__dragged) {
  35613. delete node.__dragged;
  35614. state.onNodeDragEnd(node, translate);
  35615. }
  35616. }
  35617. state.forceGraph.d3AlphaTarget(0) // release engine low intensity
  35618. .resetCountdown(); // let the engine readjust after releasing fixed nodes
  35619. if (state.enableNavigationControls) {
  35620. controls.enabled = true; // Re-enable controls
  35621. controls.domElement && controls.domElement.ownerDocument && controls.domElement.ownerDocument.dispatchEvent( // simulate mouseup to ensure the controls don't take over after dragend
  35622. new PointerEvent('pointerup', {
  35623. pointerType: 'touch'
  35624. }));
  35625. } // clear cursor
  35626. renderer.domElement.classList.remove('grabbable');
  35627. });
  35628. }
  35629. }); // config renderObjs
  35630. state.renderObjs.objects([// Populate scene
  35631. new three.AmbientLight(0xbbbbbb), new three.DirectionalLight(0xffffff, 0.6), state.forceGraph]).hoverOrderComparator(function (a, b) {
  35632. // Prioritize graph objects
  35633. var aObj = getGraphObj(a);
  35634. if (!aObj) return 1;
  35635. var bObj = getGraphObj(b);
  35636. if (!bObj) return -1; // Prioritize nodes over links
  35637. var isNode = function isNode(o) {
  35638. return o.__graphObjType === 'node';
  35639. };
  35640. return isNode(bObj) - isNode(aObj);
  35641. }).tooltipContent(function (obj) {
  35642. var graphObj = getGraphObj(obj);
  35643. return graphObj ? index$1(state["".concat(graphObj.__graphObjType, "Label")])(graphObj.__data) || '' : '';
  35644. }).hoverDuringDrag(false).onHover(function (obj) {
  35645. // Update tooltip and trigger onHover events
  35646. var hoverObj = getGraphObj(obj);
  35647. if (hoverObj !== state.hoverObj) {
  35648. var prevObjType = state.hoverObj ? state.hoverObj.__graphObjType : null;
  35649. var prevObjData = state.hoverObj ? state.hoverObj.__data : null;
  35650. var objType = hoverObj ? hoverObj.__graphObjType : null;
  35651. var objData = hoverObj ? hoverObj.__data : null;
  35652. if (prevObjType && prevObjType !== objType) {
  35653. // Hover out
  35654. var fn = state["on".concat(prevObjType === 'node' ? 'Node' : 'Link', "Hover")];
  35655. fn && fn(null, prevObjData);
  35656. }
  35657. if (objType) {
  35658. // Hover in
  35659. var _fn = state["on".concat(objType === 'node' ? 'Node' : 'Link', "Hover")];
  35660. _fn && _fn(objData, prevObjType === objType ? prevObjData : null);
  35661. } // set pointer if hovered object is clickable
  35662. renderer.domElement.classList[hoverObj && state["on".concat(objType === 'node' ? 'Node' : 'Link', "Click")] || !hoverObj && state.onBackgroundClick ? 'add' : 'remove']('clickable');
  35663. state.hoverObj = hoverObj;
  35664. }
  35665. }).clickAfterDrag(false).onClick(function (obj, ev) {
  35666. var graphObj = getGraphObj(obj);
  35667. if (graphObj) {
  35668. var fn = state["on".concat(graphObj.__graphObjType === 'node' ? 'Node' : 'Link', "Click")];
  35669. fn && fn(graphObj.__data, ev);
  35670. } else {
  35671. state.onBackgroundClick && state.onBackgroundClick(ev);
  35672. }
  35673. }).onRightClick(function (obj, ev) {
  35674. // Handle right-click events
  35675. var graphObj = getGraphObj(obj);
  35676. if (graphObj) {
  35677. var fn = state["on".concat(graphObj.__graphObjType === 'node' ? 'Node' : 'Link', "RightClick")];
  35678. fn && fn(graphObj.__data, ev);
  35679. } else {
  35680. state.onBackgroundRightClick && state.onBackgroundRightClick(ev);
  35681. }
  35682. }); //
  35683. // Kick-off renderer
  35684. this._animationCycle();
  35685. }
  35686. }); //
  35687. function getGraphObj(object) {
  35688. var obj = object; // recurse up object chain until finding the graph object
  35689. while (obj && !obj.hasOwnProperty('__graphObjType')) {
  35690. obj = obj.parent;
  35691. }
  35692. return obj;
  35693. }
  35694. return _3dForceGraph;
  35695. })));
  35696. //# sourceMappingURL=3d-force-graph.js.map