2
0

three.module.js 1.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648
  1. /**
  2. * @license
  3. * Copyright 2010-2021 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '134dev';
  7. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  8. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  9. const CullFaceNone = 0;
  10. const CullFaceBack = 1;
  11. const CullFaceFront = 2;
  12. const CullFaceFrontBack = 3;
  13. const BasicShadowMap = 0;
  14. const PCFShadowMap = 1;
  15. const PCFSoftShadowMap = 2;
  16. const VSMShadowMap = 3;
  17. const FrontSide = 0;
  18. const BackSide = 1;
  19. const DoubleSide = 2;
  20. const FlatShading = 1;
  21. const SmoothShading = 2;
  22. const NoBlending = 0;
  23. const NormalBlending = 1;
  24. const AdditiveBlending = 2;
  25. const SubtractiveBlending = 3;
  26. const MultiplyBlending = 4;
  27. const CustomBlending = 5;
  28. const AddEquation = 100;
  29. const SubtractEquation = 101;
  30. const ReverseSubtractEquation = 102;
  31. const MinEquation = 103;
  32. const MaxEquation = 104;
  33. const ZeroFactor = 200;
  34. const OneFactor = 201;
  35. const SrcColorFactor = 202;
  36. const OneMinusSrcColorFactor = 203;
  37. const SrcAlphaFactor = 204;
  38. const OneMinusSrcAlphaFactor = 205;
  39. const DstAlphaFactor = 206;
  40. const OneMinusDstAlphaFactor = 207;
  41. const DstColorFactor = 208;
  42. const OneMinusDstColorFactor = 209;
  43. const SrcAlphaSaturateFactor = 210;
  44. const NeverDepth = 0;
  45. const AlwaysDepth = 1;
  46. const LessDepth = 2;
  47. const LessEqualDepth = 3;
  48. const EqualDepth = 4;
  49. const GreaterEqualDepth = 5;
  50. const GreaterDepth = 6;
  51. const NotEqualDepth = 7;
  52. const MultiplyOperation = 0;
  53. const MixOperation = 1;
  54. const AddOperation = 2;
  55. const NoToneMapping = 0;
  56. const LinearToneMapping = 1;
  57. const ReinhardToneMapping = 2;
  58. const CineonToneMapping = 3;
  59. const ACESFilmicToneMapping = 4;
  60. const CustomToneMapping = 5;
  61. const UVMapping = 300;
  62. const CubeReflectionMapping = 301;
  63. const CubeRefractionMapping = 302;
  64. const EquirectangularReflectionMapping = 303;
  65. const EquirectangularRefractionMapping = 304;
  66. const CubeUVReflectionMapping = 306;
  67. const CubeUVRefractionMapping = 307;
  68. const RepeatWrapping = 1000;
  69. const ClampToEdgeWrapping = 1001;
  70. const MirroredRepeatWrapping = 1002;
  71. const NearestFilter = 1003;
  72. const NearestMipmapNearestFilter = 1004;
  73. const NearestMipMapNearestFilter = 1004;
  74. const NearestMipmapLinearFilter = 1005;
  75. const NearestMipMapLinearFilter = 1005;
  76. const LinearFilter = 1006;
  77. const LinearMipmapNearestFilter = 1007;
  78. const LinearMipMapNearestFilter = 1007;
  79. const LinearMipmapLinearFilter = 1008;
  80. const LinearMipMapLinearFilter = 1008;
  81. const UnsignedByteType = 1009;
  82. const ByteType = 1010;
  83. const ShortType = 1011;
  84. const UnsignedShortType = 1012;
  85. const IntType = 1013;
  86. const UnsignedIntType = 1014;
  87. const FloatType = 1015;
  88. const HalfFloatType = 1016;
  89. const UnsignedShort4444Type = 1017;
  90. const UnsignedShort5551Type = 1018;
  91. const UnsignedShort565Type = 1019;
  92. const UnsignedInt248Type = 1020;
  93. const AlphaFormat = 1021;
  94. const RGBFormat = 1022;
  95. const RGBAFormat = 1023;
  96. const LuminanceFormat = 1024;
  97. const LuminanceAlphaFormat = 1025;
  98. const RGBEFormat = RGBAFormat;
  99. const DepthFormat = 1026;
  100. const DepthStencilFormat = 1027;
  101. const RedFormat = 1028;
  102. const RedIntegerFormat = 1029;
  103. const RGFormat = 1030;
  104. const RGIntegerFormat = 1031;
  105. const RGBIntegerFormat = 1032;
  106. const RGBAIntegerFormat = 1033;
  107. const RGB_S3TC_DXT1_Format = 33776;
  108. const RGBA_S3TC_DXT1_Format = 33777;
  109. const RGBA_S3TC_DXT3_Format = 33778;
  110. const RGBA_S3TC_DXT5_Format = 33779;
  111. const RGB_PVRTC_4BPPV1_Format = 35840;
  112. const RGB_PVRTC_2BPPV1_Format = 35841;
  113. const RGBA_PVRTC_4BPPV1_Format = 35842;
  114. const RGBA_PVRTC_2BPPV1_Format = 35843;
  115. const RGB_ETC1_Format = 36196;
  116. const RGB_ETC2_Format = 37492;
  117. const RGBA_ETC2_EAC_Format = 37496;
  118. const RGBA_ASTC_4x4_Format = 37808;
  119. const RGBA_ASTC_5x4_Format = 37809;
  120. const RGBA_ASTC_5x5_Format = 37810;
  121. const RGBA_ASTC_6x5_Format = 37811;
  122. const RGBA_ASTC_6x6_Format = 37812;
  123. const RGBA_ASTC_8x5_Format = 37813;
  124. const RGBA_ASTC_8x6_Format = 37814;
  125. const RGBA_ASTC_8x8_Format = 37815;
  126. const RGBA_ASTC_10x5_Format = 37816;
  127. const RGBA_ASTC_10x6_Format = 37817;
  128. const RGBA_ASTC_10x8_Format = 37818;
  129. const RGBA_ASTC_10x10_Format = 37819;
  130. const RGBA_ASTC_12x10_Format = 37820;
  131. const RGBA_ASTC_12x12_Format = 37821;
  132. const RGBA_BPTC_Format = 36492;
  133. const SRGB8_ALPHA8_ASTC_4x4_Format = 37840;
  134. const SRGB8_ALPHA8_ASTC_5x4_Format = 37841;
  135. const SRGB8_ALPHA8_ASTC_5x5_Format = 37842;
  136. const SRGB8_ALPHA8_ASTC_6x5_Format = 37843;
  137. const SRGB8_ALPHA8_ASTC_6x6_Format = 37844;
  138. const SRGB8_ALPHA8_ASTC_8x5_Format = 37845;
  139. const SRGB8_ALPHA8_ASTC_8x6_Format = 37846;
  140. const SRGB8_ALPHA8_ASTC_8x8_Format = 37847;
  141. const SRGB8_ALPHA8_ASTC_10x5_Format = 37848;
  142. const SRGB8_ALPHA8_ASTC_10x6_Format = 37849;
  143. const SRGB8_ALPHA8_ASTC_10x8_Format = 37850;
  144. const SRGB8_ALPHA8_ASTC_10x10_Format = 37851;
  145. const SRGB8_ALPHA8_ASTC_12x10_Format = 37852;
  146. const SRGB8_ALPHA8_ASTC_12x12_Format = 37853;
  147. const LoopOnce = 2200;
  148. const LoopRepeat = 2201;
  149. const LoopPingPong = 2202;
  150. const InterpolateDiscrete = 2300;
  151. const InterpolateLinear = 2301;
  152. const InterpolateSmooth = 2302;
  153. const ZeroCurvatureEnding = 2400;
  154. const ZeroSlopeEnding = 2401;
  155. const WrapAroundEnding = 2402;
  156. const NormalAnimationBlendMode = 2500;
  157. const AdditiveAnimationBlendMode = 2501;
  158. const TrianglesDrawMode = 0;
  159. const TriangleStripDrawMode = 1;
  160. const TriangleFanDrawMode = 2;
  161. const LinearEncoding = 3000;
  162. const sRGBEncoding = 3001;
  163. const GammaEncoding = 3007;
  164. const RGBEEncoding = 3002;
  165. const LogLuvEncoding = 3003;
  166. const RGBM7Encoding = 3004;
  167. const RGBM16Encoding = 3005;
  168. const RGBDEncoding = 3006;
  169. const BasicDepthPacking = 3200;
  170. const RGBADepthPacking = 3201;
  171. const TangentSpaceNormalMap = 0;
  172. const ObjectSpaceNormalMap = 1;
  173. const ZeroStencilOp = 0;
  174. const KeepStencilOp = 7680;
  175. const ReplaceStencilOp = 7681;
  176. const IncrementStencilOp = 7682;
  177. const DecrementStencilOp = 7683;
  178. const IncrementWrapStencilOp = 34055;
  179. const DecrementWrapStencilOp = 34056;
  180. const InvertStencilOp = 5386;
  181. const NeverStencilFunc = 512;
  182. const LessStencilFunc = 513;
  183. const EqualStencilFunc = 514;
  184. const LessEqualStencilFunc = 515;
  185. const GreaterStencilFunc = 516;
  186. const NotEqualStencilFunc = 517;
  187. const GreaterEqualStencilFunc = 518;
  188. const AlwaysStencilFunc = 519;
  189. const StaticDrawUsage = 35044;
  190. const DynamicDrawUsage = 35048;
  191. const StreamDrawUsage = 35040;
  192. const StaticReadUsage = 35045;
  193. const DynamicReadUsage = 35049;
  194. const StreamReadUsage = 35041;
  195. const StaticCopyUsage = 35046;
  196. const DynamicCopyUsage = 35050;
  197. const StreamCopyUsage = 35042;
  198. const GLSL1 = '100';
  199. const GLSL3 = '300 es';
  200. /**
  201. * https://github.com/mrdoob/eventdispatcher.js/
  202. */
  203. class EventDispatcher {
  204. addEventListener( type, listener ) {
  205. if ( this._listeners === undefined ) this._listeners = {};
  206. const listeners = this._listeners;
  207. if ( listeners[ type ] === undefined ) {
  208. listeners[ type ] = [];
  209. }
  210. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  211. listeners[ type ].push( listener );
  212. }
  213. }
  214. hasEventListener( type, listener ) {
  215. if ( this._listeners === undefined ) return false;
  216. const listeners = this._listeners;
  217. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  218. }
  219. removeEventListener( type, listener ) {
  220. if ( this._listeners === undefined ) return;
  221. const listeners = this._listeners;
  222. const listenerArray = listeners[ type ];
  223. if ( listenerArray !== undefined ) {
  224. const index = listenerArray.indexOf( listener );
  225. if ( index !== - 1 ) {
  226. listenerArray.splice( index, 1 );
  227. }
  228. }
  229. }
  230. dispatchEvent( event ) {
  231. if ( this._listeners === undefined ) return;
  232. const listeners = this._listeners;
  233. const listenerArray = listeners[ event.type ];
  234. if ( listenerArray !== undefined ) {
  235. event.target = this;
  236. // Make a copy, in case listeners are removed while iterating.
  237. const array = listenerArray.slice( 0 );
  238. for ( let i = 0, l = array.length; i < l; i ++ ) {
  239. array[ i ].call( this, event );
  240. }
  241. event.target = null;
  242. }
  243. }
  244. }
  245. let _seed = 1234567;
  246. const DEG2RAD = Math.PI / 180;
  247. const RAD2DEG = 180 / Math.PI;
  248. //
  249. const _lut = [];
  250. for ( let i = 0; i < 256; i ++ ) {
  251. _lut[ i ] = ( i < 16 ? '0' : '' ) + ( i ).toString( 16 );
  252. }
  253. const hasRandomUUID = typeof crypto !== 'undefined' && 'randomUUID' in crypto;
  254. function generateUUID() {
  255. if ( hasRandomUUID ) {
  256. return crypto.randomUUID().toUpperCase();
  257. }
  258. // TODO Remove this code when crypto.randomUUID() is available everywhere
  259. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  260. const d0 = Math.random() * 0xffffffff | 0;
  261. const d1 = Math.random() * 0xffffffff | 0;
  262. const d2 = Math.random() * 0xffffffff | 0;
  263. const d3 = Math.random() * 0xffffffff | 0;
  264. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  265. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  266. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  267. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  268. // .toUpperCase() here flattens concatenated strings to save heap memory space.
  269. return uuid.toUpperCase();
  270. }
  271. function clamp( value, min, max ) {
  272. return Math.max( min, Math.min( max, value ) );
  273. }
  274. // compute euclidian modulo of m % n
  275. // https://en.wikipedia.org/wiki/Modulo_operation
  276. function euclideanModulo( n, m ) {
  277. return ( ( n % m ) + m ) % m;
  278. }
  279. // Linear mapping from range <a1, a2> to range <b1, b2>
  280. function mapLinear( x, a1, a2, b1, b2 ) {
  281. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  282. }
  283. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  284. function inverseLerp( x, y, value ) {
  285. if ( x !== y ) {
  286. return ( value - x ) / ( y - x );
  287. } else {
  288. return 0;
  289. }
  290. }
  291. // https://en.wikipedia.org/wiki/Linear_interpolation
  292. function lerp( x, y, t ) {
  293. return ( 1 - t ) * x + t * y;
  294. }
  295. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  296. function damp( x, y, lambda, dt ) {
  297. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  298. }
  299. // https://www.desmos.com/calculator/vcsjnyz7x4
  300. function pingpong( x, length = 1 ) {
  301. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  302. }
  303. // http://en.wikipedia.org/wiki/Smoothstep
  304. function smoothstep( x, min, max ) {
  305. if ( x <= min ) return 0;
  306. if ( x >= max ) return 1;
  307. x = ( x - min ) / ( max - min );
  308. return x * x * ( 3 - 2 * x );
  309. }
  310. function smootherstep( x, min, max ) {
  311. if ( x <= min ) return 0;
  312. if ( x >= max ) return 1;
  313. x = ( x - min ) / ( max - min );
  314. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  315. }
  316. // Random integer from <low, high> interval
  317. function randInt( low, high ) {
  318. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  319. }
  320. // Random float from <low, high> interval
  321. function randFloat( low, high ) {
  322. return low + Math.random() * ( high - low );
  323. }
  324. // Random float from <-range/2, range/2> interval
  325. function randFloatSpread( range ) {
  326. return range * ( 0.5 - Math.random() );
  327. }
  328. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  329. function seededRandom( s ) {
  330. if ( s !== undefined ) _seed = s % 2147483647;
  331. // Park-Miller algorithm
  332. _seed = _seed * 16807 % 2147483647;
  333. return ( _seed - 1 ) / 2147483646;
  334. }
  335. function degToRad( degrees ) {
  336. return degrees * DEG2RAD;
  337. }
  338. function radToDeg( radians ) {
  339. return radians * RAD2DEG;
  340. }
  341. function isPowerOfTwo( value ) {
  342. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  343. }
  344. function ceilPowerOfTwo( value ) {
  345. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  346. }
  347. function floorPowerOfTwo( value ) {
  348. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  349. }
  350. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  351. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  352. // rotations are applied to the axes in the order specified by 'order'
  353. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  354. // angles are in radians
  355. const cos = Math.cos;
  356. const sin = Math.sin;
  357. const c2 = cos( b / 2 );
  358. const s2 = sin( b / 2 );
  359. const c13 = cos( ( a + c ) / 2 );
  360. const s13 = sin( ( a + c ) / 2 );
  361. const c1_3 = cos( ( a - c ) / 2 );
  362. const s1_3 = sin( ( a - c ) / 2 );
  363. const c3_1 = cos( ( c - a ) / 2 );
  364. const s3_1 = sin( ( c - a ) / 2 );
  365. switch ( order ) {
  366. case 'XYX':
  367. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  368. break;
  369. case 'YZY':
  370. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  371. break;
  372. case 'ZXZ':
  373. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  374. break;
  375. case 'XZX':
  376. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  377. break;
  378. case 'YXY':
  379. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  380. break;
  381. case 'ZYZ':
  382. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  383. break;
  384. default:
  385. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  386. }
  387. }
  388. var MathUtils = /*#__PURE__*/Object.freeze({
  389. __proto__: null,
  390. DEG2RAD: DEG2RAD,
  391. RAD2DEG: RAD2DEG,
  392. generateUUID: generateUUID,
  393. clamp: clamp,
  394. euclideanModulo: euclideanModulo,
  395. mapLinear: mapLinear,
  396. inverseLerp: inverseLerp,
  397. lerp: lerp,
  398. damp: damp,
  399. pingpong: pingpong,
  400. smoothstep: smoothstep,
  401. smootherstep: smootherstep,
  402. randInt: randInt,
  403. randFloat: randFloat,
  404. randFloatSpread: randFloatSpread,
  405. seededRandom: seededRandom,
  406. degToRad: degToRad,
  407. radToDeg: radToDeg,
  408. isPowerOfTwo: isPowerOfTwo,
  409. ceilPowerOfTwo: ceilPowerOfTwo,
  410. floorPowerOfTwo: floorPowerOfTwo,
  411. setQuaternionFromProperEuler: setQuaternionFromProperEuler
  412. });
  413. class Vector2 {
  414. constructor( x = 0, y = 0 ) {
  415. this.x = x;
  416. this.y = y;
  417. }
  418. get width() {
  419. return this.x;
  420. }
  421. set width( value ) {
  422. this.x = value;
  423. }
  424. get height() {
  425. return this.y;
  426. }
  427. set height( value ) {
  428. this.y = value;
  429. }
  430. set( x, y ) {
  431. this.x = x;
  432. this.y = y;
  433. return this;
  434. }
  435. setScalar( scalar ) {
  436. this.x = scalar;
  437. this.y = scalar;
  438. return this;
  439. }
  440. setX( x ) {
  441. this.x = x;
  442. return this;
  443. }
  444. setY( y ) {
  445. this.y = y;
  446. return this;
  447. }
  448. setComponent( index, value ) {
  449. switch ( index ) {
  450. case 0: this.x = value; break;
  451. case 1: this.y = value; break;
  452. default: throw new Error( 'index is out of range: ' + index );
  453. }
  454. return this;
  455. }
  456. getComponent( index ) {
  457. switch ( index ) {
  458. case 0: return this.x;
  459. case 1: return this.y;
  460. default: throw new Error( 'index is out of range: ' + index );
  461. }
  462. }
  463. clone() {
  464. return new this.constructor( this.x, this.y );
  465. }
  466. copy( v ) {
  467. this.x = v.x;
  468. this.y = v.y;
  469. return this;
  470. }
  471. add( v, w ) {
  472. if ( w !== undefined ) {
  473. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  474. return this.addVectors( v, w );
  475. }
  476. this.x += v.x;
  477. this.y += v.y;
  478. return this;
  479. }
  480. addScalar( s ) {
  481. this.x += s;
  482. this.y += s;
  483. return this;
  484. }
  485. addVectors( a, b ) {
  486. this.x = a.x + b.x;
  487. this.y = a.y + b.y;
  488. return this;
  489. }
  490. addScaledVector( v, s ) {
  491. this.x += v.x * s;
  492. this.y += v.y * s;
  493. return this;
  494. }
  495. sub( v, w ) {
  496. if ( w !== undefined ) {
  497. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  498. return this.subVectors( v, w );
  499. }
  500. this.x -= v.x;
  501. this.y -= v.y;
  502. return this;
  503. }
  504. subScalar( s ) {
  505. this.x -= s;
  506. this.y -= s;
  507. return this;
  508. }
  509. subVectors( a, b ) {
  510. this.x = a.x - b.x;
  511. this.y = a.y - b.y;
  512. return this;
  513. }
  514. multiply( v ) {
  515. this.x *= v.x;
  516. this.y *= v.y;
  517. return this;
  518. }
  519. multiplyScalar( scalar ) {
  520. this.x *= scalar;
  521. this.y *= scalar;
  522. return this;
  523. }
  524. divide( v ) {
  525. this.x /= v.x;
  526. this.y /= v.y;
  527. return this;
  528. }
  529. divideScalar( scalar ) {
  530. return this.multiplyScalar( 1 / scalar );
  531. }
  532. applyMatrix3( m ) {
  533. const x = this.x, y = this.y;
  534. const e = m.elements;
  535. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  536. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  537. return this;
  538. }
  539. min( v ) {
  540. this.x = Math.min( this.x, v.x );
  541. this.y = Math.min( this.y, v.y );
  542. return this;
  543. }
  544. max( v ) {
  545. this.x = Math.max( this.x, v.x );
  546. this.y = Math.max( this.y, v.y );
  547. return this;
  548. }
  549. clamp( min, max ) {
  550. // assumes min < max, componentwise
  551. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  552. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  553. return this;
  554. }
  555. clampScalar( minVal, maxVal ) {
  556. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  557. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  558. return this;
  559. }
  560. clampLength( min, max ) {
  561. const length = this.length();
  562. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  563. }
  564. floor() {
  565. this.x = Math.floor( this.x );
  566. this.y = Math.floor( this.y );
  567. return this;
  568. }
  569. ceil() {
  570. this.x = Math.ceil( this.x );
  571. this.y = Math.ceil( this.y );
  572. return this;
  573. }
  574. round() {
  575. this.x = Math.round( this.x );
  576. this.y = Math.round( this.y );
  577. return this;
  578. }
  579. roundToZero() {
  580. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  581. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  582. return this;
  583. }
  584. negate() {
  585. this.x = - this.x;
  586. this.y = - this.y;
  587. return this;
  588. }
  589. dot( v ) {
  590. return this.x * v.x + this.y * v.y;
  591. }
  592. cross( v ) {
  593. return this.x * v.y - this.y * v.x;
  594. }
  595. lengthSq() {
  596. return this.x * this.x + this.y * this.y;
  597. }
  598. length() {
  599. return Math.sqrt( this.x * this.x + this.y * this.y );
  600. }
  601. manhattanLength() {
  602. return Math.abs( this.x ) + Math.abs( this.y );
  603. }
  604. normalize() {
  605. return this.divideScalar( this.length() || 1 );
  606. }
  607. angle() {
  608. // computes the angle in radians with respect to the positive x-axis
  609. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  610. return angle;
  611. }
  612. distanceTo( v ) {
  613. return Math.sqrt( this.distanceToSquared( v ) );
  614. }
  615. distanceToSquared( v ) {
  616. const dx = this.x - v.x, dy = this.y - v.y;
  617. return dx * dx + dy * dy;
  618. }
  619. manhattanDistanceTo( v ) {
  620. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  621. }
  622. setLength( length ) {
  623. return this.normalize().multiplyScalar( length );
  624. }
  625. lerp( v, alpha ) {
  626. this.x += ( v.x - this.x ) * alpha;
  627. this.y += ( v.y - this.y ) * alpha;
  628. return this;
  629. }
  630. lerpVectors( v1, v2, alpha ) {
  631. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  632. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  633. return this;
  634. }
  635. equals( v ) {
  636. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  637. }
  638. fromArray( array, offset = 0 ) {
  639. this.x = array[ offset ];
  640. this.y = array[ offset + 1 ];
  641. return this;
  642. }
  643. toArray( array = [], offset = 0 ) {
  644. array[ offset ] = this.x;
  645. array[ offset + 1 ] = this.y;
  646. return array;
  647. }
  648. fromBufferAttribute( attribute, index, offset ) {
  649. if ( offset !== undefined ) {
  650. console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' );
  651. }
  652. this.x = attribute.getX( index );
  653. this.y = attribute.getY( index );
  654. return this;
  655. }
  656. rotateAround( center, angle ) {
  657. const c = Math.cos( angle ), s = Math.sin( angle );
  658. const x = this.x - center.x;
  659. const y = this.y - center.y;
  660. this.x = x * c - y * s + center.x;
  661. this.y = x * s + y * c + center.y;
  662. return this;
  663. }
  664. random() {
  665. this.x = Math.random();
  666. this.y = Math.random();
  667. return this;
  668. }
  669. *[ Symbol.iterator ]() {
  670. yield this.x;
  671. yield this.y;
  672. }
  673. }
  674. Vector2.prototype.isVector2 = true;
  675. class Matrix3 {
  676. constructor() {
  677. this.elements = [
  678. 1, 0, 0,
  679. 0, 1, 0,
  680. 0, 0, 1
  681. ];
  682. if ( arguments.length > 0 ) {
  683. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  684. }
  685. }
  686. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  687. const te = this.elements;
  688. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  689. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  690. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  691. return this;
  692. }
  693. identity() {
  694. this.set(
  695. 1, 0, 0,
  696. 0, 1, 0,
  697. 0, 0, 1
  698. );
  699. return this;
  700. }
  701. copy( m ) {
  702. const te = this.elements;
  703. const me = m.elements;
  704. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  705. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  706. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  707. return this;
  708. }
  709. extractBasis( xAxis, yAxis, zAxis ) {
  710. xAxis.setFromMatrix3Column( this, 0 );
  711. yAxis.setFromMatrix3Column( this, 1 );
  712. zAxis.setFromMatrix3Column( this, 2 );
  713. return this;
  714. }
  715. setFromMatrix4( m ) {
  716. const me = m.elements;
  717. this.set(
  718. me[ 0 ], me[ 4 ], me[ 8 ],
  719. me[ 1 ], me[ 5 ], me[ 9 ],
  720. me[ 2 ], me[ 6 ], me[ 10 ]
  721. );
  722. return this;
  723. }
  724. multiply( m ) {
  725. return this.multiplyMatrices( this, m );
  726. }
  727. premultiply( m ) {
  728. return this.multiplyMatrices( m, this );
  729. }
  730. multiplyMatrices( a, b ) {
  731. const ae = a.elements;
  732. const be = b.elements;
  733. const te = this.elements;
  734. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  735. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  736. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  737. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  738. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  739. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  740. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  741. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  742. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  743. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  744. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  745. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  746. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  747. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  748. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  749. return this;
  750. }
  751. multiplyScalar( s ) {
  752. const te = this.elements;
  753. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  754. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  755. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  756. return this;
  757. }
  758. determinant() {
  759. const te = this.elements;
  760. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  761. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  762. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  763. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  764. }
  765. invert() {
  766. const te = this.elements,
  767. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  768. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  769. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  770. t11 = n33 * n22 - n32 * n23,
  771. t12 = n32 * n13 - n33 * n12,
  772. t13 = n23 * n12 - n22 * n13,
  773. det = n11 * t11 + n21 * t12 + n31 * t13;
  774. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  775. const detInv = 1 / det;
  776. te[ 0 ] = t11 * detInv;
  777. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  778. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  779. te[ 3 ] = t12 * detInv;
  780. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  781. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  782. te[ 6 ] = t13 * detInv;
  783. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  784. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  785. return this;
  786. }
  787. transpose() {
  788. let tmp;
  789. const m = this.elements;
  790. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  791. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  792. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  793. return this;
  794. }
  795. getNormalMatrix( matrix4 ) {
  796. return this.setFromMatrix4( matrix4 ).invert().transpose();
  797. }
  798. transposeIntoArray( r ) {
  799. const m = this.elements;
  800. r[ 0 ] = m[ 0 ];
  801. r[ 1 ] = m[ 3 ];
  802. r[ 2 ] = m[ 6 ];
  803. r[ 3 ] = m[ 1 ];
  804. r[ 4 ] = m[ 4 ];
  805. r[ 5 ] = m[ 7 ];
  806. r[ 6 ] = m[ 2 ];
  807. r[ 7 ] = m[ 5 ];
  808. r[ 8 ] = m[ 8 ];
  809. return this;
  810. }
  811. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  812. const c = Math.cos( rotation );
  813. const s = Math.sin( rotation );
  814. this.set(
  815. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  816. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  817. 0, 0, 1
  818. );
  819. return this;
  820. }
  821. scale( sx, sy ) {
  822. const te = this.elements;
  823. te[ 0 ] *= sx; te[ 3 ] *= sx; te[ 6 ] *= sx;
  824. te[ 1 ] *= sy; te[ 4 ] *= sy; te[ 7 ] *= sy;
  825. return this;
  826. }
  827. rotate( theta ) {
  828. const c = Math.cos( theta );
  829. const s = Math.sin( theta );
  830. const te = this.elements;
  831. const a11 = te[ 0 ], a12 = te[ 3 ], a13 = te[ 6 ];
  832. const a21 = te[ 1 ], a22 = te[ 4 ], a23 = te[ 7 ];
  833. te[ 0 ] = c * a11 + s * a21;
  834. te[ 3 ] = c * a12 + s * a22;
  835. te[ 6 ] = c * a13 + s * a23;
  836. te[ 1 ] = - s * a11 + c * a21;
  837. te[ 4 ] = - s * a12 + c * a22;
  838. te[ 7 ] = - s * a13 + c * a23;
  839. return this;
  840. }
  841. translate( tx, ty ) {
  842. const te = this.elements;
  843. te[ 0 ] += tx * te[ 2 ]; te[ 3 ] += tx * te[ 5 ]; te[ 6 ] += tx * te[ 8 ];
  844. te[ 1 ] += ty * te[ 2 ]; te[ 4 ] += ty * te[ 5 ]; te[ 7 ] += ty * te[ 8 ];
  845. return this;
  846. }
  847. equals( matrix ) {
  848. const te = this.elements;
  849. const me = matrix.elements;
  850. for ( let i = 0; i < 9; i ++ ) {
  851. if ( te[ i ] !== me[ i ] ) return false;
  852. }
  853. return true;
  854. }
  855. fromArray( array, offset = 0 ) {
  856. for ( let i = 0; i < 9; i ++ ) {
  857. this.elements[ i ] = array[ i + offset ];
  858. }
  859. return this;
  860. }
  861. toArray( array = [], offset = 0 ) {
  862. const te = this.elements;
  863. array[ offset ] = te[ 0 ];
  864. array[ offset + 1 ] = te[ 1 ];
  865. array[ offset + 2 ] = te[ 2 ];
  866. array[ offset + 3 ] = te[ 3 ];
  867. array[ offset + 4 ] = te[ 4 ];
  868. array[ offset + 5 ] = te[ 5 ];
  869. array[ offset + 6 ] = te[ 6 ];
  870. array[ offset + 7 ] = te[ 7 ];
  871. array[ offset + 8 ] = te[ 8 ];
  872. return array;
  873. }
  874. clone() {
  875. return new this.constructor().fromArray( this.elements );
  876. }
  877. }
  878. Matrix3.prototype.isMatrix3 = true;
  879. function arrayMax( array ) {
  880. if ( array.length === 0 ) return - Infinity;
  881. let max = array[ 0 ];
  882. for ( let i = 1, l = array.length; i < l; ++ i ) {
  883. if ( array[ i ] > max ) max = array[ i ];
  884. }
  885. return max;
  886. }
  887. const TYPED_ARRAYS = {
  888. Int8Array: Int8Array,
  889. Uint8Array: Uint8Array,
  890. Uint8ClampedArray: Uint8ClampedArray,
  891. Int16Array: Int16Array,
  892. Uint16Array: Uint16Array,
  893. Int32Array: Int32Array,
  894. Uint32Array: Uint32Array,
  895. Float32Array: Float32Array,
  896. Float64Array: Float64Array
  897. };
  898. function getTypedArray( type, buffer ) {
  899. return new TYPED_ARRAYS[ type ]( buffer );
  900. }
  901. function createElementNS( name ) {
  902. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  903. }
  904. /**
  905. * cyrb53 hash for string from: https://stackoverflow.com/a/52171480
  906. *
  907. * Public Domain, @bryc - https://stackoverflow.com/users/815680/bryc
  908. *
  909. * It is roughly similar to the well-known MurmurHash/xxHash algorithms. It uses a combination
  910. * of multiplication and Xorshift to generate the hash, but not as thorough. As a result it's
  911. * faster than either would be in JavaScript and significantly simpler to implement. Keep in
  912. * mind this is not a secure algorithm, if privacy/security is a concern, this is not for you.
  913. *
  914. * @param {string} str
  915. * @param {number} seed, default 0
  916. * @returns number
  917. */
  918. function hashString( str, seed = 0 ) {
  919. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  920. for ( let i = 0, ch; i < str.length; i ++ ) {
  921. ch = str.charCodeAt( i );
  922. h1 = Math.imul( h1 ^ ch, 2654435761 );
  923. h2 = Math.imul( h2 ^ ch, 1597334677 );
  924. }
  925. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 ) ^ Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  926. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 ) ^ Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  927. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  928. }
  929. let _canvas;
  930. class ImageUtils {
  931. static getDataURL( image ) {
  932. if ( /^data:/i.test( image.src ) ) {
  933. return image.src;
  934. }
  935. if ( typeof HTMLCanvasElement == 'undefined' ) {
  936. return image.src;
  937. }
  938. let canvas;
  939. if ( image instanceof HTMLCanvasElement ) {
  940. canvas = image;
  941. } else {
  942. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  943. _canvas.width = image.width;
  944. _canvas.height = image.height;
  945. const context = _canvas.getContext( '2d' );
  946. if ( image instanceof ImageData ) {
  947. context.putImageData( image, 0, 0 );
  948. } else {
  949. context.drawImage( image, 0, 0, image.width, image.height );
  950. }
  951. canvas = _canvas;
  952. }
  953. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  954. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  955. return canvas.toDataURL( 'image/jpeg', 0.6 );
  956. } else {
  957. return canvas.toDataURL( 'image/png' );
  958. }
  959. }
  960. }
  961. let textureId = 0;
  962. class Texture extends EventDispatcher {
  963. 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 ) {
  964. super();
  965. Object.defineProperty( this, 'id', { value: textureId ++ } );
  966. this.uuid = generateUUID();
  967. this.name = '';
  968. this.image = image;
  969. this.mipmaps = [];
  970. this.mapping = mapping;
  971. this.wrapS = wrapS;
  972. this.wrapT = wrapT;
  973. this.magFilter = magFilter;
  974. this.minFilter = minFilter;
  975. this.anisotropy = anisotropy;
  976. this.format = format;
  977. this.internalFormat = null;
  978. this.type = type;
  979. this.offset = new Vector2( 0, 0 );
  980. this.repeat = new Vector2( 1, 1 );
  981. this.center = new Vector2( 0, 0 );
  982. this.rotation = 0;
  983. this.matrixAutoUpdate = true;
  984. this.matrix = new Matrix3();
  985. this.generateMipmaps = true;
  986. this.premultiplyAlpha = false;
  987. this.flipY = true;
  988. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  989. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  990. //
  991. // Also changing the encoding after already used by a Material will not automatically make the Material
  992. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  993. this.encoding = encoding;
  994. this.version = 0;
  995. this.onUpdate = null;
  996. this.isRenderTargetTexture = false;
  997. }
  998. updateMatrix() {
  999. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  1000. }
  1001. clone() {
  1002. return new this.constructor().copy( this );
  1003. }
  1004. copy( source ) {
  1005. this.name = source.name;
  1006. this.image = source.image;
  1007. this.mipmaps = source.mipmaps.slice( 0 );
  1008. this.mapping = source.mapping;
  1009. this.wrapS = source.wrapS;
  1010. this.wrapT = source.wrapT;
  1011. this.magFilter = source.magFilter;
  1012. this.minFilter = source.minFilter;
  1013. this.anisotropy = source.anisotropy;
  1014. this.format = source.format;
  1015. this.internalFormat = source.internalFormat;
  1016. this.type = source.type;
  1017. this.offset.copy( source.offset );
  1018. this.repeat.copy( source.repeat );
  1019. this.center.copy( source.center );
  1020. this.rotation = source.rotation;
  1021. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1022. this.matrix.copy( source.matrix );
  1023. this.generateMipmaps = source.generateMipmaps;
  1024. this.premultiplyAlpha = source.premultiplyAlpha;
  1025. this.flipY = source.flipY;
  1026. this.unpackAlignment = source.unpackAlignment;
  1027. this.encoding = source.encoding;
  1028. return this;
  1029. }
  1030. toJSON( meta ) {
  1031. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1032. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  1033. return meta.textures[ this.uuid ];
  1034. }
  1035. const output = {
  1036. metadata: {
  1037. version: 4.5,
  1038. type: 'Texture',
  1039. generator: 'Texture.toJSON'
  1040. },
  1041. uuid: this.uuid,
  1042. name: this.name,
  1043. mapping: this.mapping,
  1044. repeat: [ this.repeat.x, this.repeat.y ],
  1045. offset: [ this.offset.x, this.offset.y ],
  1046. center: [ this.center.x, this.center.y ],
  1047. rotation: this.rotation,
  1048. wrap: [ this.wrapS, this.wrapT ],
  1049. format: this.format,
  1050. type: this.type,
  1051. encoding: this.encoding,
  1052. minFilter: this.minFilter,
  1053. magFilter: this.magFilter,
  1054. anisotropy: this.anisotropy,
  1055. flipY: this.flipY,
  1056. premultiplyAlpha: this.premultiplyAlpha,
  1057. unpackAlignment: this.unpackAlignment
  1058. };
  1059. if ( this.image !== undefined ) {
  1060. // TODO: Move to THREE.Image
  1061. const image = this.image;
  1062. if ( image.uuid === undefined ) {
  1063. image.uuid = generateUUID(); // UGH
  1064. }
  1065. if ( ! isRootObject && meta.images[ image.uuid ] === undefined ) {
  1066. let url;
  1067. if ( Array.isArray( image ) ) {
  1068. // process array of images e.g. CubeTexture
  1069. url = [];
  1070. for ( let i = 0, l = image.length; i < l; i ++ ) {
  1071. // check cube texture with data textures
  1072. if ( image[ i ].isDataTexture ) {
  1073. url.push( serializeImage( image[ i ].image ) );
  1074. } else {
  1075. url.push( serializeImage( image[ i ] ) );
  1076. }
  1077. }
  1078. } else {
  1079. // process single image
  1080. url = serializeImage( image );
  1081. }
  1082. meta.images[ image.uuid ] = {
  1083. uuid: image.uuid,
  1084. url: url
  1085. };
  1086. }
  1087. output.image = image.uuid;
  1088. }
  1089. if ( ! isRootObject ) {
  1090. meta.textures[ this.uuid ] = output;
  1091. }
  1092. return output;
  1093. }
  1094. dispose() {
  1095. this.dispatchEvent( { type: 'dispose' } );
  1096. }
  1097. transformUv( uv ) {
  1098. if ( this.mapping !== UVMapping ) return uv;
  1099. uv.applyMatrix3( this.matrix );
  1100. if ( uv.x < 0 || uv.x > 1 ) {
  1101. switch ( this.wrapS ) {
  1102. case RepeatWrapping:
  1103. uv.x = uv.x - Math.floor( uv.x );
  1104. break;
  1105. case ClampToEdgeWrapping:
  1106. uv.x = uv.x < 0 ? 0 : 1;
  1107. break;
  1108. case MirroredRepeatWrapping:
  1109. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1110. uv.x = Math.ceil( uv.x ) - uv.x;
  1111. } else {
  1112. uv.x = uv.x - Math.floor( uv.x );
  1113. }
  1114. break;
  1115. }
  1116. }
  1117. if ( uv.y < 0 || uv.y > 1 ) {
  1118. switch ( this.wrapT ) {
  1119. case RepeatWrapping:
  1120. uv.y = uv.y - Math.floor( uv.y );
  1121. break;
  1122. case ClampToEdgeWrapping:
  1123. uv.y = uv.y < 0 ? 0 : 1;
  1124. break;
  1125. case MirroredRepeatWrapping:
  1126. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1127. uv.y = Math.ceil( uv.y ) - uv.y;
  1128. } else {
  1129. uv.y = uv.y - Math.floor( uv.y );
  1130. }
  1131. break;
  1132. }
  1133. }
  1134. if ( this.flipY ) {
  1135. uv.y = 1 - uv.y;
  1136. }
  1137. return uv;
  1138. }
  1139. set needsUpdate( value ) {
  1140. if ( value === true ) this.version ++;
  1141. }
  1142. }
  1143. Texture.DEFAULT_IMAGE = undefined;
  1144. Texture.DEFAULT_MAPPING = UVMapping;
  1145. Texture.prototype.isTexture = true;
  1146. function serializeImage( image ) {
  1147. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1148. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1149. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1150. // default images
  1151. return ImageUtils.getDataURL( image );
  1152. } else {
  1153. if ( image.data ) {
  1154. // images of DataTexture
  1155. return {
  1156. data: Array.prototype.slice.call( image.data ),
  1157. width: image.width,
  1158. height: image.height,
  1159. type: image.data.constructor.name
  1160. };
  1161. } else {
  1162. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1163. return {};
  1164. }
  1165. }
  1166. }
  1167. class Vector4 {
  1168. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1169. this.x = x;
  1170. this.y = y;
  1171. this.z = z;
  1172. this.w = w;
  1173. }
  1174. get width() {
  1175. return this.z;
  1176. }
  1177. set width( value ) {
  1178. this.z = value;
  1179. }
  1180. get height() {
  1181. return this.w;
  1182. }
  1183. set height( value ) {
  1184. this.w = value;
  1185. }
  1186. set( x, y, z, w ) {
  1187. this.x = x;
  1188. this.y = y;
  1189. this.z = z;
  1190. this.w = w;
  1191. return this;
  1192. }
  1193. setScalar( scalar ) {
  1194. this.x = scalar;
  1195. this.y = scalar;
  1196. this.z = scalar;
  1197. this.w = scalar;
  1198. return this;
  1199. }
  1200. setX( x ) {
  1201. this.x = x;
  1202. return this;
  1203. }
  1204. setY( y ) {
  1205. this.y = y;
  1206. return this;
  1207. }
  1208. setZ( z ) {
  1209. this.z = z;
  1210. return this;
  1211. }
  1212. setW( w ) {
  1213. this.w = w;
  1214. return this;
  1215. }
  1216. setComponent( index, value ) {
  1217. switch ( index ) {
  1218. case 0: this.x = value; break;
  1219. case 1: this.y = value; break;
  1220. case 2: this.z = value; break;
  1221. case 3: this.w = value; break;
  1222. default: throw new Error( 'index is out of range: ' + index );
  1223. }
  1224. return this;
  1225. }
  1226. getComponent( index ) {
  1227. switch ( index ) {
  1228. case 0: return this.x;
  1229. case 1: return this.y;
  1230. case 2: return this.z;
  1231. case 3: return this.w;
  1232. default: throw new Error( 'index is out of range: ' + index );
  1233. }
  1234. }
  1235. clone() {
  1236. return new this.constructor( this.x, this.y, this.z, this.w );
  1237. }
  1238. copy( v ) {
  1239. this.x = v.x;
  1240. this.y = v.y;
  1241. this.z = v.z;
  1242. this.w = ( v.w !== undefined ) ? v.w : 1;
  1243. return this;
  1244. }
  1245. add( v, w ) {
  1246. if ( w !== undefined ) {
  1247. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1248. return this.addVectors( v, w );
  1249. }
  1250. this.x += v.x;
  1251. this.y += v.y;
  1252. this.z += v.z;
  1253. this.w += v.w;
  1254. return this;
  1255. }
  1256. addScalar( s ) {
  1257. this.x += s;
  1258. this.y += s;
  1259. this.z += s;
  1260. this.w += s;
  1261. return this;
  1262. }
  1263. addVectors( a, b ) {
  1264. this.x = a.x + b.x;
  1265. this.y = a.y + b.y;
  1266. this.z = a.z + b.z;
  1267. this.w = a.w + b.w;
  1268. return this;
  1269. }
  1270. addScaledVector( v, s ) {
  1271. this.x += v.x * s;
  1272. this.y += v.y * s;
  1273. this.z += v.z * s;
  1274. this.w += v.w * s;
  1275. return this;
  1276. }
  1277. sub( v, w ) {
  1278. if ( w !== undefined ) {
  1279. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1280. return this.subVectors( v, w );
  1281. }
  1282. this.x -= v.x;
  1283. this.y -= v.y;
  1284. this.z -= v.z;
  1285. this.w -= v.w;
  1286. return this;
  1287. }
  1288. subScalar( s ) {
  1289. this.x -= s;
  1290. this.y -= s;
  1291. this.z -= s;
  1292. this.w -= s;
  1293. return this;
  1294. }
  1295. subVectors( a, b ) {
  1296. this.x = a.x - b.x;
  1297. this.y = a.y - b.y;
  1298. this.z = a.z - b.z;
  1299. this.w = a.w - b.w;
  1300. return this;
  1301. }
  1302. multiply( v ) {
  1303. this.x *= v.x;
  1304. this.y *= v.y;
  1305. this.z *= v.z;
  1306. this.w *= v.w;
  1307. return this;
  1308. }
  1309. multiplyScalar( scalar ) {
  1310. this.x *= scalar;
  1311. this.y *= scalar;
  1312. this.z *= scalar;
  1313. this.w *= scalar;
  1314. return this;
  1315. }
  1316. applyMatrix4( m ) {
  1317. const x = this.x, y = this.y, z = this.z, w = this.w;
  1318. const e = m.elements;
  1319. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1320. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1321. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1322. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1323. return this;
  1324. }
  1325. divideScalar( scalar ) {
  1326. return this.multiplyScalar( 1 / scalar );
  1327. }
  1328. setAxisAngleFromQuaternion( q ) {
  1329. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1330. // q is assumed to be normalized
  1331. this.w = 2 * Math.acos( q.w );
  1332. const s = Math.sqrt( 1 - q.w * q.w );
  1333. if ( s < 0.0001 ) {
  1334. this.x = 1;
  1335. this.y = 0;
  1336. this.z = 0;
  1337. } else {
  1338. this.x = q.x / s;
  1339. this.y = q.y / s;
  1340. this.z = q.z / s;
  1341. }
  1342. return this;
  1343. }
  1344. setAxisAngleFromRotationMatrix( m ) {
  1345. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1346. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1347. let angle, x, y, z; // variables for result
  1348. const epsilon = 0.01, // margin to allow for rounding errors
  1349. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1350. te = m.elements,
  1351. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1352. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1353. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1354. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1355. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1356. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1357. // singularity found
  1358. // first check for identity matrix which must have +1 for all terms
  1359. // in leading diagonal and zero in other terms
  1360. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1361. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1362. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1363. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1364. // this singularity is identity matrix so angle = 0
  1365. this.set( 1, 0, 0, 0 );
  1366. return this; // zero angle, arbitrary axis
  1367. }
  1368. // otherwise this singularity is angle = 180
  1369. angle = Math.PI;
  1370. const xx = ( m11 + 1 ) / 2;
  1371. const yy = ( m22 + 1 ) / 2;
  1372. const zz = ( m33 + 1 ) / 2;
  1373. const xy = ( m12 + m21 ) / 4;
  1374. const xz = ( m13 + m31 ) / 4;
  1375. const yz = ( m23 + m32 ) / 4;
  1376. if ( ( xx > yy ) && ( xx > zz ) ) {
  1377. // m11 is the largest diagonal term
  1378. if ( xx < epsilon ) {
  1379. x = 0;
  1380. y = 0.707106781;
  1381. z = 0.707106781;
  1382. } else {
  1383. x = Math.sqrt( xx );
  1384. y = xy / x;
  1385. z = xz / x;
  1386. }
  1387. } else if ( yy > zz ) {
  1388. // m22 is the largest diagonal term
  1389. if ( yy < epsilon ) {
  1390. x = 0.707106781;
  1391. y = 0;
  1392. z = 0.707106781;
  1393. } else {
  1394. y = Math.sqrt( yy );
  1395. x = xy / y;
  1396. z = yz / y;
  1397. }
  1398. } else {
  1399. // m33 is the largest diagonal term so base result on this
  1400. if ( zz < epsilon ) {
  1401. x = 0.707106781;
  1402. y = 0.707106781;
  1403. z = 0;
  1404. } else {
  1405. z = Math.sqrt( zz );
  1406. x = xz / z;
  1407. y = yz / z;
  1408. }
  1409. }
  1410. this.set( x, y, z, angle );
  1411. return this; // return 180 deg rotation
  1412. }
  1413. // as we have reached here there are no singularities so we can handle normally
  1414. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1415. ( m13 - m31 ) * ( m13 - m31 ) +
  1416. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1417. if ( Math.abs( s ) < 0.001 ) s = 1;
  1418. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1419. // caught by singularity test above, but I've left it in just in case
  1420. this.x = ( m32 - m23 ) / s;
  1421. this.y = ( m13 - m31 ) / s;
  1422. this.z = ( m21 - m12 ) / s;
  1423. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1424. return this;
  1425. }
  1426. min( v ) {
  1427. this.x = Math.min( this.x, v.x );
  1428. this.y = Math.min( this.y, v.y );
  1429. this.z = Math.min( this.z, v.z );
  1430. this.w = Math.min( this.w, v.w );
  1431. return this;
  1432. }
  1433. max( v ) {
  1434. this.x = Math.max( this.x, v.x );
  1435. this.y = Math.max( this.y, v.y );
  1436. this.z = Math.max( this.z, v.z );
  1437. this.w = Math.max( this.w, v.w );
  1438. return this;
  1439. }
  1440. clamp( min, max ) {
  1441. // assumes min < max, componentwise
  1442. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1443. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1444. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1445. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1446. return this;
  1447. }
  1448. clampScalar( minVal, maxVal ) {
  1449. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1450. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1451. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1452. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  1453. return this;
  1454. }
  1455. clampLength( min, max ) {
  1456. const length = this.length();
  1457. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1458. }
  1459. floor() {
  1460. this.x = Math.floor( this.x );
  1461. this.y = Math.floor( this.y );
  1462. this.z = Math.floor( this.z );
  1463. this.w = Math.floor( this.w );
  1464. return this;
  1465. }
  1466. ceil() {
  1467. this.x = Math.ceil( this.x );
  1468. this.y = Math.ceil( this.y );
  1469. this.z = Math.ceil( this.z );
  1470. this.w = Math.ceil( this.w );
  1471. return this;
  1472. }
  1473. round() {
  1474. this.x = Math.round( this.x );
  1475. this.y = Math.round( this.y );
  1476. this.z = Math.round( this.z );
  1477. this.w = Math.round( this.w );
  1478. return this;
  1479. }
  1480. roundToZero() {
  1481. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1482. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1483. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1484. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1485. return this;
  1486. }
  1487. negate() {
  1488. this.x = - this.x;
  1489. this.y = - this.y;
  1490. this.z = - this.z;
  1491. this.w = - this.w;
  1492. return this;
  1493. }
  1494. dot( v ) {
  1495. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1496. }
  1497. lengthSq() {
  1498. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1499. }
  1500. length() {
  1501. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1502. }
  1503. manhattanLength() {
  1504. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1505. }
  1506. normalize() {
  1507. return this.divideScalar( this.length() || 1 );
  1508. }
  1509. setLength( length ) {
  1510. return this.normalize().multiplyScalar( length );
  1511. }
  1512. lerp( v, alpha ) {
  1513. this.x += ( v.x - this.x ) * alpha;
  1514. this.y += ( v.y - this.y ) * alpha;
  1515. this.z += ( v.z - this.z ) * alpha;
  1516. this.w += ( v.w - this.w ) * alpha;
  1517. return this;
  1518. }
  1519. lerpVectors( v1, v2, alpha ) {
  1520. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1521. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1522. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1523. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  1524. return this;
  1525. }
  1526. equals( v ) {
  1527. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1528. }
  1529. fromArray( array, offset = 0 ) {
  1530. this.x = array[ offset ];
  1531. this.y = array[ offset + 1 ];
  1532. this.z = array[ offset + 2 ];
  1533. this.w = array[ offset + 3 ];
  1534. return this;
  1535. }
  1536. toArray( array = [], offset = 0 ) {
  1537. array[ offset ] = this.x;
  1538. array[ offset + 1 ] = this.y;
  1539. array[ offset + 2 ] = this.z;
  1540. array[ offset + 3 ] = this.w;
  1541. return array;
  1542. }
  1543. fromBufferAttribute( attribute, index, offset ) {
  1544. if ( offset !== undefined ) {
  1545. console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' );
  1546. }
  1547. this.x = attribute.getX( index );
  1548. this.y = attribute.getY( index );
  1549. this.z = attribute.getZ( index );
  1550. this.w = attribute.getW( index );
  1551. return this;
  1552. }
  1553. random() {
  1554. this.x = Math.random();
  1555. this.y = Math.random();
  1556. this.z = Math.random();
  1557. this.w = Math.random();
  1558. return this;
  1559. }
  1560. *[ Symbol.iterator ]() {
  1561. yield this.x;
  1562. yield this.y;
  1563. yield this.z;
  1564. yield this.w;
  1565. }
  1566. }
  1567. Vector4.prototype.isVector4 = true;
  1568. /*
  1569. In options, we can specify:
  1570. * Texture parameters for an auto-generated target texture
  1571. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1572. */
  1573. class WebGLRenderTarget extends EventDispatcher {
  1574. constructor( width, height, options = {} ) {
  1575. super();
  1576. this.width = width;
  1577. this.height = height;
  1578. this.depth = 1;
  1579. this.scissor = new Vector4( 0, 0, width, height );
  1580. this.scissorTest = false;
  1581. this.viewport = new Vector4( 0, 0, width, height );
  1582. this.texture = new Texture( undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  1583. this.texture.isRenderTargetTexture = true;
  1584. this.texture.image = { width: width, height: height, depth: 1 };
  1585. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  1586. this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null;
  1587. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  1588. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  1589. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  1590. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  1591. }
  1592. setTexture( texture ) {
  1593. texture.image = {
  1594. width: this.width,
  1595. height: this.height,
  1596. depth: this.depth
  1597. };
  1598. this.texture = texture;
  1599. }
  1600. setSize( width, height, depth = 1 ) {
  1601. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1602. this.width = width;
  1603. this.height = height;
  1604. this.depth = depth;
  1605. this.texture.image.width = width;
  1606. this.texture.image.height = height;
  1607. this.texture.image.depth = depth;
  1608. this.dispose();
  1609. }
  1610. this.viewport.set( 0, 0, width, height );
  1611. this.scissor.set( 0, 0, width, height );
  1612. }
  1613. clone() {
  1614. return new this.constructor().copy( this );
  1615. }
  1616. copy( source ) {
  1617. this.width = source.width;
  1618. this.height = source.height;
  1619. this.depth = source.depth;
  1620. this.viewport.copy( source.viewport );
  1621. this.texture = source.texture.clone();
  1622. this.texture.image = { ...this.texture.image }; // See #20328.
  1623. this.depthBuffer = source.depthBuffer;
  1624. this.stencilBuffer = source.stencilBuffer;
  1625. this.depthTexture = source.depthTexture;
  1626. return this;
  1627. }
  1628. dispose() {
  1629. this.dispatchEvent( { type: 'dispose' } );
  1630. }
  1631. }
  1632. WebGLRenderTarget.prototype.isWebGLRenderTarget = true;
  1633. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  1634. constructor( width, height, count ) {
  1635. super( width, height );
  1636. const texture = this.texture;
  1637. this.texture = [];
  1638. for ( let i = 0; i < count; i ++ ) {
  1639. this.texture[ i ] = texture.clone();
  1640. }
  1641. }
  1642. setSize( width, height, depth = 1 ) {
  1643. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1644. this.width = width;
  1645. this.height = height;
  1646. this.depth = depth;
  1647. for ( let i = 0, il = this.texture.length; i < il; i ++ ) {
  1648. this.texture[ i ].image.width = width;
  1649. this.texture[ i ].image.height = height;
  1650. this.texture[ i ].image.depth = depth;
  1651. }
  1652. this.dispose();
  1653. }
  1654. this.viewport.set( 0, 0, width, height );
  1655. this.scissor.set( 0, 0, width, height );
  1656. return this;
  1657. }
  1658. copy( source ) {
  1659. this.dispose();
  1660. this.width = source.width;
  1661. this.height = source.height;
  1662. this.depth = source.depth;
  1663. this.viewport.set( 0, 0, this.width, this.height );
  1664. this.scissor.set( 0, 0, this.width, this.height );
  1665. this.depthBuffer = source.depthBuffer;
  1666. this.stencilBuffer = source.stencilBuffer;
  1667. this.depthTexture = source.depthTexture;
  1668. this.texture.length = 0;
  1669. for ( let i = 0, il = source.texture.length; i < il; i ++ ) {
  1670. this.texture[ i ] = source.texture[ i ].clone();
  1671. }
  1672. return this;
  1673. }
  1674. }
  1675. WebGLMultipleRenderTargets.prototype.isWebGLMultipleRenderTargets = true;
  1676. class WebGLMultisampleRenderTarget extends WebGLRenderTarget {
  1677. constructor( width, height, options ) {
  1678. super( width, height, options );
  1679. this.samples = 4;
  1680. }
  1681. copy( source ) {
  1682. super.copy.call( this, source );
  1683. this.samples = source.samples;
  1684. return this;
  1685. }
  1686. }
  1687. WebGLMultisampleRenderTarget.prototype.isWebGLMultisampleRenderTarget = true;
  1688. class Quaternion {
  1689. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1690. this._x = x;
  1691. this._y = y;
  1692. this._z = z;
  1693. this._w = w;
  1694. }
  1695. static slerp( qa, qb, qm, t ) {
  1696. console.warn( 'THREE.Quaternion: Static .slerp() has been deprecated. Use qm.slerpQuaternions( qa, qb, t ) instead.' );
  1697. return qm.slerpQuaternions( qa, qb, t );
  1698. }
  1699. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1700. // fuzz-free, array-based Quaternion SLERP operation
  1701. let x0 = src0[ srcOffset0 + 0 ],
  1702. y0 = src0[ srcOffset0 + 1 ],
  1703. z0 = src0[ srcOffset0 + 2 ],
  1704. w0 = src0[ srcOffset0 + 3 ];
  1705. const x1 = src1[ srcOffset1 + 0 ],
  1706. y1 = src1[ srcOffset1 + 1 ],
  1707. z1 = src1[ srcOffset1 + 2 ],
  1708. w1 = src1[ srcOffset1 + 3 ];
  1709. if ( t === 0 ) {
  1710. dst[ dstOffset + 0 ] = x0;
  1711. dst[ dstOffset + 1 ] = y0;
  1712. dst[ dstOffset + 2 ] = z0;
  1713. dst[ dstOffset + 3 ] = w0;
  1714. return;
  1715. }
  1716. if ( t === 1 ) {
  1717. dst[ dstOffset + 0 ] = x1;
  1718. dst[ dstOffset + 1 ] = y1;
  1719. dst[ dstOffset + 2 ] = z1;
  1720. dst[ dstOffset + 3 ] = w1;
  1721. return;
  1722. }
  1723. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1724. let s = 1 - t;
  1725. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1726. dir = ( cos >= 0 ? 1 : - 1 ),
  1727. sqrSin = 1 - cos * cos;
  1728. // Skip the Slerp for tiny steps to avoid numeric problems:
  1729. if ( sqrSin > Number.EPSILON ) {
  1730. const sin = Math.sqrt( sqrSin ),
  1731. len = Math.atan2( sin, cos * dir );
  1732. s = Math.sin( s * len ) / sin;
  1733. t = Math.sin( t * len ) / sin;
  1734. }
  1735. const tDir = t * dir;
  1736. x0 = x0 * s + x1 * tDir;
  1737. y0 = y0 * s + y1 * tDir;
  1738. z0 = z0 * s + z1 * tDir;
  1739. w0 = w0 * s + w1 * tDir;
  1740. // Normalize in case we just did a lerp:
  1741. if ( s === 1 - t ) {
  1742. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  1743. x0 *= f;
  1744. y0 *= f;
  1745. z0 *= f;
  1746. w0 *= f;
  1747. }
  1748. }
  1749. dst[ dstOffset ] = x0;
  1750. dst[ dstOffset + 1 ] = y0;
  1751. dst[ dstOffset + 2 ] = z0;
  1752. dst[ dstOffset + 3 ] = w0;
  1753. }
  1754. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  1755. const x0 = src0[ srcOffset0 ];
  1756. const y0 = src0[ srcOffset0 + 1 ];
  1757. const z0 = src0[ srcOffset0 + 2 ];
  1758. const w0 = src0[ srcOffset0 + 3 ];
  1759. const x1 = src1[ srcOffset1 ];
  1760. const y1 = src1[ srcOffset1 + 1 ];
  1761. const z1 = src1[ srcOffset1 + 2 ];
  1762. const w1 = src1[ srcOffset1 + 3 ];
  1763. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  1764. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  1765. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  1766. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  1767. return dst;
  1768. }
  1769. get x() {
  1770. return this._x;
  1771. }
  1772. set x( value ) {
  1773. this._x = value;
  1774. this._onChangeCallback();
  1775. }
  1776. get y() {
  1777. return this._y;
  1778. }
  1779. set y( value ) {
  1780. this._y = value;
  1781. this._onChangeCallback();
  1782. }
  1783. get z() {
  1784. return this._z;
  1785. }
  1786. set z( value ) {
  1787. this._z = value;
  1788. this._onChangeCallback();
  1789. }
  1790. get w() {
  1791. return this._w;
  1792. }
  1793. set w( value ) {
  1794. this._w = value;
  1795. this._onChangeCallback();
  1796. }
  1797. set( x, y, z, w ) {
  1798. this._x = x;
  1799. this._y = y;
  1800. this._z = z;
  1801. this._w = w;
  1802. this._onChangeCallback();
  1803. return this;
  1804. }
  1805. clone() {
  1806. return new this.constructor( this._x, this._y, this._z, this._w );
  1807. }
  1808. copy( quaternion ) {
  1809. this._x = quaternion.x;
  1810. this._y = quaternion.y;
  1811. this._z = quaternion.z;
  1812. this._w = quaternion.w;
  1813. this._onChangeCallback();
  1814. return this;
  1815. }
  1816. setFromEuler( euler, update ) {
  1817. if ( ! ( euler && euler.isEuler ) ) {
  1818. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  1819. }
  1820. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  1821. // http://www.mathworks.com/matlabcentral/fileexchange/
  1822. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1823. // content/SpinCalc.m
  1824. const cos = Math.cos;
  1825. const sin = Math.sin;
  1826. const c1 = cos( x / 2 );
  1827. const c2 = cos( y / 2 );
  1828. const c3 = cos( z / 2 );
  1829. const s1 = sin( x / 2 );
  1830. const s2 = sin( y / 2 );
  1831. const s3 = sin( z / 2 );
  1832. switch ( order ) {
  1833. case 'XYZ':
  1834. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1835. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1836. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1837. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1838. break;
  1839. case 'YXZ':
  1840. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1841. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1842. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1843. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1844. break;
  1845. case 'ZXY':
  1846. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1847. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1848. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1849. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1850. break;
  1851. case 'ZYX':
  1852. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1853. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1854. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1855. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1856. break;
  1857. case 'YZX':
  1858. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1859. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1860. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1861. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1862. break;
  1863. case 'XZY':
  1864. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1865. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1866. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1867. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1868. break;
  1869. default:
  1870. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  1871. }
  1872. if ( update !== false ) this._onChangeCallback();
  1873. return this;
  1874. }
  1875. setFromAxisAngle( axis, angle ) {
  1876. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  1877. // assumes axis is normalized
  1878. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  1879. this._x = axis.x * s;
  1880. this._y = axis.y * s;
  1881. this._z = axis.z * s;
  1882. this._w = Math.cos( halfAngle );
  1883. this._onChangeCallback();
  1884. return this;
  1885. }
  1886. setFromRotationMatrix( m ) {
  1887. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  1888. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1889. const te = m.elements,
  1890. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1891. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1892. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  1893. trace = m11 + m22 + m33;
  1894. if ( trace > 0 ) {
  1895. const s = 0.5 / Math.sqrt( trace + 1.0 );
  1896. this._w = 0.25 / s;
  1897. this._x = ( m32 - m23 ) * s;
  1898. this._y = ( m13 - m31 ) * s;
  1899. this._z = ( m21 - m12 ) * s;
  1900. } else if ( m11 > m22 && m11 > m33 ) {
  1901. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  1902. this._w = ( m32 - m23 ) / s;
  1903. this._x = 0.25 * s;
  1904. this._y = ( m12 + m21 ) / s;
  1905. this._z = ( m13 + m31 ) / s;
  1906. } else if ( m22 > m33 ) {
  1907. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  1908. this._w = ( m13 - m31 ) / s;
  1909. this._x = ( m12 + m21 ) / s;
  1910. this._y = 0.25 * s;
  1911. this._z = ( m23 + m32 ) / s;
  1912. } else {
  1913. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  1914. this._w = ( m21 - m12 ) / s;
  1915. this._x = ( m13 + m31 ) / s;
  1916. this._y = ( m23 + m32 ) / s;
  1917. this._z = 0.25 * s;
  1918. }
  1919. this._onChangeCallback();
  1920. return this;
  1921. }
  1922. setFromUnitVectors( vFrom, vTo ) {
  1923. // assumes direction vectors vFrom and vTo are normalized
  1924. let r = vFrom.dot( vTo ) + 1;
  1925. if ( r < Number.EPSILON ) {
  1926. // vFrom and vTo point in opposite directions
  1927. r = 0;
  1928. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  1929. this._x = - vFrom.y;
  1930. this._y = vFrom.x;
  1931. this._z = 0;
  1932. this._w = r;
  1933. } else {
  1934. this._x = 0;
  1935. this._y = - vFrom.z;
  1936. this._z = vFrom.y;
  1937. this._w = r;
  1938. }
  1939. } else {
  1940. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  1941. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  1942. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  1943. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  1944. this._w = r;
  1945. }
  1946. return this.normalize();
  1947. }
  1948. angleTo( q ) {
  1949. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) );
  1950. }
  1951. rotateTowards( q, step ) {
  1952. const angle = this.angleTo( q );
  1953. if ( angle === 0 ) return this;
  1954. const t = Math.min( 1, step / angle );
  1955. this.slerp( q, t );
  1956. return this;
  1957. }
  1958. identity() {
  1959. return this.set( 0, 0, 0, 1 );
  1960. }
  1961. invert() {
  1962. // quaternion is assumed to have unit length
  1963. return this.conjugate();
  1964. }
  1965. conjugate() {
  1966. this._x *= - 1;
  1967. this._y *= - 1;
  1968. this._z *= - 1;
  1969. this._onChangeCallback();
  1970. return this;
  1971. }
  1972. dot( v ) {
  1973. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  1974. }
  1975. lengthSq() {
  1976. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  1977. }
  1978. length() {
  1979. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  1980. }
  1981. normalize() {
  1982. let l = this.length();
  1983. if ( l === 0 ) {
  1984. this._x = 0;
  1985. this._y = 0;
  1986. this._z = 0;
  1987. this._w = 1;
  1988. } else {
  1989. l = 1 / l;
  1990. this._x = this._x * l;
  1991. this._y = this._y * l;
  1992. this._z = this._z * l;
  1993. this._w = this._w * l;
  1994. }
  1995. this._onChangeCallback();
  1996. return this;
  1997. }
  1998. multiply( q, p ) {
  1999. if ( p !== undefined ) {
  2000. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  2001. return this.multiplyQuaternions( q, p );
  2002. }
  2003. return this.multiplyQuaternions( this, q );
  2004. }
  2005. premultiply( q ) {
  2006. return this.multiplyQuaternions( q, this );
  2007. }
  2008. multiplyQuaternions( a, b ) {
  2009. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2010. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  2011. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  2012. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2013. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2014. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2015. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2016. this._onChangeCallback();
  2017. return this;
  2018. }
  2019. slerp( qb, t ) {
  2020. if ( t === 0 ) return this;
  2021. if ( t === 1 ) return this.copy( qb );
  2022. const x = this._x, y = this._y, z = this._z, w = this._w;
  2023. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2024. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2025. if ( cosHalfTheta < 0 ) {
  2026. this._w = - qb._w;
  2027. this._x = - qb._x;
  2028. this._y = - qb._y;
  2029. this._z = - qb._z;
  2030. cosHalfTheta = - cosHalfTheta;
  2031. } else {
  2032. this.copy( qb );
  2033. }
  2034. if ( cosHalfTheta >= 1.0 ) {
  2035. this._w = w;
  2036. this._x = x;
  2037. this._y = y;
  2038. this._z = z;
  2039. return this;
  2040. }
  2041. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2042. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  2043. const s = 1 - t;
  2044. this._w = s * w + t * this._w;
  2045. this._x = s * x + t * this._x;
  2046. this._y = s * y + t * this._y;
  2047. this._z = s * z + t * this._z;
  2048. this.normalize();
  2049. this._onChangeCallback();
  2050. return this;
  2051. }
  2052. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  2053. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  2054. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2055. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2056. this._w = ( w * ratioA + this._w * ratioB );
  2057. this._x = ( x * ratioA + this._x * ratioB );
  2058. this._y = ( y * ratioA + this._y * ratioB );
  2059. this._z = ( z * ratioA + this._z * ratioB );
  2060. this._onChangeCallback();
  2061. return this;
  2062. }
  2063. slerpQuaternions( qa, qb, t ) {
  2064. this.copy( qa ).slerp( qb, t );
  2065. }
  2066. random() {
  2067. // Derived from http://planning.cs.uiuc.edu/node198.html
  2068. // Note, this source uses w, x, y, z ordering,
  2069. // so we swap the order below.
  2070. const u1 = Math.random();
  2071. const sqrt1u1 = Math.sqrt( 1 - u1 );
  2072. const sqrtu1 = Math.sqrt( u1 );
  2073. const u2 = 2 * Math.PI * Math.random();
  2074. const u3 = 2 * Math.PI * Math.random();
  2075. return this.set(
  2076. sqrt1u1 * Math.cos( u2 ),
  2077. sqrtu1 * Math.sin( u3 ),
  2078. sqrtu1 * Math.cos( u3 ),
  2079. sqrt1u1 * Math.sin( u2 ),
  2080. );
  2081. }
  2082. equals( quaternion ) {
  2083. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2084. }
  2085. fromArray( array, offset = 0 ) {
  2086. this._x = array[ offset ];
  2087. this._y = array[ offset + 1 ];
  2088. this._z = array[ offset + 2 ];
  2089. this._w = array[ offset + 3 ];
  2090. this._onChangeCallback();
  2091. return this;
  2092. }
  2093. toArray( array = [], offset = 0 ) {
  2094. array[ offset ] = this._x;
  2095. array[ offset + 1 ] = this._y;
  2096. array[ offset + 2 ] = this._z;
  2097. array[ offset + 3 ] = this._w;
  2098. return array;
  2099. }
  2100. fromBufferAttribute( attribute, index ) {
  2101. this._x = attribute.getX( index );
  2102. this._y = attribute.getY( index );
  2103. this._z = attribute.getZ( index );
  2104. this._w = attribute.getW( index );
  2105. return this;
  2106. }
  2107. _onChange( callback ) {
  2108. this._onChangeCallback = callback;
  2109. return this;
  2110. }
  2111. _onChangeCallback() {}
  2112. }
  2113. Quaternion.prototype.isQuaternion = true;
  2114. class Vector3 {
  2115. constructor( x = 0, y = 0, z = 0 ) {
  2116. this.x = x;
  2117. this.y = y;
  2118. this.z = z;
  2119. }
  2120. set( x, y, z ) {
  2121. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2122. this.x = x;
  2123. this.y = y;
  2124. this.z = z;
  2125. return this;
  2126. }
  2127. setScalar( scalar ) {
  2128. this.x = scalar;
  2129. this.y = scalar;
  2130. this.z = scalar;
  2131. return this;
  2132. }
  2133. setX( x ) {
  2134. this.x = x;
  2135. return this;
  2136. }
  2137. setY( y ) {
  2138. this.y = y;
  2139. return this;
  2140. }
  2141. setZ( z ) {
  2142. this.z = z;
  2143. return this;
  2144. }
  2145. setComponent( index, value ) {
  2146. switch ( index ) {
  2147. case 0: this.x = value; break;
  2148. case 1: this.y = value; break;
  2149. case 2: this.z = value; break;
  2150. default: throw new Error( 'index is out of range: ' + index );
  2151. }
  2152. return this;
  2153. }
  2154. getComponent( index ) {
  2155. switch ( index ) {
  2156. case 0: return this.x;
  2157. case 1: return this.y;
  2158. case 2: return this.z;
  2159. default: throw new Error( 'index is out of range: ' + index );
  2160. }
  2161. }
  2162. clone() {
  2163. return new this.constructor( this.x, this.y, this.z );
  2164. }
  2165. copy( v ) {
  2166. this.x = v.x;
  2167. this.y = v.y;
  2168. this.z = v.z;
  2169. return this;
  2170. }
  2171. add( v, w ) {
  2172. if ( w !== undefined ) {
  2173. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  2174. return this.addVectors( v, w );
  2175. }
  2176. this.x += v.x;
  2177. this.y += v.y;
  2178. this.z += v.z;
  2179. return this;
  2180. }
  2181. addScalar( s ) {
  2182. this.x += s;
  2183. this.y += s;
  2184. this.z += s;
  2185. return this;
  2186. }
  2187. addVectors( a, b ) {
  2188. this.x = a.x + b.x;
  2189. this.y = a.y + b.y;
  2190. this.z = a.z + b.z;
  2191. return this;
  2192. }
  2193. addScaledVector( v, s ) {
  2194. this.x += v.x * s;
  2195. this.y += v.y * s;
  2196. this.z += v.z * s;
  2197. return this;
  2198. }
  2199. sub( v, w ) {
  2200. if ( w !== undefined ) {
  2201. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  2202. return this.subVectors( v, w );
  2203. }
  2204. this.x -= v.x;
  2205. this.y -= v.y;
  2206. this.z -= v.z;
  2207. return this;
  2208. }
  2209. subScalar( s ) {
  2210. this.x -= s;
  2211. this.y -= s;
  2212. this.z -= s;
  2213. return this;
  2214. }
  2215. subVectors( a, b ) {
  2216. this.x = a.x - b.x;
  2217. this.y = a.y - b.y;
  2218. this.z = a.z - b.z;
  2219. return this;
  2220. }
  2221. multiply( v, w ) {
  2222. if ( w !== undefined ) {
  2223. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  2224. return this.multiplyVectors( v, w );
  2225. }
  2226. this.x *= v.x;
  2227. this.y *= v.y;
  2228. this.z *= v.z;
  2229. return this;
  2230. }
  2231. multiplyScalar( scalar ) {
  2232. this.x *= scalar;
  2233. this.y *= scalar;
  2234. this.z *= scalar;
  2235. return this;
  2236. }
  2237. multiplyVectors( a, b ) {
  2238. this.x = a.x * b.x;
  2239. this.y = a.y * b.y;
  2240. this.z = a.z * b.z;
  2241. return this;
  2242. }
  2243. applyEuler( euler ) {
  2244. if ( ! ( euler && euler.isEuler ) ) {
  2245. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  2246. }
  2247. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  2248. }
  2249. applyAxisAngle( axis, angle ) {
  2250. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  2251. }
  2252. applyMatrix3( m ) {
  2253. const x = this.x, y = this.y, z = this.z;
  2254. const e = m.elements;
  2255. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2256. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2257. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2258. return this;
  2259. }
  2260. applyNormalMatrix( m ) {
  2261. return this.applyMatrix3( m ).normalize();
  2262. }
  2263. applyMatrix4( m ) {
  2264. const x = this.x, y = this.y, z = this.z;
  2265. const e = m.elements;
  2266. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2267. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2268. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2269. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2270. return this;
  2271. }
  2272. applyQuaternion( q ) {
  2273. const x = this.x, y = this.y, z = this.z;
  2274. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2275. // calculate quat * vector
  2276. const ix = qw * x + qy * z - qz * y;
  2277. const iy = qw * y + qz * x - qx * z;
  2278. const iz = qw * z + qx * y - qy * x;
  2279. const iw = - qx * x - qy * y - qz * z;
  2280. // calculate result * inverse quat
  2281. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  2282. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  2283. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  2284. return this;
  2285. }
  2286. project( camera ) {
  2287. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2288. }
  2289. unproject( camera ) {
  2290. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2291. }
  2292. transformDirection( m ) {
  2293. // input: THREE.Matrix4 affine matrix
  2294. // vector interpreted as a direction
  2295. const x = this.x, y = this.y, z = this.z;
  2296. const e = m.elements;
  2297. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2298. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2299. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2300. return this.normalize();
  2301. }
  2302. divide( v ) {
  2303. this.x /= v.x;
  2304. this.y /= v.y;
  2305. this.z /= v.z;
  2306. return this;
  2307. }
  2308. divideScalar( scalar ) {
  2309. return this.multiplyScalar( 1 / scalar );
  2310. }
  2311. min( v ) {
  2312. this.x = Math.min( this.x, v.x );
  2313. this.y = Math.min( this.y, v.y );
  2314. this.z = Math.min( this.z, v.z );
  2315. return this;
  2316. }
  2317. max( v ) {
  2318. this.x = Math.max( this.x, v.x );
  2319. this.y = Math.max( this.y, v.y );
  2320. this.z = Math.max( this.z, v.z );
  2321. return this;
  2322. }
  2323. clamp( min, max ) {
  2324. // assumes min < max, componentwise
  2325. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2326. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2327. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2328. return this;
  2329. }
  2330. clampScalar( minVal, maxVal ) {
  2331. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2332. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2333. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2334. return this;
  2335. }
  2336. clampLength( min, max ) {
  2337. const length = this.length();
  2338. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2339. }
  2340. floor() {
  2341. this.x = Math.floor( this.x );
  2342. this.y = Math.floor( this.y );
  2343. this.z = Math.floor( this.z );
  2344. return this;
  2345. }
  2346. ceil() {
  2347. this.x = Math.ceil( this.x );
  2348. this.y = Math.ceil( this.y );
  2349. this.z = Math.ceil( this.z );
  2350. return this;
  2351. }
  2352. round() {
  2353. this.x = Math.round( this.x );
  2354. this.y = Math.round( this.y );
  2355. this.z = Math.round( this.z );
  2356. return this;
  2357. }
  2358. roundToZero() {
  2359. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  2360. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  2361. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  2362. return this;
  2363. }
  2364. negate() {
  2365. this.x = - this.x;
  2366. this.y = - this.y;
  2367. this.z = - this.z;
  2368. return this;
  2369. }
  2370. dot( v ) {
  2371. return this.x * v.x + this.y * v.y + this.z * v.z;
  2372. }
  2373. // TODO lengthSquared?
  2374. lengthSq() {
  2375. return this.x * this.x + this.y * this.y + this.z * this.z;
  2376. }
  2377. length() {
  2378. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2379. }
  2380. manhattanLength() {
  2381. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2382. }
  2383. normalize() {
  2384. return this.divideScalar( this.length() || 1 );
  2385. }
  2386. setLength( length ) {
  2387. return this.normalize().multiplyScalar( length );
  2388. }
  2389. lerp( v, alpha ) {
  2390. this.x += ( v.x - this.x ) * alpha;
  2391. this.y += ( v.y - this.y ) * alpha;
  2392. this.z += ( v.z - this.z ) * alpha;
  2393. return this;
  2394. }
  2395. lerpVectors( v1, v2, alpha ) {
  2396. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2397. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2398. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2399. return this;
  2400. }
  2401. cross( v, w ) {
  2402. if ( w !== undefined ) {
  2403. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  2404. return this.crossVectors( v, w );
  2405. }
  2406. return this.crossVectors( this, v );
  2407. }
  2408. crossVectors( a, b ) {
  2409. const ax = a.x, ay = a.y, az = a.z;
  2410. const bx = b.x, by = b.y, bz = b.z;
  2411. this.x = ay * bz - az * by;
  2412. this.y = az * bx - ax * bz;
  2413. this.z = ax * by - ay * bx;
  2414. return this;
  2415. }
  2416. projectOnVector( v ) {
  2417. const denominator = v.lengthSq();
  2418. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2419. const scalar = v.dot( this ) / denominator;
  2420. return this.copy( v ).multiplyScalar( scalar );
  2421. }
  2422. projectOnPlane( planeNormal ) {
  2423. _vector$c.copy( this ).projectOnVector( planeNormal );
  2424. return this.sub( _vector$c );
  2425. }
  2426. reflect( normal ) {
  2427. // reflect incident vector off plane orthogonal to normal
  2428. // normal is assumed to have unit length
  2429. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2430. }
  2431. angleTo( v ) {
  2432. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2433. if ( denominator === 0 ) return Math.PI / 2;
  2434. const theta = this.dot( v ) / denominator;
  2435. // clamp, to handle numerical problems
  2436. return Math.acos( clamp( theta, - 1, 1 ) );
  2437. }
  2438. distanceTo( v ) {
  2439. return Math.sqrt( this.distanceToSquared( v ) );
  2440. }
  2441. distanceToSquared( v ) {
  2442. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2443. return dx * dx + dy * dy + dz * dz;
  2444. }
  2445. manhattanDistanceTo( v ) {
  2446. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2447. }
  2448. setFromSpherical( s ) {
  2449. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2450. }
  2451. setFromSphericalCoords( radius, phi, theta ) {
  2452. const sinPhiRadius = Math.sin( phi ) * radius;
  2453. this.x = sinPhiRadius * Math.sin( theta );
  2454. this.y = Math.cos( phi ) * radius;
  2455. this.z = sinPhiRadius * Math.cos( theta );
  2456. return this;
  2457. }
  2458. setFromCylindrical( c ) {
  2459. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2460. }
  2461. setFromCylindricalCoords( radius, theta, y ) {
  2462. this.x = radius * Math.sin( theta );
  2463. this.y = y;
  2464. this.z = radius * Math.cos( theta );
  2465. return this;
  2466. }
  2467. setFromMatrixPosition( m ) {
  2468. const e = m.elements;
  2469. this.x = e[ 12 ];
  2470. this.y = e[ 13 ];
  2471. this.z = e[ 14 ];
  2472. return this;
  2473. }
  2474. setFromMatrixScale( m ) {
  2475. const sx = this.setFromMatrixColumn( m, 0 ).length();
  2476. const sy = this.setFromMatrixColumn( m, 1 ).length();
  2477. const sz = this.setFromMatrixColumn( m, 2 ).length();
  2478. this.x = sx;
  2479. this.y = sy;
  2480. this.z = sz;
  2481. return this;
  2482. }
  2483. setFromMatrixColumn( m, index ) {
  2484. return this.fromArray( m.elements, index * 4 );
  2485. }
  2486. setFromMatrix3Column( m, index ) {
  2487. return this.fromArray( m.elements, index * 3 );
  2488. }
  2489. equals( v ) {
  2490. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2491. }
  2492. fromArray( array, offset = 0 ) {
  2493. this.x = array[ offset ];
  2494. this.y = array[ offset + 1 ];
  2495. this.z = array[ offset + 2 ];
  2496. return this;
  2497. }
  2498. toArray( array = [], offset = 0 ) {
  2499. array[ offset ] = this.x;
  2500. array[ offset + 1 ] = this.y;
  2501. array[ offset + 2 ] = this.z;
  2502. return array;
  2503. }
  2504. fromBufferAttribute( attribute, index, offset ) {
  2505. if ( offset !== undefined ) {
  2506. console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' );
  2507. }
  2508. this.x = attribute.getX( index );
  2509. this.y = attribute.getY( index );
  2510. this.z = attribute.getZ( index );
  2511. return this;
  2512. }
  2513. random() {
  2514. this.x = Math.random();
  2515. this.y = Math.random();
  2516. this.z = Math.random();
  2517. return this;
  2518. }
  2519. randomDirection() {
  2520. // Derived from https://mathworld.wolfram.com/SpherePointPicking.html
  2521. const u = ( Math.random() - 0.5 ) * 2;
  2522. const t = Math.random() * Math.PI * 2;
  2523. const f = Math.sqrt( 1 - u ** 2 );
  2524. this.x = f * Math.cos( t );
  2525. this.y = f * Math.sin( t );
  2526. this.z = u;
  2527. return this;
  2528. }
  2529. *[ Symbol.iterator ]() {
  2530. yield this.x;
  2531. yield this.y;
  2532. yield this.z;
  2533. }
  2534. }
  2535. Vector3.prototype.isVector3 = true;
  2536. const _vector$c = /*@__PURE__*/ new Vector3();
  2537. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  2538. class Box3 {
  2539. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  2540. this.min = min;
  2541. this.max = max;
  2542. }
  2543. set( min, max ) {
  2544. this.min.copy( min );
  2545. this.max.copy( max );
  2546. return this;
  2547. }
  2548. setFromArray( array ) {
  2549. let minX = + Infinity;
  2550. let minY = + Infinity;
  2551. let minZ = + Infinity;
  2552. let maxX = - Infinity;
  2553. let maxY = - Infinity;
  2554. let maxZ = - Infinity;
  2555. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  2556. const x = array[ i ];
  2557. const y = array[ i + 1 ];
  2558. const z = array[ i + 2 ];
  2559. if ( x < minX ) minX = x;
  2560. if ( y < minY ) minY = y;
  2561. if ( z < minZ ) minZ = z;
  2562. if ( x > maxX ) maxX = x;
  2563. if ( y > maxY ) maxY = y;
  2564. if ( z > maxZ ) maxZ = z;
  2565. }
  2566. this.min.set( minX, minY, minZ );
  2567. this.max.set( maxX, maxY, maxZ );
  2568. return this;
  2569. }
  2570. setFromBufferAttribute( attribute ) {
  2571. let minX = + Infinity;
  2572. let minY = + Infinity;
  2573. let minZ = + Infinity;
  2574. let maxX = - Infinity;
  2575. let maxY = - Infinity;
  2576. let maxZ = - Infinity;
  2577. for ( let i = 0, l = attribute.count; i < l; i ++ ) {
  2578. const x = attribute.getX( i );
  2579. const y = attribute.getY( i );
  2580. const z = attribute.getZ( i );
  2581. if ( x < minX ) minX = x;
  2582. if ( y < minY ) minY = y;
  2583. if ( z < minZ ) minZ = z;
  2584. if ( x > maxX ) maxX = x;
  2585. if ( y > maxY ) maxY = y;
  2586. if ( z > maxZ ) maxZ = z;
  2587. }
  2588. this.min.set( minX, minY, minZ );
  2589. this.max.set( maxX, maxY, maxZ );
  2590. return this;
  2591. }
  2592. setFromPoints( points ) {
  2593. this.makeEmpty();
  2594. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2595. this.expandByPoint( points[ i ] );
  2596. }
  2597. return this;
  2598. }
  2599. setFromCenterAndSize( center, size ) {
  2600. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  2601. this.min.copy( center ).sub( halfSize );
  2602. this.max.copy( center ).add( halfSize );
  2603. return this;
  2604. }
  2605. setFromObject( object ) {
  2606. this.makeEmpty();
  2607. return this.expandByObject( object );
  2608. }
  2609. clone() {
  2610. return new this.constructor().copy( this );
  2611. }
  2612. copy( box ) {
  2613. this.min.copy( box.min );
  2614. this.max.copy( box.max );
  2615. return this;
  2616. }
  2617. makeEmpty() {
  2618. this.min.x = this.min.y = this.min.z = + Infinity;
  2619. this.max.x = this.max.y = this.max.z = - Infinity;
  2620. return this;
  2621. }
  2622. isEmpty() {
  2623. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2624. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2625. }
  2626. getCenter( target ) {
  2627. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2628. }
  2629. getSize( target ) {
  2630. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  2631. }
  2632. expandByPoint( point ) {
  2633. this.min.min( point );
  2634. this.max.max( point );
  2635. return this;
  2636. }
  2637. expandByVector( vector ) {
  2638. this.min.sub( vector );
  2639. this.max.add( vector );
  2640. return this;
  2641. }
  2642. expandByScalar( scalar ) {
  2643. this.min.addScalar( - scalar );
  2644. this.max.addScalar( scalar );
  2645. return this;
  2646. }
  2647. expandByObject( object ) {
  2648. // Computes the world-axis-aligned bounding box of an object (including its children),
  2649. // accounting for both the object's, and children's, world transforms
  2650. object.updateWorldMatrix( false, false );
  2651. const geometry = object.geometry;
  2652. if ( geometry !== undefined ) {
  2653. if ( geometry.boundingBox === null ) {
  2654. geometry.computeBoundingBox();
  2655. }
  2656. _box$3.copy( geometry.boundingBox );
  2657. _box$3.applyMatrix4( object.matrixWorld );
  2658. this.union( _box$3 );
  2659. }
  2660. const children = object.children;
  2661. for ( let i = 0, l = children.length; i < l; i ++ ) {
  2662. this.expandByObject( children[ i ] );
  2663. }
  2664. return this;
  2665. }
  2666. containsPoint( point ) {
  2667. return point.x < this.min.x || point.x > this.max.x ||
  2668. point.y < this.min.y || point.y > this.max.y ||
  2669. point.z < this.min.z || point.z > this.max.z ? false : true;
  2670. }
  2671. containsBox( box ) {
  2672. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  2673. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  2674. this.min.z <= box.min.z && box.max.z <= this.max.z;
  2675. }
  2676. getParameter( point, target ) {
  2677. // This can potentially have a divide by zero if the box
  2678. // has a size dimension of 0.
  2679. return target.set(
  2680. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2681. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2682. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2683. );
  2684. }
  2685. intersectsBox( box ) {
  2686. // using 6 splitting planes to rule out intersections.
  2687. return box.max.x < this.min.x || box.min.x > this.max.x ||
  2688. box.max.y < this.min.y || box.min.y > this.max.y ||
  2689. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  2690. }
  2691. intersectsSphere( sphere ) {
  2692. // Find the point on the AABB closest to the sphere center.
  2693. this.clampPoint( sphere.center, _vector$b );
  2694. // If that point is inside the sphere, the AABB and sphere intersect.
  2695. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  2696. }
  2697. intersectsPlane( plane ) {
  2698. // We compute the minimum and maximum dot product values. If those values
  2699. // are on the same side (back or front) of the plane, then there is no intersection.
  2700. let min, max;
  2701. if ( plane.normal.x > 0 ) {
  2702. min = plane.normal.x * this.min.x;
  2703. max = plane.normal.x * this.max.x;
  2704. } else {
  2705. min = plane.normal.x * this.max.x;
  2706. max = plane.normal.x * this.min.x;
  2707. }
  2708. if ( plane.normal.y > 0 ) {
  2709. min += plane.normal.y * this.min.y;
  2710. max += plane.normal.y * this.max.y;
  2711. } else {
  2712. min += plane.normal.y * this.max.y;
  2713. max += plane.normal.y * this.min.y;
  2714. }
  2715. if ( plane.normal.z > 0 ) {
  2716. min += plane.normal.z * this.min.z;
  2717. max += plane.normal.z * this.max.z;
  2718. } else {
  2719. min += plane.normal.z * this.max.z;
  2720. max += plane.normal.z * this.min.z;
  2721. }
  2722. return ( min <= - plane.constant && max >= - plane.constant );
  2723. }
  2724. intersectsTriangle( triangle ) {
  2725. if ( this.isEmpty() ) {
  2726. return false;
  2727. }
  2728. // compute box center and extents
  2729. this.getCenter( _center );
  2730. _extents.subVectors( this.max, _center );
  2731. // translate triangle to aabb origin
  2732. _v0$2.subVectors( triangle.a, _center );
  2733. _v1$7.subVectors( triangle.b, _center );
  2734. _v2$3.subVectors( triangle.c, _center );
  2735. // compute edge vectors for triangle
  2736. _f0.subVectors( _v1$7, _v0$2 );
  2737. _f1.subVectors( _v2$3, _v1$7 );
  2738. _f2.subVectors( _v0$2, _v2$3 );
  2739. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  2740. // 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
  2741. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2742. let axes = [
  2743. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  2744. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  2745. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  2746. ];
  2747. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents ) ) {
  2748. return false;
  2749. }
  2750. // test 3 face normals from the aabb
  2751. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  2752. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents ) ) {
  2753. return false;
  2754. }
  2755. // finally testing the face normal of the triangle
  2756. // use already existing triangle edge vectors here
  2757. _triangleNormal.crossVectors( _f0, _f1 );
  2758. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  2759. return satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents );
  2760. }
  2761. clampPoint( point, target ) {
  2762. return target.copy( point ).clamp( this.min, this.max );
  2763. }
  2764. distanceToPoint( point ) {
  2765. const clampedPoint = _vector$b.copy( point ).clamp( this.min, this.max );
  2766. return clampedPoint.sub( point ).length();
  2767. }
  2768. getBoundingSphere( target ) {
  2769. this.getCenter( target.center );
  2770. target.radius = this.getSize( _vector$b ).length() * 0.5;
  2771. return target;
  2772. }
  2773. intersect( box ) {
  2774. this.min.max( box.min );
  2775. this.max.min( box.max );
  2776. // 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.
  2777. if ( this.isEmpty() ) this.makeEmpty();
  2778. return this;
  2779. }
  2780. union( box ) {
  2781. this.min.min( box.min );
  2782. this.max.max( box.max );
  2783. return this;
  2784. }
  2785. applyMatrix4( matrix ) {
  2786. // transform of empty box is an empty box.
  2787. if ( this.isEmpty() ) return this;
  2788. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2789. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2790. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2791. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2792. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2793. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2794. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2795. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2796. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2797. this.setFromPoints( _points );
  2798. return this;
  2799. }
  2800. translate( offset ) {
  2801. this.min.add( offset );
  2802. this.max.add( offset );
  2803. return this;
  2804. }
  2805. equals( box ) {
  2806. return box.min.equals( this.min ) && box.max.equals( this.max );
  2807. }
  2808. }
  2809. Box3.prototype.isBox3 = true;
  2810. const _points = [
  2811. /*@__PURE__*/ new Vector3(),
  2812. /*@__PURE__*/ new Vector3(),
  2813. /*@__PURE__*/ new Vector3(),
  2814. /*@__PURE__*/ new Vector3(),
  2815. /*@__PURE__*/ new Vector3(),
  2816. /*@__PURE__*/ new Vector3(),
  2817. /*@__PURE__*/ new Vector3(),
  2818. /*@__PURE__*/ new Vector3()
  2819. ];
  2820. const _vector$b = /*@__PURE__*/ new Vector3();
  2821. const _box$3 = /*@__PURE__*/ new Box3();
  2822. // triangle centered vertices
  2823. const _v0$2 = /*@__PURE__*/ new Vector3();
  2824. const _v1$7 = /*@__PURE__*/ new Vector3();
  2825. const _v2$3 = /*@__PURE__*/ new Vector3();
  2826. // triangle edge vectors
  2827. const _f0 = /*@__PURE__*/ new Vector3();
  2828. const _f1 = /*@__PURE__*/ new Vector3();
  2829. const _f2 = /*@__PURE__*/ new Vector3();
  2830. const _center = /*@__PURE__*/ new Vector3();
  2831. const _extents = /*@__PURE__*/ new Vector3();
  2832. const _triangleNormal = /*@__PURE__*/ new Vector3();
  2833. const _testAxis = /*@__PURE__*/ new Vector3();
  2834. function satForAxes( axes, v0, v1, v2, extents ) {
  2835. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  2836. _testAxis.fromArray( axes, i );
  2837. // project the aabb onto the seperating axis
  2838. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  2839. // project all 3 vertices of the triangle onto the seperating axis
  2840. const p0 = v0.dot( _testAxis );
  2841. const p1 = v1.dot( _testAxis );
  2842. const p2 = v2.dot( _testAxis );
  2843. // actual test, basically see if either of the most extreme of the triangle points intersects r
  2844. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  2845. // points of the projected triangle are outside the projected half-length of the aabb
  2846. // the axis is seperating and we can exit
  2847. return false;
  2848. }
  2849. }
  2850. return true;
  2851. }
  2852. const _box$2 = /*@__PURE__*/ new Box3();
  2853. const _v1$6 = /*@__PURE__*/ new Vector3();
  2854. const _toFarthestPoint = /*@__PURE__*/ new Vector3();
  2855. const _toPoint = /*@__PURE__*/ new Vector3();
  2856. class Sphere {
  2857. constructor( center = new Vector3(), radius = - 1 ) {
  2858. this.center = center;
  2859. this.radius = radius;
  2860. }
  2861. set( center, radius ) {
  2862. this.center.copy( center );
  2863. this.radius = radius;
  2864. return this;
  2865. }
  2866. setFromPoints( points, optionalCenter ) {
  2867. const center = this.center;
  2868. if ( optionalCenter !== undefined ) {
  2869. center.copy( optionalCenter );
  2870. } else {
  2871. _box$2.setFromPoints( points ).getCenter( center );
  2872. }
  2873. let maxRadiusSq = 0;
  2874. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2875. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  2876. }
  2877. this.radius = Math.sqrt( maxRadiusSq );
  2878. return this;
  2879. }
  2880. copy( sphere ) {
  2881. this.center.copy( sphere.center );
  2882. this.radius = sphere.radius;
  2883. return this;
  2884. }
  2885. isEmpty() {
  2886. return ( this.radius < 0 );
  2887. }
  2888. makeEmpty() {
  2889. this.center.set( 0, 0, 0 );
  2890. this.radius = - 1;
  2891. return this;
  2892. }
  2893. containsPoint( point ) {
  2894. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  2895. }
  2896. distanceToPoint( point ) {
  2897. return ( point.distanceTo( this.center ) - this.radius );
  2898. }
  2899. intersectsSphere( sphere ) {
  2900. const radiusSum = this.radius + sphere.radius;
  2901. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  2902. }
  2903. intersectsBox( box ) {
  2904. return box.intersectsSphere( this );
  2905. }
  2906. intersectsPlane( plane ) {
  2907. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  2908. }
  2909. clampPoint( point, target ) {
  2910. const deltaLengthSq = this.center.distanceToSquared( point );
  2911. target.copy( point );
  2912. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  2913. target.sub( this.center ).normalize();
  2914. target.multiplyScalar( this.radius ).add( this.center );
  2915. }
  2916. return target;
  2917. }
  2918. getBoundingBox( target ) {
  2919. if ( this.isEmpty() ) {
  2920. // Empty sphere produces empty bounding box
  2921. target.makeEmpty();
  2922. return target;
  2923. }
  2924. target.set( this.center, this.center );
  2925. target.expandByScalar( this.radius );
  2926. return target;
  2927. }
  2928. applyMatrix4( matrix ) {
  2929. this.center.applyMatrix4( matrix );
  2930. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  2931. return this;
  2932. }
  2933. translate( offset ) {
  2934. this.center.add( offset );
  2935. return this;
  2936. }
  2937. expandByPoint( point ) {
  2938. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L649-L671
  2939. _toPoint.subVectors( point, this.center );
  2940. const lengthSq = _toPoint.lengthSq();
  2941. if ( lengthSq > ( this.radius * this.radius ) ) {
  2942. const length = Math.sqrt( lengthSq );
  2943. const missingRadiusHalf = ( length - this.radius ) * 0.5;
  2944. // Nudge this sphere towards the target point. Add half the missing distance to radius,
  2945. // and the other half to position. This gives a tighter enclosure, instead of if
  2946. // the whole missing distance were just added to radius.
  2947. this.center.add( _toPoint.multiplyScalar( missingRadiusHalf / length ) );
  2948. this.radius += missingRadiusHalf;
  2949. }
  2950. return this;
  2951. }
  2952. union( sphere ) {
  2953. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L759-L769
  2954. // To enclose another sphere into this sphere, we only need to enclose two points:
  2955. // 1) Enclose the farthest point on the other sphere into this sphere.
  2956. // 2) Enclose the opposite point of the farthest point into this sphere.
  2957. _toFarthestPoint.subVectors( sphere.center, this.center ).normalize().multiplyScalar( sphere.radius );
  2958. this.expandByPoint( _v1$6.copy( sphere.center ).add( _toFarthestPoint ) );
  2959. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _toFarthestPoint ) );
  2960. return this;
  2961. }
  2962. equals( sphere ) {
  2963. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  2964. }
  2965. clone() {
  2966. return new this.constructor().copy( this );
  2967. }
  2968. }
  2969. const _vector$a = /*@__PURE__*/ new Vector3();
  2970. const _segCenter = /*@__PURE__*/ new Vector3();
  2971. const _segDir = /*@__PURE__*/ new Vector3();
  2972. const _diff = /*@__PURE__*/ new Vector3();
  2973. const _edge1 = /*@__PURE__*/ new Vector3();
  2974. const _edge2 = /*@__PURE__*/ new Vector3();
  2975. const _normal$1 = /*@__PURE__*/ new Vector3();
  2976. class Ray {
  2977. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  2978. this.origin = origin;
  2979. this.direction = direction;
  2980. }
  2981. set( origin, direction ) {
  2982. this.origin.copy( origin );
  2983. this.direction.copy( direction );
  2984. return this;
  2985. }
  2986. copy( ray ) {
  2987. this.origin.copy( ray.origin );
  2988. this.direction.copy( ray.direction );
  2989. return this;
  2990. }
  2991. at( t, target ) {
  2992. return target.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  2993. }
  2994. lookAt( v ) {
  2995. this.direction.copy( v ).sub( this.origin ).normalize();
  2996. return this;
  2997. }
  2998. recast( t ) {
  2999. this.origin.copy( this.at( t, _vector$a ) );
  3000. return this;
  3001. }
  3002. closestPointToPoint( point, target ) {
  3003. target.subVectors( point, this.origin );
  3004. const directionDistance = target.dot( this.direction );
  3005. if ( directionDistance < 0 ) {
  3006. return target.copy( this.origin );
  3007. }
  3008. return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3009. }
  3010. distanceToPoint( point ) {
  3011. return Math.sqrt( this.distanceSqToPoint( point ) );
  3012. }
  3013. distanceSqToPoint( point ) {
  3014. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  3015. // point behind the ray
  3016. if ( directionDistance < 0 ) {
  3017. return this.origin.distanceToSquared( point );
  3018. }
  3019. _vector$a.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3020. return _vector$a.distanceToSquared( point );
  3021. }
  3022. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3023. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3024. // It returns the min distance between the ray and the segment
  3025. // defined by v0 and v1
  3026. // It can also set two optional targets :
  3027. // - The closest point on the ray
  3028. // - The closest point on the segment
  3029. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3030. _segDir.copy( v1 ).sub( v0 ).normalize();
  3031. _diff.copy( this.origin ).sub( _segCenter );
  3032. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3033. const a01 = - this.direction.dot( _segDir );
  3034. const b0 = _diff.dot( this.direction );
  3035. const b1 = - _diff.dot( _segDir );
  3036. const c = _diff.lengthSq();
  3037. const det = Math.abs( 1 - a01 * a01 );
  3038. let s0, s1, sqrDist, extDet;
  3039. if ( det > 0 ) {
  3040. // The ray and segment are not parallel.
  3041. s0 = a01 * b1 - b0;
  3042. s1 = a01 * b0 - b1;
  3043. extDet = segExtent * det;
  3044. if ( s0 >= 0 ) {
  3045. if ( s1 >= - extDet ) {
  3046. if ( s1 <= extDet ) {
  3047. // region 0
  3048. // Minimum at interior points of ray and segment.
  3049. const invDet = 1 / det;
  3050. s0 *= invDet;
  3051. s1 *= invDet;
  3052. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3053. } else {
  3054. // region 1
  3055. s1 = segExtent;
  3056. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3057. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3058. }
  3059. } else {
  3060. // region 5
  3061. s1 = - segExtent;
  3062. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3063. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3064. }
  3065. } else {
  3066. if ( s1 <= - extDet ) {
  3067. // region 4
  3068. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3069. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3070. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3071. } else if ( s1 <= extDet ) {
  3072. // region 3
  3073. s0 = 0;
  3074. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3075. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3076. } else {
  3077. // region 2
  3078. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3079. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3080. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3081. }
  3082. }
  3083. } else {
  3084. // Ray and segment are parallel.
  3085. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3086. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3087. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3088. }
  3089. if ( optionalPointOnRay ) {
  3090. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  3091. }
  3092. if ( optionalPointOnSegment ) {
  3093. optionalPointOnSegment.copy( _segDir ).multiplyScalar( s1 ).add( _segCenter );
  3094. }
  3095. return sqrDist;
  3096. }
  3097. intersectSphere( sphere, target ) {
  3098. _vector$a.subVectors( sphere.center, this.origin );
  3099. const tca = _vector$a.dot( this.direction );
  3100. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  3101. const radius2 = sphere.radius * sphere.radius;
  3102. if ( d2 > radius2 ) return null;
  3103. const thc = Math.sqrt( radius2 - d2 );
  3104. // t0 = first intersect point - entrance on front of sphere
  3105. const t0 = tca - thc;
  3106. // t1 = second intersect point - exit point on back of sphere
  3107. const t1 = tca + thc;
  3108. // test to see if both t0 and t1 are behind the ray - if so, return null
  3109. if ( t0 < 0 && t1 < 0 ) return null;
  3110. // test to see if t0 is behind the ray:
  3111. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3112. // in order to always return an intersect point that is in front of the ray.
  3113. if ( t0 < 0 ) return this.at( t1, target );
  3114. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3115. return this.at( t0, target );
  3116. }
  3117. intersectsSphere( sphere ) {
  3118. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3119. }
  3120. distanceToPlane( plane ) {
  3121. const denominator = plane.normal.dot( this.direction );
  3122. if ( denominator === 0 ) {
  3123. // line is coplanar, return origin
  3124. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3125. return 0;
  3126. }
  3127. // Null is preferable to undefined since undefined means.... it is undefined
  3128. return null;
  3129. }
  3130. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3131. // Return if the ray never intersects the plane
  3132. return t >= 0 ? t : null;
  3133. }
  3134. intersectPlane( plane, target ) {
  3135. const t = this.distanceToPlane( plane );
  3136. if ( t === null ) {
  3137. return null;
  3138. }
  3139. return this.at( t, target );
  3140. }
  3141. intersectsPlane( plane ) {
  3142. // check if the ray lies on the plane first
  3143. const distToPoint = plane.distanceToPoint( this.origin );
  3144. if ( distToPoint === 0 ) {
  3145. return true;
  3146. }
  3147. const denominator = plane.normal.dot( this.direction );
  3148. if ( denominator * distToPoint < 0 ) {
  3149. return true;
  3150. }
  3151. // ray origin is behind the plane (and is pointing behind it)
  3152. return false;
  3153. }
  3154. intersectBox( box, target ) {
  3155. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3156. const invdirx = 1 / this.direction.x,
  3157. invdiry = 1 / this.direction.y,
  3158. invdirz = 1 / this.direction.z;
  3159. const origin = this.origin;
  3160. if ( invdirx >= 0 ) {
  3161. tmin = ( box.min.x - origin.x ) * invdirx;
  3162. tmax = ( box.max.x - origin.x ) * invdirx;
  3163. } else {
  3164. tmin = ( box.max.x - origin.x ) * invdirx;
  3165. tmax = ( box.min.x - origin.x ) * invdirx;
  3166. }
  3167. if ( invdiry >= 0 ) {
  3168. tymin = ( box.min.y - origin.y ) * invdiry;
  3169. tymax = ( box.max.y - origin.y ) * invdiry;
  3170. } else {
  3171. tymin = ( box.max.y - origin.y ) * invdiry;
  3172. tymax = ( box.min.y - origin.y ) * invdiry;
  3173. }
  3174. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3175. // These lines also handle the case where tmin or tmax is NaN
  3176. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3177. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  3178. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  3179. if ( invdirz >= 0 ) {
  3180. tzmin = ( box.min.z - origin.z ) * invdirz;
  3181. tzmax = ( box.max.z - origin.z ) * invdirz;
  3182. } else {
  3183. tzmin = ( box.max.z - origin.z ) * invdirz;
  3184. tzmax = ( box.min.z - origin.z ) * invdirz;
  3185. }
  3186. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3187. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3188. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3189. //return point closest to the ray (positive side)
  3190. if ( tmax < 0 ) return null;
  3191. return this.at( tmin >= 0 ? tmin : tmax, target );
  3192. }
  3193. intersectsBox( box ) {
  3194. return this.intersectBox( box, _vector$a ) !== null;
  3195. }
  3196. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3197. // Compute the offset origin, edges, and normal.
  3198. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3199. _edge1.subVectors( b, a );
  3200. _edge2.subVectors( c, a );
  3201. _normal$1.crossVectors( _edge1, _edge2 );
  3202. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3203. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3204. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3205. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3206. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3207. let DdN = this.direction.dot( _normal$1 );
  3208. let sign;
  3209. if ( DdN > 0 ) {
  3210. if ( backfaceCulling ) return null;
  3211. sign = 1;
  3212. } else if ( DdN < 0 ) {
  3213. sign = - 1;
  3214. DdN = - DdN;
  3215. } else {
  3216. return null;
  3217. }
  3218. _diff.subVectors( this.origin, a );
  3219. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3220. // b1 < 0, no intersection
  3221. if ( DdQxE2 < 0 ) {
  3222. return null;
  3223. }
  3224. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3225. // b2 < 0, no intersection
  3226. if ( DdE1xQ < 0 ) {
  3227. return null;
  3228. }
  3229. // b1+b2 > 1, no intersection
  3230. if ( DdQxE2 + DdE1xQ > DdN ) {
  3231. return null;
  3232. }
  3233. // Line intersects triangle, check if ray does.
  3234. const QdN = - sign * _diff.dot( _normal$1 );
  3235. // t < 0, no intersection
  3236. if ( QdN < 0 ) {
  3237. return null;
  3238. }
  3239. // Ray intersects triangle.
  3240. return this.at( QdN / DdN, target );
  3241. }
  3242. applyMatrix4( matrix4 ) {
  3243. this.origin.applyMatrix4( matrix4 );
  3244. this.direction.transformDirection( matrix4 );
  3245. return this;
  3246. }
  3247. equals( ray ) {
  3248. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3249. }
  3250. clone() {
  3251. return new this.constructor().copy( this );
  3252. }
  3253. }
  3254. class Matrix4 {
  3255. constructor() {
  3256. this.elements = [
  3257. 1, 0, 0, 0,
  3258. 0, 1, 0, 0,
  3259. 0, 0, 1, 0,
  3260. 0, 0, 0, 1
  3261. ];
  3262. if ( arguments.length > 0 ) {
  3263. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  3264. }
  3265. }
  3266. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3267. const te = this.elements;
  3268. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3269. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3270. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3271. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3272. return this;
  3273. }
  3274. identity() {
  3275. this.set(
  3276. 1, 0, 0, 0,
  3277. 0, 1, 0, 0,
  3278. 0, 0, 1, 0,
  3279. 0, 0, 0, 1
  3280. );
  3281. return this;
  3282. }
  3283. clone() {
  3284. return new Matrix4().fromArray( this.elements );
  3285. }
  3286. copy( m ) {
  3287. const te = this.elements;
  3288. const me = m.elements;
  3289. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3290. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3291. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3292. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3293. return this;
  3294. }
  3295. copyPosition( m ) {
  3296. const te = this.elements, me = m.elements;
  3297. te[ 12 ] = me[ 12 ];
  3298. te[ 13 ] = me[ 13 ];
  3299. te[ 14 ] = me[ 14 ];
  3300. return this;
  3301. }
  3302. setFromMatrix3( m ) {
  3303. const me = m.elements;
  3304. this.set(
  3305. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3306. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3307. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3308. 0, 0, 0, 1
  3309. );
  3310. return this;
  3311. }
  3312. extractBasis( xAxis, yAxis, zAxis ) {
  3313. xAxis.setFromMatrixColumn( this, 0 );
  3314. yAxis.setFromMatrixColumn( this, 1 );
  3315. zAxis.setFromMatrixColumn( this, 2 );
  3316. return this;
  3317. }
  3318. makeBasis( xAxis, yAxis, zAxis ) {
  3319. this.set(
  3320. xAxis.x, yAxis.x, zAxis.x, 0,
  3321. xAxis.y, yAxis.y, zAxis.y, 0,
  3322. xAxis.z, yAxis.z, zAxis.z, 0,
  3323. 0, 0, 0, 1
  3324. );
  3325. return this;
  3326. }
  3327. extractRotation( m ) {
  3328. // this method does not support reflection matrices
  3329. const te = this.elements;
  3330. const me = m.elements;
  3331. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  3332. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  3333. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  3334. te[ 0 ] = me[ 0 ] * scaleX;
  3335. te[ 1 ] = me[ 1 ] * scaleX;
  3336. te[ 2 ] = me[ 2 ] * scaleX;
  3337. te[ 3 ] = 0;
  3338. te[ 4 ] = me[ 4 ] * scaleY;
  3339. te[ 5 ] = me[ 5 ] * scaleY;
  3340. te[ 6 ] = me[ 6 ] * scaleY;
  3341. te[ 7 ] = 0;
  3342. te[ 8 ] = me[ 8 ] * scaleZ;
  3343. te[ 9 ] = me[ 9 ] * scaleZ;
  3344. te[ 10 ] = me[ 10 ] * scaleZ;
  3345. te[ 11 ] = 0;
  3346. te[ 12 ] = 0;
  3347. te[ 13 ] = 0;
  3348. te[ 14 ] = 0;
  3349. te[ 15 ] = 1;
  3350. return this;
  3351. }
  3352. makeRotationFromEuler( euler ) {
  3353. if ( ! ( euler && euler.isEuler ) ) {
  3354. console.error( 'THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  3355. }
  3356. const te = this.elements;
  3357. const x = euler.x, y = euler.y, z = euler.z;
  3358. const a = Math.cos( x ), b = Math.sin( x );
  3359. const c = Math.cos( y ), d = Math.sin( y );
  3360. const e = Math.cos( z ), f = Math.sin( z );
  3361. if ( euler.order === 'XYZ' ) {
  3362. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3363. te[ 0 ] = c * e;
  3364. te[ 4 ] = - c * f;
  3365. te[ 8 ] = d;
  3366. te[ 1 ] = af + be * d;
  3367. te[ 5 ] = ae - bf * d;
  3368. te[ 9 ] = - b * c;
  3369. te[ 2 ] = bf - ae * d;
  3370. te[ 6 ] = be + af * d;
  3371. te[ 10 ] = a * c;
  3372. } else if ( euler.order === 'YXZ' ) {
  3373. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3374. te[ 0 ] = ce + df * b;
  3375. te[ 4 ] = de * b - cf;
  3376. te[ 8 ] = a * d;
  3377. te[ 1 ] = a * f;
  3378. te[ 5 ] = a * e;
  3379. te[ 9 ] = - b;
  3380. te[ 2 ] = cf * b - de;
  3381. te[ 6 ] = df + ce * b;
  3382. te[ 10 ] = a * c;
  3383. } else if ( euler.order === 'ZXY' ) {
  3384. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3385. te[ 0 ] = ce - df * b;
  3386. te[ 4 ] = - a * f;
  3387. te[ 8 ] = de + cf * b;
  3388. te[ 1 ] = cf + de * b;
  3389. te[ 5 ] = a * e;
  3390. te[ 9 ] = df - ce * b;
  3391. te[ 2 ] = - a * d;
  3392. te[ 6 ] = b;
  3393. te[ 10 ] = a * c;
  3394. } else if ( euler.order === 'ZYX' ) {
  3395. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3396. te[ 0 ] = c * e;
  3397. te[ 4 ] = be * d - af;
  3398. te[ 8 ] = ae * d + bf;
  3399. te[ 1 ] = c * f;
  3400. te[ 5 ] = bf * d + ae;
  3401. te[ 9 ] = af * d - be;
  3402. te[ 2 ] = - d;
  3403. te[ 6 ] = b * c;
  3404. te[ 10 ] = a * c;
  3405. } else if ( euler.order === 'YZX' ) {
  3406. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3407. te[ 0 ] = c * e;
  3408. te[ 4 ] = bd - ac * f;
  3409. te[ 8 ] = bc * f + ad;
  3410. te[ 1 ] = f;
  3411. te[ 5 ] = a * e;
  3412. te[ 9 ] = - b * e;
  3413. te[ 2 ] = - d * e;
  3414. te[ 6 ] = ad * f + bc;
  3415. te[ 10 ] = ac - bd * f;
  3416. } else if ( euler.order === 'XZY' ) {
  3417. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3418. te[ 0 ] = c * e;
  3419. te[ 4 ] = - f;
  3420. te[ 8 ] = d * e;
  3421. te[ 1 ] = ac * f + bd;
  3422. te[ 5 ] = a * e;
  3423. te[ 9 ] = ad * f - bc;
  3424. te[ 2 ] = bc * f - ad;
  3425. te[ 6 ] = b * e;
  3426. te[ 10 ] = bd * f + ac;
  3427. }
  3428. // bottom row
  3429. te[ 3 ] = 0;
  3430. te[ 7 ] = 0;
  3431. te[ 11 ] = 0;
  3432. // last column
  3433. te[ 12 ] = 0;
  3434. te[ 13 ] = 0;
  3435. te[ 14 ] = 0;
  3436. te[ 15 ] = 1;
  3437. return this;
  3438. }
  3439. makeRotationFromQuaternion( q ) {
  3440. return this.compose( _zero, q, _one );
  3441. }
  3442. lookAt( eye, target, up ) {
  3443. const te = this.elements;
  3444. _z.subVectors( eye, target );
  3445. if ( _z.lengthSq() === 0 ) {
  3446. // eye and target are in the same position
  3447. _z.z = 1;
  3448. }
  3449. _z.normalize();
  3450. _x.crossVectors( up, _z );
  3451. if ( _x.lengthSq() === 0 ) {
  3452. // up and z are parallel
  3453. if ( Math.abs( up.z ) === 1 ) {
  3454. _z.x += 0.0001;
  3455. } else {
  3456. _z.z += 0.0001;
  3457. }
  3458. _z.normalize();
  3459. _x.crossVectors( up, _z );
  3460. }
  3461. _x.normalize();
  3462. _y.crossVectors( _z, _x );
  3463. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3464. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3465. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3466. return this;
  3467. }
  3468. multiply( m, n ) {
  3469. if ( n !== undefined ) {
  3470. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  3471. return this.multiplyMatrices( m, n );
  3472. }
  3473. return this.multiplyMatrices( this, m );
  3474. }
  3475. premultiply( m ) {
  3476. return this.multiplyMatrices( m, this );
  3477. }
  3478. multiplyMatrices( a, b ) {
  3479. const ae = a.elements;
  3480. const be = b.elements;
  3481. const te = this.elements;
  3482. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3483. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3484. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3485. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3486. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3487. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3488. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3489. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3490. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3491. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3492. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3493. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3494. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3495. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3496. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3497. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3498. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3499. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3500. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3501. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3502. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3503. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3504. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3505. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3506. return this;
  3507. }
  3508. multiplyScalar( s ) {
  3509. const te = this.elements;
  3510. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3511. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3512. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3513. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3514. return this;
  3515. }
  3516. determinant() {
  3517. const te = this.elements;
  3518. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3519. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3520. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3521. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3522. //TODO: make this more efficient
  3523. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3524. return (
  3525. n41 * (
  3526. + n14 * n23 * n32
  3527. - n13 * n24 * n32
  3528. - n14 * n22 * n33
  3529. + n12 * n24 * n33
  3530. + n13 * n22 * n34
  3531. - n12 * n23 * n34
  3532. ) +
  3533. n42 * (
  3534. + n11 * n23 * n34
  3535. - n11 * n24 * n33
  3536. + n14 * n21 * n33
  3537. - n13 * n21 * n34
  3538. + n13 * n24 * n31
  3539. - n14 * n23 * n31
  3540. ) +
  3541. n43 * (
  3542. + n11 * n24 * n32
  3543. - n11 * n22 * n34
  3544. - n14 * n21 * n32
  3545. + n12 * n21 * n34
  3546. + n14 * n22 * n31
  3547. - n12 * n24 * n31
  3548. ) +
  3549. n44 * (
  3550. - n13 * n22 * n31
  3551. - n11 * n23 * n32
  3552. + n11 * n22 * n33
  3553. + n13 * n21 * n32
  3554. - n12 * n21 * n33
  3555. + n12 * n23 * n31
  3556. )
  3557. );
  3558. }
  3559. transpose() {
  3560. const te = this.elements;
  3561. let tmp;
  3562. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3563. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3564. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3565. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3566. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3567. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3568. return this;
  3569. }
  3570. setPosition( x, y, z ) {
  3571. const te = this.elements;
  3572. if ( x.isVector3 ) {
  3573. te[ 12 ] = x.x;
  3574. te[ 13 ] = x.y;
  3575. te[ 14 ] = x.z;
  3576. } else {
  3577. te[ 12 ] = x;
  3578. te[ 13 ] = y;
  3579. te[ 14 ] = z;
  3580. }
  3581. return this;
  3582. }
  3583. invert() {
  3584. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3585. const te = this.elements,
  3586. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  3587. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  3588. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  3589. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  3590. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3591. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3592. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3593. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3594. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3595. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  3596. const detInv = 1 / det;
  3597. te[ 0 ] = t11 * detInv;
  3598. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  3599. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  3600. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  3601. te[ 4 ] = t12 * detInv;
  3602. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  3603. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  3604. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  3605. te[ 8 ] = t13 * detInv;
  3606. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  3607. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  3608. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  3609. te[ 12 ] = t14 * detInv;
  3610. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  3611. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  3612. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  3613. return this;
  3614. }
  3615. scale( v ) {
  3616. const te = this.elements;
  3617. const x = v.x, y = v.y, z = v.z;
  3618. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3619. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3620. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3621. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3622. return this;
  3623. }
  3624. getMaxScaleOnAxis() {
  3625. const te = this.elements;
  3626. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3627. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3628. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3629. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3630. }
  3631. makeTranslation( x, y, z ) {
  3632. this.set(
  3633. 1, 0, 0, x,
  3634. 0, 1, 0, y,
  3635. 0, 0, 1, z,
  3636. 0, 0, 0, 1
  3637. );
  3638. return this;
  3639. }
  3640. makeRotationX( theta ) {
  3641. const c = Math.cos( theta ), s = Math.sin( theta );
  3642. this.set(
  3643. 1, 0, 0, 0,
  3644. 0, c, - s, 0,
  3645. 0, s, c, 0,
  3646. 0, 0, 0, 1
  3647. );
  3648. return this;
  3649. }
  3650. makeRotationY( theta ) {
  3651. const c = Math.cos( theta ), s = Math.sin( theta );
  3652. this.set(
  3653. c, 0, s, 0,
  3654. 0, 1, 0, 0,
  3655. - s, 0, c, 0,
  3656. 0, 0, 0, 1
  3657. );
  3658. return this;
  3659. }
  3660. makeRotationZ( theta ) {
  3661. const c = Math.cos( theta ), s = Math.sin( theta );
  3662. this.set(
  3663. c, - s, 0, 0,
  3664. s, c, 0, 0,
  3665. 0, 0, 1, 0,
  3666. 0, 0, 0, 1
  3667. );
  3668. return this;
  3669. }
  3670. makeRotationAxis( axis, angle ) {
  3671. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3672. const c = Math.cos( angle );
  3673. const s = Math.sin( angle );
  3674. const t = 1 - c;
  3675. const x = axis.x, y = axis.y, z = axis.z;
  3676. const tx = t * x, ty = t * y;
  3677. this.set(
  3678. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3679. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3680. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3681. 0, 0, 0, 1
  3682. );
  3683. return this;
  3684. }
  3685. makeScale( x, y, z ) {
  3686. this.set(
  3687. x, 0, 0, 0,
  3688. 0, y, 0, 0,
  3689. 0, 0, z, 0,
  3690. 0, 0, 0, 1
  3691. );
  3692. return this;
  3693. }
  3694. makeShear( xy, xz, yx, yz, zx, zy ) {
  3695. this.set(
  3696. 1, yx, zx, 0,
  3697. xy, 1, zy, 0,
  3698. xz, yz, 1, 0,
  3699. 0, 0, 0, 1
  3700. );
  3701. return this;
  3702. }
  3703. compose( position, quaternion, scale ) {
  3704. const te = this.elements;
  3705. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  3706. const x2 = x + x, y2 = y + y, z2 = z + z;
  3707. const xx = x * x2, xy = x * y2, xz = x * z2;
  3708. const yy = y * y2, yz = y * z2, zz = z * z2;
  3709. const wx = w * x2, wy = w * y2, wz = w * z2;
  3710. const sx = scale.x, sy = scale.y, sz = scale.z;
  3711. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  3712. te[ 1 ] = ( xy + wz ) * sx;
  3713. te[ 2 ] = ( xz - wy ) * sx;
  3714. te[ 3 ] = 0;
  3715. te[ 4 ] = ( xy - wz ) * sy;
  3716. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  3717. te[ 6 ] = ( yz + wx ) * sy;
  3718. te[ 7 ] = 0;
  3719. te[ 8 ] = ( xz + wy ) * sz;
  3720. te[ 9 ] = ( yz - wx ) * sz;
  3721. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  3722. te[ 11 ] = 0;
  3723. te[ 12 ] = position.x;
  3724. te[ 13 ] = position.y;
  3725. te[ 14 ] = position.z;
  3726. te[ 15 ] = 1;
  3727. return this;
  3728. }
  3729. decompose( position, quaternion, scale ) {
  3730. const te = this.elements;
  3731. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  3732. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  3733. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  3734. // if determine is negative, we need to invert one scale
  3735. const det = this.determinant();
  3736. if ( det < 0 ) sx = - sx;
  3737. position.x = te[ 12 ];
  3738. position.y = te[ 13 ];
  3739. position.z = te[ 14 ];
  3740. // scale the rotation part
  3741. _m1$2.copy( this );
  3742. const invSX = 1 / sx;
  3743. const invSY = 1 / sy;
  3744. const invSZ = 1 / sz;
  3745. _m1$2.elements[ 0 ] *= invSX;
  3746. _m1$2.elements[ 1 ] *= invSX;
  3747. _m1$2.elements[ 2 ] *= invSX;
  3748. _m1$2.elements[ 4 ] *= invSY;
  3749. _m1$2.elements[ 5 ] *= invSY;
  3750. _m1$2.elements[ 6 ] *= invSY;
  3751. _m1$2.elements[ 8 ] *= invSZ;
  3752. _m1$2.elements[ 9 ] *= invSZ;
  3753. _m1$2.elements[ 10 ] *= invSZ;
  3754. quaternion.setFromRotationMatrix( _m1$2 );
  3755. scale.x = sx;
  3756. scale.y = sy;
  3757. scale.z = sz;
  3758. return this;
  3759. }
  3760. makePerspective( left, right, top, bottom, near, far ) {
  3761. if ( far === undefined ) {
  3762. console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' );
  3763. }
  3764. const te = this.elements;
  3765. const x = 2 * near / ( right - left );
  3766. const y = 2 * near / ( top - bottom );
  3767. const a = ( right + left ) / ( right - left );
  3768. const b = ( top + bottom ) / ( top - bottom );
  3769. const c = - ( far + near ) / ( far - near );
  3770. const d = - 2 * far * near / ( far - near );
  3771. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  3772. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  3773. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  3774. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  3775. return this;
  3776. }
  3777. makeOrthographic( left, right, top, bottom, near, far ) {
  3778. const te = this.elements;
  3779. const w = 1.0 / ( right - left );
  3780. const h = 1.0 / ( top - bottom );
  3781. const p = 1.0 / ( far - near );
  3782. const x = ( right + left ) * w;
  3783. const y = ( top + bottom ) * h;
  3784. const z = ( far + near ) * p;
  3785. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  3786. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  3787. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  3788. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  3789. return this;
  3790. }
  3791. equals( matrix ) {
  3792. const te = this.elements;
  3793. const me = matrix.elements;
  3794. for ( let i = 0; i < 16; i ++ ) {
  3795. if ( te[ i ] !== me[ i ] ) return false;
  3796. }
  3797. return true;
  3798. }
  3799. fromArray( array, offset = 0 ) {
  3800. for ( let i = 0; i < 16; i ++ ) {
  3801. this.elements[ i ] = array[ i + offset ];
  3802. }
  3803. return this;
  3804. }
  3805. toArray( array = [], offset = 0 ) {
  3806. const te = this.elements;
  3807. array[ offset ] = te[ 0 ];
  3808. array[ offset + 1 ] = te[ 1 ];
  3809. array[ offset + 2 ] = te[ 2 ];
  3810. array[ offset + 3 ] = te[ 3 ];
  3811. array[ offset + 4 ] = te[ 4 ];
  3812. array[ offset + 5 ] = te[ 5 ];
  3813. array[ offset + 6 ] = te[ 6 ];
  3814. array[ offset + 7 ] = te[ 7 ];
  3815. array[ offset + 8 ] = te[ 8 ];
  3816. array[ offset + 9 ] = te[ 9 ];
  3817. array[ offset + 10 ] = te[ 10 ];
  3818. array[ offset + 11 ] = te[ 11 ];
  3819. array[ offset + 12 ] = te[ 12 ];
  3820. array[ offset + 13 ] = te[ 13 ];
  3821. array[ offset + 14 ] = te[ 14 ];
  3822. array[ offset + 15 ] = te[ 15 ];
  3823. return array;
  3824. }
  3825. }
  3826. Matrix4.prototype.isMatrix4 = true;
  3827. const _v1$5 = /*@__PURE__*/ new Vector3();
  3828. const _m1$2 = /*@__PURE__*/ new Matrix4();
  3829. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  3830. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  3831. const _x = /*@__PURE__*/ new Vector3();
  3832. const _y = /*@__PURE__*/ new Vector3();
  3833. const _z = /*@__PURE__*/ new Vector3();
  3834. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  3835. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  3836. class Euler {
  3837. constructor( x = 0, y = 0, z = 0, order = Euler.DefaultOrder ) {
  3838. this._x = x;
  3839. this._y = y;
  3840. this._z = z;
  3841. this._order = order;
  3842. }
  3843. get x() {
  3844. return this._x;
  3845. }
  3846. set x( value ) {
  3847. this._x = value;
  3848. this._onChangeCallback();
  3849. }
  3850. get y() {
  3851. return this._y;
  3852. }
  3853. set y( value ) {
  3854. this._y = value;
  3855. this._onChangeCallback();
  3856. }
  3857. get z() {
  3858. return this._z;
  3859. }
  3860. set z( value ) {
  3861. this._z = value;
  3862. this._onChangeCallback();
  3863. }
  3864. get order() {
  3865. return this._order;
  3866. }
  3867. set order( value ) {
  3868. this._order = value;
  3869. this._onChangeCallback();
  3870. }
  3871. set( x, y, z, order = this._order ) {
  3872. this._x = x;
  3873. this._y = y;
  3874. this._z = z;
  3875. this._order = order;
  3876. this._onChangeCallback();
  3877. return this;
  3878. }
  3879. clone() {
  3880. return new this.constructor( this._x, this._y, this._z, this._order );
  3881. }
  3882. copy( euler ) {
  3883. this._x = euler._x;
  3884. this._y = euler._y;
  3885. this._z = euler._z;
  3886. this._order = euler._order;
  3887. this._onChangeCallback();
  3888. return this;
  3889. }
  3890. setFromRotationMatrix( m, order = this._order, update = true ) {
  3891. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3892. const te = m.elements;
  3893. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  3894. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  3895. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  3896. switch ( order ) {
  3897. case 'XYZ':
  3898. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  3899. if ( Math.abs( m13 ) < 0.9999999 ) {
  3900. this._x = Math.atan2( - m23, m33 );
  3901. this._z = Math.atan2( - m12, m11 );
  3902. } else {
  3903. this._x = Math.atan2( m32, m22 );
  3904. this._z = 0;
  3905. }
  3906. break;
  3907. case 'YXZ':
  3908. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  3909. if ( Math.abs( m23 ) < 0.9999999 ) {
  3910. this._y = Math.atan2( m13, m33 );
  3911. this._z = Math.atan2( m21, m22 );
  3912. } else {
  3913. this._y = Math.atan2( - m31, m11 );
  3914. this._z = 0;
  3915. }
  3916. break;
  3917. case 'ZXY':
  3918. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  3919. if ( Math.abs( m32 ) < 0.9999999 ) {
  3920. this._y = Math.atan2( - m31, m33 );
  3921. this._z = Math.atan2( - m12, m22 );
  3922. } else {
  3923. this._y = 0;
  3924. this._z = Math.atan2( m21, m11 );
  3925. }
  3926. break;
  3927. case 'ZYX':
  3928. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  3929. if ( Math.abs( m31 ) < 0.9999999 ) {
  3930. this._x = Math.atan2( m32, m33 );
  3931. this._z = Math.atan2( m21, m11 );
  3932. } else {
  3933. this._x = 0;
  3934. this._z = Math.atan2( - m12, m22 );
  3935. }
  3936. break;
  3937. case 'YZX':
  3938. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  3939. if ( Math.abs( m21 ) < 0.9999999 ) {
  3940. this._x = Math.atan2( - m23, m22 );
  3941. this._y = Math.atan2( - m31, m11 );
  3942. } else {
  3943. this._x = 0;
  3944. this._y = Math.atan2( m13, m33 );
  3945. }
  3946. break;
  3947. case 'XZY':
  3948. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  3949. if ( Math.abs( m12 ) < 0.9999999 ) {
  3950. this._x = Math.atan2( m32, m22 );
  3951. this._y = Math.atan2( m13, m11 );
  3952. } else {
  3953. this._x = Math.atan2( - m23, m33 );
  3954. this._y = 0;
  3955. }
  3956. break;
  3957. default:
  3958. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  3959. }
  3960. this._order = order;
  3961. if ( update === true ) this._onChangeCallback();
  3962. return this;
  3963. }
  3964. setFromQuaternion( q, order, update ) {
  3965. _matrix$1.makeRotationFromQuaternion( q );
  3966. return this.setFromRotationMatrix( _matrix$1, order, update );
  3967. }
  3968. setFromVector3( v, order = this._order ) {
  3969. return this.set( v.x, v.y, v.z, order );
  3970. }
  3971. reorder( newOrder ) {
  3972. // WARNING: this discards revolution information -bhouston
  3973. _quaternion$3.setFromEuler( this );
  3974. return this.setFromQuaternion( _quaternion$3, newOrder );
  3975. }
  3976. equals( euler ) {
  3977. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  3978. }
  3979. fromArray( array ) {
  3980. this._x = array[ 0 ];
  3981. this._y = array[ 1 ];
  3982. this._z = array[ 2 ];
  3983. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  3984. this._onChangeCallback();
  3985. return this;
  3986. }
  3987. toArray( array = [], offset = 0 ) {
  3988. array[ offset ] = this._x;
  3989. array[ offset + 1 ] = this._y;
  3990. array[ offset + 2 ] = this._z;
  3991. array[ offset + 3 ] = this._order;
  3992. return array;
  3993. }
  3994. toVector3( optionalResult ) {
  3995. if ( optionalResult ) {
  3996. return optionalResult.set( this._x, this._y, this._z );
  3997. } else {
  3998. return new Vector3( this._x, this._y, this._z );
  3999. }
  4000. }
  4001. _onChange( callback ) {
  4002. this._onChangeCallback = callback;
  4003. return this;
  4004. }
  4005. _onChangeCallback() {}
  4006. }
  4007. Euler.prototype.isEuler = true;
  4008. Euler.DefaultOrder = 'XYZ';
  4009. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  4010. class Layers {
  4011. constructor() {
  4012. this.mask = 1 | 0;
  4013. }
  4014. set( channel ) {
  4015. this.mask = 1 << channel | 0;
  4016. }
  4017. enable( channel ) {
  4018. this.mask |= 1 << channel | 0;
  4019. }
  4020. enableAll() {
  4021. this.mask = 0xffffffff | 0;
  4022. }
  4023. toggle( channel ) {
  4024. this.mask ^= 1 << channel | 0;
  4025. }
  4026. disable( channel ) {
  4027. this.mask &= ~ ( 1 << channel | 0 );
  4028. }
  4029. disableAll() {
  4030. this.mask = 0;
  4031. }
  4032. test( layers ) {
  4033. return ( this.mask & layers.mask ) !== 0;
  4034. }
  4035. }
  4036. let _object3DId = 0;
  4037. const _v1$4 = /*@__PURE__*/ new Vector3();
  4038. const _q1 = /*@__PURE__*/ new Quaternion();
  4039. const _m1$1 = /*@__PURE__*/ new Matrix4();
  4040. const _target = /*@__PURE__*/ new Vector3();
  4041. const _position$3 = /*@__PURE__*/ new Vector3();
  4042. const _scale$2 = /*@__PURE__*/ new Vector3();
  4043. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  4044. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  4045. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4046. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  4047. const _addedEvent = { type: 'added' };
  4048. const _removedEvent = { type: 'removed' };
  4049. class Object3D extends EventDispatcher {
  4050. constructor() {
  4051. super();
  4052. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  4053. this.uuid = generateUUID();
  4054. this.name = '';
  4055. this.type = 'Object3D';
  4056. this.parent = null;
  4057. this.children = [];
  4058. this.up = Object3D.DefaultUp.clone();
  4059. const position = new Vector3();
  4060. const rotation = new Euler();
  4061. const quaternion = new Quaternion();
  4062. const scale = new Vector3( 1, 1, 1 );
  4063. function onRotationChange() {
  4064. quaternion.setFromEuler( rotation, false );
  4065. }
  4066. function onQuaternionChange() {
  4067. rotation.setFromQuaternion( quaternion, undefined, false );
  4068. }
  4069. rotation._onChange( onRotationChange );
  4070. quaternion._onChange( onQuaternionChange );
  4071. Object.defineProperties( this, {
  4072. position: {
  4073. configurable: true,
  4074. enumerable: true,
  4075. value: position
  4076. },
  4077. rotation: {
  4078. configurable: true,
  4079. enumerable: true,
  4080. value: rotation
  4081. },
  4082. quaternion: {
  4083. configurable: true,
  4084. enumerable: true,
  4085. value: quaternion
  4086. },
  4087. scale: {
  4088. configurable: true,
  4089. enumerable: true,
  4090. value: scale
  4091. },
  4092. modelViewMatrix: {
  4093. value: new Matrix4()
  4094. },
  4095. normalMatrix: {
  4096. value: new Matrix3()
  4097. }
  4098. } );
  4099. this.matrix = new Matrix4();
  4100. this.matrixWorld = new Matrix4();
  4101. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  4102. this.matrixWorldNeedsUpdate = false;
  4103. this.layers = new Layers();
  4104. this.visible = true;
  4105. this.castShadow = false;
  4106. this.receiveShadow = false;
  4107. this.frustumCulled = true;
  4108. this.renderOrder = 0;
  4109. this.animations = [];
  4110. this.userData = {};
  4111. }
  4112. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4113. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4114. applyMatrix4( matrix ) {
  4115. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4116. this.matrix.premultiply( matrix );
  4117. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4118. }
  4119. applyQuaternion( q ) {
  4120. this.quaternion.premultiply( q );
  4121. return this;
  4122. }
  4123. setRotationFromAxisAngle( axis, angle ) {
  4124. // assumes axis is normalized
  4125. this.quaternion.setFromAxisAngle( axis, angle );
  4126. }
  4127. setRotationFromEuler( euler ) {
  4128. this.quaternion.setFromEuler( euler, true );
  4129. }
  4130. setRotationFromMatrix( m ) {
  4131. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4132. this.quaternion.setFromRotationMatrix( m );
  4133. }
  4134. setRotationFromQuaternion( q ) {
  4135. // assumes q is normalized
  4136. this.quaternion.copy( q );
  4137. }
  4138. rotateOnAxis( axis, angle ) {
  4139. // rotate object on axis in object space
  4140. // axis is assumed to be normalized
  4141. _q1.setFromAxisAngle( axis, angle );
  4142. this.quaternion.multiply( _q1 );
  4143. return this;
  4144. }
  4145. rotateOnWorldAxis( axis, angle ) {
  4146. // rotate object on axis in world space
  4147. // axis is assumed to be normalized
  4148. // method assumes no rotated parent
  4149. _q1.setFromAxisAngle( axis, angle );
  4150. this.quaternion.premultiply( _q1 );
  4151. return this;
  4152. }
  4153. rotateX( angle ) {
  4154. return this.rotateOnAxis( _xAxis, angle );
  4155. }
  4156. rotateY( angle ) {
  4157. return this.rotateOnAxis( _yAxis, angle );
  4158. }
  4159. rotateZ( angle ) {
  4160. return this.rotateOnAxis( _zAxis, angle );
  4161. }
  4162. translateOnAxis( axis, distance ) {
  4163. // translate object by distance along axis in object space
  4164. // axis is assumed to be normalized
  4165. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  4166. this.position.add( _v1$4.multiplyScalar( distance ) );
  4167. return this;
  4168. }
  4169. translateX( distance ) {
  4170. return this.translateOnAxis( _xAxis, distance );
  4171. }
  4172. translateY( distance ) {
  4173. return this.translateOnAxis( _yAxis, distance );
  4174. }
  4175. translateZ( distance ) {
  4176. return this.translateOnAxis( _zAxis, distance );
  4177. }
  4178. localToWorld( vector ) {
  4179. return vector.applyMatrix4( this.matrixWorld );
  4180. }
  4181. worldToLocal( vector ) {
  4182. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  4183. }
  4184. lookAt( x, y, z ) {
  4185. // This method does not support objects having non-uniformly-scaled parent(s)
  4186. if ( x.isVector3 ) {
  4187. _target.copy( x );
  4188. } else {
  4189. _target.set( x, y, z );
  4190. }
  4191. const parent = this.parent;
  4192. this.updateWorldMatrix( true, false );
  4193. _position$3.setFromMatrixPosition( this.matrixWorld );
  4194. if ( this.isCamera || this.isLight ) {
  4195. _m1$1.lookAt( _position$3, _target, this.up );
  4196. } else {
  4197. _m1$1.lookAt( _target, _position$3, this.up );
  4198. }
  4199. this.quaternion.setFromRotationMatrix( _m1$1 );
  4200. if ( parent ) {
  4201. _m1$1.extractRotation( parent.matrixWorld );
  4202. _q1.setFromRotationMatrix( _m1$1 );
  4203. this.quaternion.premultiply( _q1.invert() );
  4204. }
  4205. }
  4206. add( object ) {
  4207. if ( arguments.length > 1 ) {
  4208. for ( let i = 0; i < arguments.length; i ++ ) {
  4209. this.add( arguments[ i ] );
  4210. }
  4211. return this;
  4212. }
  4213. if ( object === this ) {
  4214. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4215. return this;
  4216. }
  4217. if ( object && object.isObject3D ) {
  4218. if ( object.parent !== null ) {
  4219. object.parent.remove( object );
  4220. }
  4221. object.parent = this;
  4222. this.children.push( object );
  4223. object.dispatchEvent( _addedEvent );
  4224. } else {
  4225. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4226. }
  4227. return this;
  4228. }
  4229. remove( object ) {
  4230. if ( arguments.length > 1 ) {
  4231. for ( let i = 0; i < arguments.length; i ++ ) {
  4232. this.remove( arguments[ i ] );
  4233. }
  4234. return this;
  4235. }
  4236. const index = this.children.indexOf( object );
  4237. if ( index !== - 1 ) {
  4238. object.parent = null;
  4239. this.children.splice( index, 1 );
  4240. object.dispatchEvent( _removedEvent );
  4241. }
  4242. return this;
  4243. }
  4244. removeFromParent() {
  4245. const parent = this.parent;
  4246. if ( parent !== null ) {
  4247. parent.remove( this );
  4248. }
  4249. return this;
  4250. }
  4251. clear() {
  4252. for ( let i = 0; i < this.children.length; i ++ ) {
  4253. const object = this.children[ i ];
  4254. object.parent = null;
  4255. object.dispatchEvent( _removedEvent );
  4256. }
  4257. this.children.length = 0;
  4258. return this;
  4259. }
  4260. attach( object ) {
  4261. // adds object as a child of this, while maintaining the object's world transform
  4262. this.updateWorldMatrix( true, false );
  4263. _m1$1.copy( this.matrixWorld ).invert();
  4264. if ( object.parent !== null ) {
  4265. object.parent.updateWorldMatrix( true, false );
  4266. _m1$1.multiply( object.parent.matrixWorld );
  4267. }
  4268. object.applyMatrix4( _m1$1 );
  4269. this.add( object );
  4270. object.updateWorldMatrix( false, true );
  4271. return this;
  4272. }
  4273. getObjectById( id ) {
  4274. return this.getObjectByProperty( 'id', id );
  4275. }
  4276. getObjectByName( name ) {
  4277. return this.getObjectByProperty( 'name', name );
  4278. }
  4279. getObjectByProperty( name, value ) {
  4280. if ( this[ name ] === value ) return this;
  4281. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4282. const child = this.children[ i ];
  4283. const object = child.getObjectByProperty( name, value );
  4284. if ( object !== undefined ) {
  4285. return object;
  4286. }
  4287. }
  4288. return undefined;
  4289. }
  4290. getWorldPosition( target ) {
  4291. this.updateWorldMatrix( true, false );
  4292. return target.setFromMatrixPosition( this.matrixWorld );
  4293. }
  4294. getWorldQuaternion( target ) {
  4295. this.updateWorldMatrix( true, false );
  4296. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  4297. return target;
  4298. }
  4299. getWorldScale( target ) {
  4300. this.updateWorldMatrix( true, false );
  4301. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  4302. return target;
  4303. }
  4304. getWorldDirection( target ) {
  4305. this.updateWorldMatrix( true, false );
  4306. const e = this.matrixWorld.elements;
  4307. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4308. }
  4309. raycast() {}
  4310. traverse( callback ) {
  4311. callback( this );
  4312. const children = this.children;
  4313. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4314. children[ i ].traverse( callback );
  4315. }
  4316. }
  4317. traverseVisible( callback ) {
  4318. if ( this.visible === false ) return;
  4319. callback( this );
  4320. const children = this.children;
  4321. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4322. children[ i ].traverseVisible( callback );
  4323. }
  4324. }
  4325. traverseAncestors( callback ) {
  4326. const parent = this.parent;
  4327. if ( parent !== null ) {
  4328. callback( parent );
  4329. parent.traverseAncestors( callback );
  4330. }
  4331. }
  4332. updateMatrix() {
  4333. this.matrix.compose( this.position, this.quaternion, this.scale );
  4334. this.matrixWorldNeedsUpdate = true;
  4335. }
  4336. updateMatrixWorld( force ) {
  4337. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4338. if ( this.matrixWorldNeedsUpdate || force ) {
  4339. if ( this.parent === null ) {
  4340. this.matrixWorld.copy( this.matrix );
  4341. } else {
  4342. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4343. }
  4344. this.matrixWorldNeedsUpdate = false;
  4345. force = true;
  4346. }
  4347. // update children
  4348. const children = this.children;
  4349. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4350. children[ i ].updateMatrixWorld( force );
  4351. }
  4352. }
  4353. updateWorldMatrix( updateParents, updateChildren ) {
  4354. const parent = this.parent;
  4355. if ( updateParents === true && parent !== null ) {
  4356. parent.updateWorldMatrix( true, false );
  4357. }
  4358. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4359. if ( this.parent === null ) {
  4360. this.matrixWorld.copy( this.matrix );
  4361. } else {
  4362. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4363. }
  4364. // update children
  4365. if ( updateChildren === true ) {
  4366. const children = this.children;
  4367. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4368. children[ i ].updateWorldMatrix( false, true );
  4369. }
  4370. }
  4371. }
  4372. toJSON( meta ) {
  4373. // meta is a string when called from JSON.stringify
  4374. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4375. const output = {};
  4376. // meta is a hash used to collect geometries, materials.
  4377. // not providing it implies that this is the root object
  4378. // being serialized.
  4379. if ( isRootObject ) {
  4380. // initialize meta obj
  4381. meta = {
  4382. geometries: {},
  4383. materials: {},
  4384. textures: {},
  4385. images: {},
  4386. shapes: {},
  4387. skeletons: {},
  4388. animations: {}
  4389. };
  4390. output.metadata = {
  4391. version: 4.5,
  4392. type: 'Object',
  4393. generator: 'Object3D.toJSON'
  4394. };
  4395. }
  4396. // standard Object3D serialization
  4397. const object = {};
  4398. object.uuid = this.uuid;
  4399. object.type = this.type;
  4400. if ( this.name !== '' ) object.name = this.name;
  4401. if ( this.castShadow === true ) object.castShadow = true;
  4402. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4403. if ( this.visible === false ) object.visible = false;
  4404. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4405. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4406. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  4407. object.layers = this.layers.mask;
  4408. object.matrix = this.matrix.toArray();
  4409. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4410. // object specific properties
  4411. if ( this.isInstancedMesh ) {
  4412. object.type = 'InstancedMesh';
  4413. object.count = this.count;
  4414. object.instanceMatrix = this.instanceMatrix.toJSON();
  4415. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  4416. }
  4417. //
  4418. function serialize( library, element ) {
  4419. if ( library[ element.uuid ] === undefined ) {
  4420. library[ element.uuid ] = element.toJSON( meta );
  4421. }
  4422. return element.uuid;
  4423. }
  4424. if ( this.isScene ) {
  4425. if ( this.background ) {
  4426. if ( this.background.isColor ) {
  4427. object.background = this.background.toJSON();
  4428. } else if ( this.background.isTexture ) {
  4429. object.background = this.background.toJSON( meta ).uuid;
  4430. }
  4431. }
  4432. if ( this.environment && this.environment.isTexture ) {
  4433. object.environment = this.environment.toJSON( meta ).uuid;
  4434. }
  4435. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  4436. object.geometry = serialize( meta.geometries, this.geometry );
  4437. const parameters = this.geometry.parameters;
  4438. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4439. const shapes = parameters.shapes;
  4440. if ( Array.isArray( shapes ) ) {
  4441. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4442. const shape = shapes[ i ];
  4443. serialize( meta.shapes, shape );
  4444. }
  4445. } else {
  4446. serialize( meta.shapes, shapes );
  4447. }
  4448. }
  4449. }
  4450. if ( this.isSkinnedMesh ) {
  4451. object.bindMode = this.bindMode;
  4452. object.bindMatrix = this.bindMatrix.toArray();
  4453. if ( this.skeleton !== undefined ) {
  4454. serialize( meta.skeletons, this.skeleton );
  4455. object.skeleton = this.skeleton.uuid;
  4456. }
  4457. }
  4458. if ( this.material !== undefined ) {
  4459. if ( Array.isArray( this.material ) ) {
  4460. const uuids = [];
  4461. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4462. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4463. }
  4464. object.material = uuids;
  4465. } else {
  4466. object.material = serialize( meta.materials, this.material );
  4467. }
  4468. }
  4469. //
  4470. if ( this.children.length > 0 ) {
  4471. object.children = [];
  4472. for ( let i = 0; i < this.children.length; i ++ ) {
  4473. object.children.push( this.children[ i ].toJSON( meta ).object );
  4474. }
  4475. }
  4476. //
  4477. if ( this.animations.length > 0 ) {
  4478. object.animations = [];
  4479. for ( let i = 0; i < this.animations.length; i ++ ) {
  4480. const animation = this.animations[ i ];
  4481. object.animations.push( serialize( meta.animations, animation ) );
  4482. }
  4483. }
  4484. if ( isRootObject ) {
  4485. const geometries = extractFromCache( meta.geometries );
  4486. const materials = extractFromCache( meta.materials );
  4487. const textures = extractFromCache( meta.textures );
  4488. const images = extractFromCache( meta.images );
  4489. const shapes = extractFromCache( meta.shapes );
  4490. const skeletons = extractFromCache( meta.skeletons );
  4491. const animations = extractFromCache( meta.animations );
  4492. if ( geometries.length > 0 ) output.geometries = geometries;
  4493. if ( materials.length > 0 ) output.materials = materials;
  4494. if ( textures.length > 0 ) output.textures = textures;
  4495. if ( images.length > 0 ) output.images = images;
  4496. if ( shapes.length > 0 ) output.shapes = shapes;
  4497. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4498. if ( animations.length > 0 ) output.animations = animations;
  4499. }
  4500. output.object = object;
  4501. return output;
  4502. // extract data from the cache hash
  4503. // remove metadata on each item
  4504. // and return as array
  4505. function extractFromCache( cache ) {
  4506. const values = [];
  4507. for ( const key in cache ) {
  4508. const data = cache[ key ];
  4509. delete data.metadata;
  4510. values.push( data );
  4511. }
  4512. return values;
  4513. }
  4514. }
  4515. clone( recursive ) {
  4516. return new this.constructor().copy( this, recursive );
  4517. }
  4518. copy( source, recursive = true ) {
  4519. this.name = source.name;
  4520. this.up.copy( source.up );
  4521. this.position.copy( source.position );
  4522. this.rotation.order = source.rotation.order;
  4523. this.quaternion.copy( source.quaternion );
  4524. this.scale.copy( source.scale );
  4525. this.matrix.copy( source.matrix );
  4526. this.matrixWorld.copy( source.matrixWorld );
  4527. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4528. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4529. this.layers.mask = source.layers.mask;
  4530. this.visible = source.visible;
  4531. this.castShadow = source.castShadow;
  4532. this.receiveShadow = source.receiveShadow;
  4533. this.frustumCulled = source.frustumCulled;
  4534. this.renderOrder = source.renderOrder;
  4535. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4536. if ( recursive === true ) {
  4537. for ( let i = 0; i < source.children.length; i ++ ) {
  4538. const child = source.children[ i ];
  4539. this.add( child.clone() );
  4540. }
  4541. }
  4542. return this;
  4543. }
  4544. }
  4545. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  4546. Object3D.DefaultMatrixAutoUpdate = true;
  4547. Object3D.prototype.isObject3D = true;
  4548. const _v0$1 = /*@__PURE__*/ new Vector3();
  4549. const _v1$3 = /*@__PURE__*/ new Vector3();
  4550. const _v2$2 = /*@__PURE__*/ new Vector3();
  4551. const _v3$1 = /*@__PURE__*/ new Vector3();
  4552. const _vab = /*@__PURE__*/ new Vector3();
  4553. const _vac = /*@__PURE__*/ new Vector3();
  4554. const _vbc = /*@__PURE__*/ new Vector3();
  4555. const _vap = /*@__PURE__*/ new Vector3();
  4556. const _vbp = /*@__PURE__*/ new Vector3();
  4557. const _vcp = /*@__PURE__*/ new Vector3();
  4558. class Triangle {
  4559. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  4560. this.a = a;
  4561. this.b = b;
  4562. this.c = c;
  4563. }
  4564. static getNormal( a, b, c, target ) {
  4565. target.subVectors( c, b );
  4566. _v0$1.subVectors( a, b );
  4567. target.cross( _v0$1 );
  4568. const targetLengthSq = target.lengthSq();
  4569. if ( targetLengthSq > 0 ) {
  4570. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  4571. }
  4572. return target.set( 0, 0, 0 );
  4573. }
  4574. // static/instance method to calculate barycentric coordinates
  4575. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4576. static getBarycoord( point, a, b, c, target ) {
  4577. _v0$1.subVectors( c, a );
  4578. _v1$3.subVectors( b, a );
  4579. _v2$2.subVectors( point, a );
  4580. const dot00 = _v0$1.dot( _v0$1 );
  4581. const dot01 = _v0$1.dot( _v1$3 );
  4582. const dot02 = _v0$1.dot( _v2$2 );
  4583. const dot11 = _v1$3.dot( _v1$3 );
  4584. const dot12 = _v1$3.dot( _v2$2 );
  4585. const denom = ( dot00 * dot11 - dot01 * dot01 );
  4586. // collinear or singular triangle
  4587. if ( denom === 0 ) {
  4588. // arbitrary location outside of triangle?
  4589. // not sure if this is the best idea, maybe should be returning undefined
  4590. return target.set( - 2, - 1, - 1 );
  4591. }
  4592. const invDenom = 1 / denom;
  4593. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4594. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4595. // barycentric coordinates must always sum to 1
  4596. return target.set( 1 - u - v, v, u );
  4597. }
  4598. static containsPoint( point, a, b, c ) {
  4599. this.getBarycoord( point, a, b, c, _v3$1 );
  4600. return ( _v3$1.x >= 0 ) && ( _v3$1.y >= 0 ) && ( ( _v3$1.x + _v3$1.y ) <= 1 );
  4601. }
  4602. static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) {
  4603. this.getBarycoord( point, p1, p2, p3, _v3$1 );
  4604. target.set( 0, 0 );
  4605. target.addScaledVector( uv1, _v3$1.x );
  4606. target.addScaledVector( uv2, _v3$1.y );
  4607. target.addScaledVector( uv3, _v3$1.z );
  4608. return target;
  4609. }
  4610. static isFrontFacing( a, b, c, direction ) {
  4611. _v0$1.subVectors( c, b );
  4612. _v1$3.subVectors( a, b );
  4613. // strictly front facing
  4614. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  4615. }
  4616. set( a, b, c ) {
  4617. this.a.copy( a );
  4618. this.b.copy( b );
  4619. this.c.copy( c );
  4620. return this;
  4621. }
  4622. setFromPointsAndIndices( points, i0, i1, i2 ) {
  4623. this.a.copy( points[ i0 ] );
  4624. this.b.copy( points[ i1 ] );
  4625. this.c.copy( points[ i2 ] );
  4626. return this;
  4627. }
  4628. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  4629. this.a.fromBufferAttribute( attribute, i0 );
  4630. this.b.fromBufferAttribute( attribute, i1 );
  4631. this.c.fromBufferAttribute( attribute, i2 );
  4632. return this;
  4633. }
  4634. clone() {
  4635. return new this.constructor().copy( this );
  4636. }
  4637. copy( triangle ) {
  4638. this.a.copy( triangle.a );
  4639. this.b.copy( triangle.b );
  4640. this.c.copy( triangle.c );
  4641. return this;
  4642. }
  4643. getArea() {
  4644. _v0$1.subVectors( this.c, this.b );
  4645. _v1$3.subVectors( this.a, this.b );
  4646. return _v0$1.cross( _v1$3 ).length() * 0.5;
  4647. }
  4648. getMidpoint( target ) {
  4649. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4650. }
  4651. getNormal( target ) {
  4652. return Triangle.getNormal( this.a, this.b, this.c, target );
  4653. }
  4654. getPlane( target ) {
  4655. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  4656. }
  4657. getBarycoord( point, target ) {
  4658. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  4659. }
  4660. getUV( point, uv1, uv2, uv3, target ) {
  4661. return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target );
  4662. }
  4663. containsPoint( point ) {
  4664. return Triangle.containsPoint( point, this.a, this.b, this.c );
  4665. }
  4666. isFrontFacing( direction ) {
  4667. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  4668. }
  4669. intersectsBox( box ) {
  4670. return box.intersectsTriangle( this );
  4671. }
  4672. closestPointToPoint( p, target ) {
  4673. const a = this.a, b = this.b, c = this.c;
  4674. let v, w;
  4675. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  4676. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  4677. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  4678. // basically, we're distinguishing which of the voronoi regions of the triangle
  4679. // the point lies in with the minimum amount of redundant computation.
  4680. _vab.subVectors( b, a );
  4681. _vac.subVectors( c, a );
  4682. _vap.subVectors( p, a );
  4683. const d1 = _vab.dot( _vap );
  4684. const d2 = _vac.dot( _vap );
  4685. if ( d1 <= 0 && d2 <= 0 ) {
  4686. // vertex region of A; barycentric coords (1, 0, 0)
  4687. return target.copy( a );
  4688. }
  4689. _vbp.subVectors( p, b );
  4690. const d3 = _vab.dot( _vbp );
  4691. const d4 = _vac.dot( _vbp );
  4692. if ( d3 >= 0 && d4 <= d3 ) {
  4693. // vertex region of B; barycentric coords (0, 1, 0)
  4694. return target.copy( b );
  4695. }
  4696. const vc = d1 * d4 - d3 * d2;
  4697. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  4698. v = d1 / ( d1 - d3 );
  4699. // edge region of AB; barycentric coords (1-v, v, 0)
  4700. return target.copy( a ).addScaledVector( _vab, v );
  4701. }
  4702. _vcp.subVectors( p, c );
  4703. const d5 = _vab.dot( _vcp );
  4704. const d6 = _vac.dot( _vcp );
  4705. if ( d6 >= 0 && d5 <= d6 ) {
  4706. // vertex region of C; barycentric coords (0, 0, 1)
  4707. return target.copy( c );
  4708. }
  4709. const vb = d5 * d2 - d1 * d6;
  4710. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  4711. w = d2 / ( d2 - d6 );
  4712. // edge region of AC; barycentric coords (1-w, 0, w)
  4713. return target.copy( a ).addScaledVector( _vac, w );
  4714. }
  4715. const va = d3 * d6 - d5 * d4;
  4716. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  4717. _vbc.subVectors( c, b );
  4718. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  4719. // edge region of BC; barycentric coords (0, 1-w, w)
  4720. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  4721. }
  4722. // face region
  4723. const denom = 1 / ( va + vb + vc );
  4724. // u = va * denom
  4725. v = vb * denom;
  4726. w = vc * denom;
  4727. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  4728. }
  4729. equals( triangle ) {
  4730. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  4731. }
  4732. }
  4733. let materialId = 0;
  4734. class Material extends EventDispatcher {
  4735. constructor() {
  4736. super();
  4737. Object.defineProperty( this, 'id', { value: materialId ++ } );
  4738. this.uuid = generateUUID();
  4739. this.name = '';
  4740. this.type = 'Material';
  4741. this.fog = true;
  4742. this.blending = NormalBlending;
  4743. this.side = FrontSide;
  4744. this.vertexColors = false;
  4745. this.opacity = 1;
  4746. this.format = RGBAFormat;
  4747. this.transparent = false;
  4748. this.blendSrc = SrcAlphaFactor;
  4749. this.blendDst = OneMinusSrcAlphaFactor;
  4750. this.blendEquation = AddEquation;
  4751. this.blendSrcAlpha = null;
  4752. this.blendDstAlpha = null;
  4753. this.blendEquationAlpha = null;
  4754. this.depthFunc = LessEqualDepth;
  4755. this.depthTest = true;
  4756. this.depthWrite = true;
  4757. this.stencilWriteMask = 0xff;
  4758. this.stencilFunc = AlwaysStencilFunc;
  4759. this.stencilRef = 0;
  4760. this.stencilFuncMask = 0xff;
  4761. this.stencilFail = KeepStencilOp;
  4762. this.stencilZFail = KeepStencilOp;
  4763. this.stencilZPass = KeepStencilOp;
  4764. this.stencilWrite = false;
  4765. this.clippingPlanes = null;
  4766. this.clipIntersection = false;
  4767. this.clipShadows = false;
  4768. this.shadowSide = null;
  4769. this.colorWrite = true;
  4770. this.precision = null; // override the renderer's default precision for this material
  4771. this.polygonOffset = false;
  4772. this.polygonOffsetFactor = 0;
  4773. this.polygonOffsetUnits = 0;
  4774. this.dithering = false;
  4775. this.alphaToCoverage = false;
  4776. this.premultipliedAlpha = false;
  4777. this.visible = true;
  4778. this.toneMapped = true;
  4779. this.userData = {};
  4780. this.version = 0;
  4781. this._alphaTest = 0;
  4782. }
  4783. get alphaTest() {
  4784. return this._alphaTest;
  4785. }
  4786. set alphaTest( value ) {
  4787. if ( this._alphaTest > 0 !== value > 0 ) {
  4788. this.version ++;
  4789. }
  4790. this._alphaTest = value;
  4791. }
  4792. onBuild( /* shaderobject, renderer */ ) {}
  4793. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  4794. onBeforeCompile( /* shaderobject, renderer */ ) {}
  4795. customProgramCacheKey() {
  4796. return this.onBeforeCompile.toString();
  4797. }
  4798. setValues( values ) {
  4799. if ( values === undefined ) return;
  4800. for ( const key in values ) {
  4801. const newValue = values[ key ];
  4802. if ( newValue === undefined ) {
  4803. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  4804. continue;
  4805. }
  4806. // for backward compatability if shading is set in the constructor
  4807. if ( key === 'shading' ) {
  4808. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  4809. this.flatShading = ( newValue === FlatShading ) ? true : false;
  4810. continue;
  4811. }
  4812. const currentValue = this[ key ];
  4813. if ( currentValue === undefined ) {
  4814. console.warn( 'THREE.' + this.type + ': \'' + key + '\' is not a property of this material.' );
  4815. continue;
  4816. }
  4817. if ( currentValue && currentValue.isColor ) {
  4818. currentValue.set( newValue );
  4819. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  4820. currentValue.copy( newValue );
  4821. } else {
  4822. this[ key ] = newValue;
  4823. }
  4824. }
  4825. }
  4826. toJSON( meta ) {
  4827. const isRoot = ( meta === undefined || typeof meta === 'string' );
  4828. if ( isRoot ) {
  4829. meta = {
  4830. textures: {},
  4831. images: {}
  4832. };
  4833. }
  4834. const data = {
  4835. metadata: {
  4836. version: 4.5,
  4837. type: 'Material',
  4838. generator: 'Material.toJSON'
  4839. }
  4840. };
  4841. // standard Material serialization
  4842. data.uuid = this.uuid;
  4843. data.type = this.type;
  4844. if ( this.name !== '' ) data.name = this.name;
  4845. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  4846. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  4847. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  4848. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  4849. if ( this.sheenTint && this.sheenTint.isColor ) data.sheenTint = this.sheenTint.getHex();
  4850. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  4851. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  4852. if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  4853. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  4854. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  4855. if ( this.specularTint && this.specularTint.isColor ) data.specularTint = this.specularTint.getHex();
  4856. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  4857. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  4858. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  4859. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  4860. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  4861. }
  4862. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  4863. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  4864. }
  4865. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  4866. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  4867. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  4868. }
  4869. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  4870. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  4871. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  4872. if ( this.lightMap && this.lightMap.isTexture ) {
  4873. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  4874. data.lightMapIntensity = this.lightMapIntensity;
  4875. }
  4876. if ( this.aoMap && this.aoMap.isTexture ) {
  4877. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  4878. data.aoMapIntensity = this.aoMapIntensity;
  4879. }
  4880. if ( this.bumpMap && this.bumpMap.isTexture ) {
  4881. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  4882. data.bumpScale = this.bumpScale;
  4883. }
  4884. if ( this.normalMap && this.normalMap.isTexture ) {
  4885. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  4886. data.normalMapType = this.normalMapType;
  4887. data.normalScale = this.normalScale.toArray();
  4888. }
  4889. if ( this.displacementMap && this.displacementMap.isTexture ) {
  4890. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  4891. data.displacementScale = this.displacementScale;
  4892. data.displacementBias = this.displacementBias;
  4893. }
  4894. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  4895. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  4896. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  4897. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  4898. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  4899. if ( this.specularTintMap && this.specularTintMap.isTexture ) data.specularTintMap = this.specularTintMap.toJSON( meta ).uuid;
  4900. if ( this.envMap && this.envMap.isTexture ) {
  4901. data.envMap = this.envMap.toJSON( meta ).uuid;
  4902. if ( this.combine !== undefined ) data.combine = this.combine;
  4903. }
  4904. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  4905. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  4906. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  4907. if ( this.gradientMap && this.gradientMap.isTexture ) {
  4908. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  4909. }
  4910. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  4911. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  4912. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  4913. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  4914. if ( this.attenuationDistance !== undefined ) data.attenuationDistance = this.attenuationDistance;
  4915. if ( this.attenuationTint !== undefined ) data.attenuationTint = this.attenuationTint.getHex();
  4916. if ( this.size !== undefined ) data.size = this.size;
  4917. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  4918. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  4919. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  4920. if ( this.side !== FrontSide ) data.side = this.side;
  4921. if ( this.vertexColors ) data.vertexColors = true;
  4922. if ( this.opacity < 1 ) data.opacity = this.opacity;
  4923. if ( this.format !== RGBAFormat ) data.format = this.format;
  4924. if ( this.transparent === true ) data.transparent = this.transparent;
  4925. data.depthFunc = this.depthFunc;
  4926. data.depthTest = this.depthTest;
  4927. data.depthWrite = this.depthWrite;
  4928. data.colorWrite = this.colorWrite;
  4929. data.stencilWrite = this.stencilWrite;
  4930. data.stencilWriteMask = this.stencilWriteMask;
  4931. data.stencilFunc = this.stencilFunc;
  4932. data.stencilRef = this.stencilRef;
  4933. data.stencilFuncMask = this.stencilFuncMask;
  4934. data.stencilFail = this.stencilFail;
  4935. data.stencilZFail = this.stencilZFail;
  4936. data.stencilZPass = this.stencilZPass;
  4937. // rotation (SpriteMaterial)
  4938. if ( this.rotation && this.rotation !== 0 ) data.rotation = this.rotation;
  4939. if ( this.polygonOffset === true ) data.polygonOffset = true;
  4940. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  4941. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  4942. if ( this.linewidth && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  4943. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  4944. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  4945. if ( this.scale !== undefined ) data.scale = this.scale;
  4946. if ( this.dithering === true ) data.dithering = true;
  4947. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  4948. if ( this.alphaToCoverage === true ) data.alphaToCoverage = this.alphaToCoverage;
  4949. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  4950. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  4951. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  4952. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  4953. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  4954. if ( this.flatShading === true ) data.flatShading = this.flatShading;
  4955. if ( this.visible === false ) data.visible = false;
  4956. if ( this.toneMapped === false ) data.toneMapped = false;
  4957. if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData;
  4958. // TODO: Copied from Object3D.toJSON
  4959. function extractFromCache( cache ) {
  4960. const values = [];
  4961. for ( const key in cache ) {
  4962. const data = cache[ key ];
  4963. delete data.metadata;
  4964. values.push( data );
  4965. }
  4966. return values;
  4967. }
  4968. if ( isRoot ) {
  4969. const textures = extractFromCache( meta.textures );
  4970. const images = extractFromCache( meta.images );
  4971. if ( textures.length > 0 ) data.textures = textures;
  4972. if ( images.length > 0 ) data.images = images;
  4973. }
  4974. return data;
  4975. }
  4976. clone() {
  4977. return new this.constructor().copy( this );
  4978. }
  4979. copy( source ) {
  4980. this.name = source.name;
  4981. this.fog = source.fog;
  4982. this.blending = source.blending;
  4983. this.side = source.side;
  4984. this.vertexColors = source.vertexColors;
  4985. this.opacity = source.opacity;
  4986. this.format = source.format;
  4987. this.transparent = source.transparent;
  4988. this.blendSrc = source.blendSrc;
  4989. this.blendDst = source.blendDst;
  4990. this.blendEquation = source.blendEquation;
  4991. this.blendSrcAlpha = source.blendSrcAlpha;
  4992. this.blendDstAlpha = source.blendDstAlpha;
  4993. this.blendEquationAlpha = source.blendEquationAlpha;
  4994. this.depthFunc = source.depthFunc;
  4995. this.depthTest = source.depthTest;
  4996. this.depthWrite = source.depthWrite;
  4997. this.stencilWriteMask = source.stencilWriteMask;
  4998. this.stencilFunc = source.stencilFunc;
  4999. this.stencilRef = source.stencilRef;
  5000. this.stencilFuncMask = source.stencilFuncMask;
  5001. this.stencilFail = source.stencilFail;
  5002. this.stencilZFail = source.stencilZFail;
  5003. this.stencilZPass = source.stencilZPass;
  5004. this.stencilWrite = source.stencilWrite;
  5005. const srcPlanes = source.clippingPlanes;
  5006. let dstPlanes = null;
  5007. if ( srcPlanes !== null ) {
  5008. const n = srcPlanes.length;
  5009. dstPlanes = new Array( n );
  5010. for ( let i = 0; i !== n; ++ i ) {
  5011. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5012. }
  5013. }
  5014. this.clippingPlanes = dstPlanes;
  5015. this.clipIntersection = source.clipIntersection;
  5016. this.clipShadows = source.clipShadows;
  5017. this.shadowSide = source.shadowSide;
  5018. this.colorWrite = source.colorWrite;
  5019. this.precision = source.precision;
  5020. this.polygonOffset = source.polygonOffset;
  5021. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5022. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5023. this.dithering = source.dithering;
  5024. this.alphaTest = source.alphaTest;
  5025. this.alphaToCoverage = source.alphaToCoverage;
  5026. this.premultipliedAlpha = source.premultipliedAlpha;
  5027. this.visible = source.visible;
  5028. this.toneMapped = source.toneMapped;
  5029. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5030. return this;
  5031. }
  5032. dispose() {
  5033. this.dispatchEvent( { type: 'dispose' } );
  5034. }
  5035. set needsUpdate( value ) {
  5036. if ( value === true ) this.version ++;
  5037. }
  5038. }
  5039. Material.prototype.isMaterial = true;
  5040. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  5041. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  5042. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  5043. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  5044. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  5045. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  5046. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  5047. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  5048. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  5049. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  5050. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  5051. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  5052. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  5053. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  5054. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  5055. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  5056. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  5057. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  5058. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  5059. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  5060. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  5061. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  5062. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  5063. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  5064. const _hslA = { h: 0, s: 0, l: 0 };
  5065. const _hslB = { h: 0, s: 0, l: 0 };
  5066. function hue2rgb( p, q, t ) {
  5067. if ( t < 0 ) t += 1;
  5068. if ( t > 1 ) t -= 1;
  5069. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  5070. if ( t < 1 / 2 ) return q;
  5071. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  5072. return p;
  5073. }
  5074. function SRGBToLinear( c ) {
  5075. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  5076. }
  5077. function LinearToSRGB( c ) {
  5078. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  5079. }
  5080. class Color {
  5081. constructor( r, g, b ) {
  5082. if ( g === undefined && b === undefined ) {
  5083. // r is THREE.Color, hex or string
  5084. return this.set( r );
  5085. }
  5086. return this.setRGB( r, g, b );
  5087. }
  5088. set( value ) {
  5089. if ( value && value.isColor ) {
  5090. this.copy( value );
  5091. } else if ( typeof value === 'number' ) {
  5092. this.setHex( value );
  5093. } else if ( typeof value === 'string' ) {
  5094. this.setStyle( value );
  5095. }
  5096. return this;
  5097. }
  5098. setScalar( scalar ) {
  5099. this.r = scalar;
  5100. this.g = scalar;
  5101. this.b = scalar;
  5102. return this;
  5103. }
  5104. setHex( hex ) {
  5105. hex = Math.floor( hex );
  5106. this.r = ( hex >> 16 & 255 ) / 255;
  5107. this.g = ( hex >> 8 & 255 ) / 255;
  5108. this.b = ( hex & 255 ) / 255;
  5109. return this;
  5110. }
  5111. setRGB( r, g, b ) {
  5112. this.r = r;
  5113. this.g = g;
  5114. this.b = b;
  5115. return this;
  5116. }
  5117. setHSL( h, s, l ) {
  5118. // h,s,l ranges are in 0.0 - 1.0
  5119. h = euclideanModulo( h, 1 );
  5120. s = clamp( s, 0, 1 );
  5121. l = clamp( l, 0, 1 );
  5122. if ( s === 0 ) {
  5123. this.r = this.g = this.b = l;
  5124. } else {
  5125. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  5126. const q = ( 2 * l ) - p;
  5127. this.r = hue2rgb( q, p, h + 1 / 3 );
  5128. this.g = hue2rgb( q, p, h );
  5129. this.b = hue2rgb( q, p, h - 1 / 3 );
  5130. }
  5131. return this;
  5132. }
  5133. setStyle( style ) {
  5134. function handleAlpha( string ) {
  5135. if ( string === undefined ) return;
  5136. if ( parseFloat( string ) < 1 ) {
  5137. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  5138. }
  5139. }
  5140. let m;
  5141. if ( m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec( style ) ) {
  5142. // rgb / hsl
  5143. let color;
  5144. const name = m[ 1 ];
  5145. const components = m[ 2 ];
  5146. switch ( name ) {
  5147. case 'rgb':
  5148. case 'rgba':
  5149. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5150. // rgb(255,0,0) rgba(255,0,0,0.5)
  5151. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  5152. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  5153. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  5154. handleAlpha( color[ 4 ] );
  5155. return this;
  5156. }
  5157. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5158. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5159. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  5160. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  5161. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  5162. handleAlpha( color[ 4 ] );
  5163. return this;
  5164. }
  5165. break;
  5166. case 'hsl':
  5167. case 'hsla':
  5168. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5169. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5170. const h = parseFloat( color[ 1 ] ) / 360;
  5171. const s = parseInt( color[ 2 ], 10 ) / 100;
  5172. const l = parseInt( color[ 3 ], 10 ) / 100;
  5173. handleAlpha( color[ 4 ] );
  5174. return this.setHSL( h, s, l );
  5175. }
  5176. break;
  5177. }
  5178. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  5179. // hex color
  5180. const hex = m[ 1 ];
  5181. const size = hex.length;
  5182. if ( size === 3 ) {
  5183. // #ff0
  5184. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  5185. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  5186. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  5187. return this;
  5188. } else if ( size === 6 ) {
  5189. // #ff0000
  5190. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  5191. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  5192. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  5193. return this;
  5194. }
  5195. }
  5196. if ( style && style.length > 0 ) {
  5197. return this.setColorName( style );
  5198. }
  5199. return this;
  5200. }
  5201. setColorName( style ) {
  5202. // color keywords
  5203. const hex = _colorKeywords[ style.toLowerCase() ];
  5204. if ( hex !== undefined ) {
  5205. // red
  5206. this.setHex( hex );
  5207. } else {
  5208. // unknown color
  5209. console.warn( 'THREE.Color: Unknown color ' + style );
  5210. }
  5211. return this;
  5212. }
  5213. clone() {
  5214. return new this.constructor( this.r, this.g, this.b );
  5215. }
  5216. copy( color ) {
  5217. this.r = color.r;
  5218. this.g = color.g;
  5219. this.b = color.b;
  5220. return this;
  5221. }
  5222. copyGammaToLinear( color, gammaFactor = 2.0 ) {
  5223. this.r = Math.pow( color.r, gammaFactor );
  5224. this.g = Math.pow( color.g, gammaFactor );
  5225. this.b = Math.pow( color.b, gammaFactor );
  5226. return this;
  5227. }
  5228. copyLinearToGamma( color, gammaFactor = 2.0 ) {
  5229. const safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  5230. this.r = Math.pow( color.r, safeInverse );
  5231. this.g = Math.pow( color.g, safeInverse );
  5232. this.b = Math.pow( color.b, safeInverse );
  5233. return this;
  5234. }
  5235. convertGammaToLinear( gammaFactor ) {
  5236. this.copyGammaToLinear( this, gammaFactor );
  5237. return this;
  5238. }
  5239. convertLinearToGamma( gammaFactor ) {
  5240. this.copyLinearToGamma( this, gammaFactor );
  5241. return this;
  5242. }
  5243. copySRGBToLinear( color ) {
  5244. this.r = SRGBToLinear( color.r );
  5245. this.g = SRGBToLinear( color.g );
  5246. this.b = SRGBToLinear( color.b );
  5247. return this;
  5248. }
  5249. copyLinearToSRGB( color ) {
  5250. this.r = LinearToSRGB( color.r );
  5251. this.g = LinearToSRGB( color.g );
  5252. this.b = LinearToSRGB( color.b );
  5253. return this;
  5254. }
  5255. convertSRGBToLinear() {
  5256. this.copySRGBToLinear( this );
  5257. return this;
  5258. }
  5259. convertLinearToSRGB() {
  5260. this.copyLinearToSRGB( this );
  5261. return this;
  5262. }
  5263. getHex() {
  5264. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  5265. }
  5266. getHexString() {
  5267. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  5268. }
  5269. getHSL( target ) {
  5270. // h,s,l ranges are in 0.0 - 1.0
  5271. const r = this.r, g = this.g, b = this.b;
  5272. const max = Math.max( r, g, b );
  5273. const min = Math.min( r, g, b );
  5274. let hue, saturation;
  5275. const lightness = ( min + max ) / 2.0;
  5276. if ( min === max ) {
  5277. hue = 0;
  5278. saturation = 0;
  5279. } else {
  5280. const delta = max - min;
  5281. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  5282. switch ( max ) {
  5283. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  5284. case g: hue = ( b - r ) / delta + 2; break;
  5285. case b: hue = ( r - g ) / delta + 4; break;
  5286. }
  5287. hue /= 6;
  5288. }
  5289. target.h = hue;
  5290. target.s = saturation;
  5291. target.l = lightness;
  5292. return target;
  5293. }
  5294. getStyle() {
  5295. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  5296. }
  5297. offsetHSL( h, s, l ) {
  5298. this.getHSL( _hslA );
  5299. _hslA.h += h; _hslA.s += s; _hslA.l += l;
  5300. this.setHSL( _hslA.h, _hslA.s, _hslA.l );
  5301. return this;
  5302. }
  5303. add( color ) {
  5304. this.r += color.r;
  5305. this.g += color.g;
  5306. this.b += color.b;
  5307. return this;
  5308. }
  5309. addColors( color1, color2 ) {
  5310. this.r = color1.r + color2.r;
  5311. this.g = color1.g + color2.g;
  5312. this.b = color1.b + color2.b;
  5313. return this;
  5314. }
  5315. addScalar( s ) {
  5316. this.r += s;
  5317. this.g += s;
  5318. this.b += s;
  5319. return this;
  5320. }
  5321. sub( color ) {
  5322. this.r = Math.max( 0, this.r - color.r );
  5323. this.g = Math.max( 0, this.g - color.g );
  5324. this.b = Math.max( 0, this.b - color.b );
  5325. return this;
  5326. }
  5327. multiply( color ) {
  5328. this.r *= color.r;
  5329. this.g *= color.g;
  5330. this.b *= color.b;
  5331. return this;
  5332. }
  5333. multiplyScalar( s ) {
  5334. this.r *= s;
  5335. this.g *= s;
  5336. this.b *= s;
  5337. return this;
  5338. }
  5339. lerp( color, alpha ) {
  5340. this.r += ( color.r - this.r ) * alpha;
  5341. this.g += ( color.g - this.g ) * alpha;
  5342. this.b += ( color.b - this.b ) * alpha;
  5343. return this;
  5344. }
  5345. lerpColors( color1, color2, alpha ) {
  5346. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  5347. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  5348. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  5349. return this;
  5350. }
  5351. lerpHSL( color, alpha ) {
  5352. this.getHSL( _hslA );
  5353. color.getHSL( _hslB );
  5354. const h = lerp( _hslA.h, _hslB.h, alpha );
  5355. const s = lerp( _hslA.s, _hslB.s, alpha );
  5356. const l = lerp( _hslA.l, _hslB.l, alpha );
  5357. this.setHSL( h, s, l );
  5358. return this;
  5359. }
  5360. equals( c ) {
  5361. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  5362. }
  5363. fromArray( array, offset = 0 ) {
  5364. this.r = array[ offset ];
  5365. this.g = array[ offset + 1 ];
  5366. this.b = array[ offset + 2 ];
  5367. return this;
  5368. }
  5369. toArray( array = [], offset = 0 ) {
  5370. array[ offset ] = this.r;
  5371. array[ offset + 1 ] = this.g;
  5372. array[ offset + 2 ] = this.b;
  5373. return array;
  5374. }
  5375. fromBufferAttribute( attribute, index ) {
  5376. this.r = attribute.getX( index );
  5377. this.g = attribute.getY( index );
  5378. this.b = attribute.getZ( index );
  5379. if ( attribute.normalized === true ) {
  5380. // assuming Uint8Array
  5381. this.r /= 255;
  5382. this.g /= 255;
  5383. this.b /= 255;
  5384. }
  5385. return this;
  5386. }
  5387. toJSON() {
  5388. return this.getHex();
  5389. }
  5390. }
  5391. Color.NAMES = _colorKeywords;
  5392. Color.prototype.isColor = true;
  5393. Color.prototype.r = 1;
  5394. Color.prototype.g = 1;
  5395. Color.prototype.b = 1;
  5396. /**
  5397. * parameters = {
  5398. * color: <hex>,
  5399. * opacity: <float>,
  5400. * map: new THREE.Texture( <Image> ),
  5401. *
  5402. * lightMap: new THREE.Texture( <Image> ),
  5403. * lightMapIntensity: <float>
  5404. *
  5405. * aoMap: new THREE.Texture( <Image> ),
  5406. * aoMapIntensity: <float>
  5407. *
  5408. * specularMap: new THREE.Texture( <Image> ),
  5409. *
  5410. * alphaMap: new THREE.Texture( <Image> ),
  5411. *
  5412. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  5413. * combine: THREE.Multiply,
  5414. * reflectivity: <float>,
  5415. * refractionRatio: <float>,
  5416. *
  5417. * depthTest: <bool>,
  5418. * depthWrite: <bool>,
  5419. *
  5420. * wireframe: <boolean>,
  5421. * wireframeLinewidth: <float>,
  5422. * }
  5423. */
  5424. class MeshBasicMaterial extends Material {
  5425. constructor( parameters ) {
  5426. super();
  5427. this.type = 'MeshBasicMaterial';
  5428. this.color = new Color( 0xffffff ); // emissive
  5429. this.map = null;
  5430. this.lightMap = null;
  5431. this.lightMapIntensity = 1.0;
  5432. this.aoMap = null;
  5433. this.aoMapIntensity = 1.0;
  5434. this.specularMap = null;
  5435. this.alphaMap = null;
  5436. this.envMap = null;
  5437. this.combine = MultiplyOperation;
  5438. this.reflectivity = 1;
  5439. this.refractionRatio = 0.98;
  5440. this.wireframe = false;
  5441. this.wireframeLinewidth = 1;
  5442. this.wireframeLinecap = 'round';
  5443. this.wireframeLinejoin = 'round';
  5444. this.setValues( parameters );
  5445. }
  5446. copy( source ) {
  5447. super.copy( source );
  5448. this.color.copy( source.color );
  5449. this.map = source.map;
  5450. this.lightMap = source.lightMap;
  5451. this.lightMapIntensity = source.lightMapIntensity;
  5452. this.aoMap = source.aoMap;
  5453. this.aoMapIntensity = source.aoMapIntensity;
  5454. this.specularMap = source.specularMap;
  5455. this.alphaMap = source.alphaMap;
  5456. this.envMap = source.envMap;
  5457. this.combine = source.combine;
  5458. this.reflectivity = source.reflectivity;
  5459. this.refractionRatio = source.refractionRatio;
  5460. this.wireframe = source.wireframe;
  5461. this.wireframeLinewidth = source.wireframeLinewidth;
  5462. this.wireframeLinecap = source.wireframeLinecap;
  5463. this.wireframeLinejoin = source.wireframeLinejoin;
  5464. return this;
  5465. }
  5466. }
  5467. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  5468. const _vector$9 = /*@__PURE__*/ new Vector3();
  5469. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5470. class BufferAttribute {
  5471. constructor( array, itemSize, normalized ) {
  5472. if ( Array.isArray( array ) ) {
  5473. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5474. }
  5475. this.name = '';
  5476. this.array = array;
  5477. this.itemSize = itemSize;
  5478. this.count = array !== undefined ? array.length / itemSize : 0;
  5479. this.normalized = normalized === true;
  5480. this.usage = StaticDrawUsage;
  5481. this.updateRange = { offset: 0, count: - 1 };
  5482. this.version = 0;
  5483. }
  5484. onUploadCallback() {}
  5485. set needsUpdate( value ) {
  5486. if ( value === true ) this.version ++;
  5487. }
  5488. setUsage( value ) {
  5489. this.usage = value;
  5490. return this;
  5491. }
  5492. copy( source ) {
  5493. this.name = source.name;
  5494. this.array = new source.array.constructor( source.array );
  5495. this.itemSize = source.itemSize;
  5496. this.count = source.count;
  5497. this.normalized = source.normalized;
  5498. this.usage = source.usage;
  5499. return this;
  5500. }
  5501. copyAt( index1, attribute, index2 ) {
  5502. index1 *= this.itemSize;
  5503. index2 *= attribute.itemSize;
  5504. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  5505. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5506. }
  5507. return this;
  5508. }
  5509. copyArray( array ) {
  5510. this.array.set( array );
  5511. return this;
  5512. }
  5513. copyColorsArray( colors ) {
  5514. const array = this.array;
  5515. let offset = 0;
  5516. for ( let i = 0, l = colors.length; i < l; i ++ ) {
  5517. let color = colors[ i ];
  5518. if ( color === undefined ) {
  5519. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  5520. color = new Color();
  5521. }
  5522. array[ offset ++ ] = color.r;
  5523. array[ offset ++ ] = color.g;
  5524. array[ offset ++ ] = color.b;
  5525. }
  5526. return this;
  5527. }
  5528. copyVector2sArray( vectors ) {
  5529. const array = this.array;
  5530. let offset = 0;
  5531. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  5532. let vector = vectors[ i ];
  5533. if ( vector === undefined ) {
  5534. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  5535. vector = new Vector2();
  5536. }
  5537. array[ offset ++ ] = vector.x;
  5538. array[ offset ++ ] = vector.y;
  5539. }
  5540. return this;
  5541. }
  5542. copyVector3sArray( vectors ) {
  5543. const array = this.array;
  5544. let offset = 0;
  5545. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  5546. let vector = vectors[ i ];
  5547. if ( vector === undefined ) {
  5548. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  5549. vector = new Vector3();
  5550. }
  5551. array[ offset ++ ] = vector.x;
  5552. array[ offset ++ ] = vector.y;
  5553. array[ offset ++ ] = vector.z;
  5554. }
  5555. return this;
  5556. }
  5557. copyVector4sArray( vectors ) {
  5558. const array = this.array;
  5559. let offset = 0;
  5560. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  5561. let vector = vectors[ i ];
  5562. if ( vector === undefined ) {
  5563. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  5564. vector = new Vector4();
  5565. }
  5566. array[ offset ++ ] = vector.x;
  5567. array[ offset ++ ] = vector.y;
  5568. array[ offset ++ ] = vector.z;
  5569. array[ offset ++ ] = vector.w;
  5570. }
  5571. return this;
  5572. }
  5573. applyMatrix3( m ) {
  5574. if ( this.itemSize === 2 ) {
  5575. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5576. _vector2$1.fromBufferAttribute( this, i );
  5577. _vector2$1.applyMatrix3( m );
  5578. this.setXY( i, _vector2$1.x, _vector2$1.y );
  5579. }
  5580. } else if ( this.itemSize === 3 ) {
  5581. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5582. _vector$9.fromBufferAttribute( this, i );
  5583. _vector$9.applyMatrix3( m );
  5584. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5585. }
  5586. }
  5587. return this;
  5588. }
  5589. applyMatrix4( m ) {
  5590. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5591. _vector$9.x = this.getX( i );
  5592. _vector$9.y = this.getY( i );
  5593. _vector$9.z = this.getZ( i );
  5594. _vector$9.applyMatrix4( m );
  5595. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5596. }
  5597. return this;
  5598. }
  5599. applyNormalMatrix( m ) {
  5600. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5601. _vector$9.x = this.getX( i );
  5602. _vector$9.y = this.getY( i );
  5603. _vector$9.z = this.getZ( i );
  5604. _vector$9.applyNormalMatrix( m );
  5605. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5606. }
  5607. return this;
  5608. }
  5609. transformDirection( m ) {
  5610. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5611. _vector$9.x = this.getX( i );
  5612. _vector$9.y = this.getY( i );
  5613. _vector$9.z = this.getZ( i );
  5614. _vector$9.transformDirection( m );
  5615. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5616. }
  5617. return this;
  5618. }
  5619. set( value, offset = 0 ) {
  5620. this.array.set( value, offset );
  5621. return this;
  5622. }
  5623. getX( index ) {
  5624. return this.array[ index * this.itemSize ];
  5625. }
  5626. setX( index, x ) {
  5627. this.array[ index * this.itemSize ] = x;
  5628. return this;
  5629. }
  5630. getY( index ) {
  5631. return this.array[ index * this.itemSize + 1 ];
  5632. }
  5633. setY( index, y ) {
  5634. this.array[ index * this.itemSize + 1 ] = y;
  5635. return this;
  5636. }
  5637. getZ( index ) {
  5638. return this.array[ index * this.itemSize + 2 ];
  5639. }
  5640. setZ( index, z ) {
  5641. this.array[ index * this.itemSize + 2 ] = z;
  5642. return this;
  5643. }
  5644. getW( index ) {
  5645. return this.array[ index * this.itemSize + 3 ];
  5646. }
  5647. setW( index, w ) {
  5648. this.array[ index * this.itemSize + 3 ] = w;
  5649. return this;
  5650. }
  5651. setXY( index, x, y ) {
  5652. index *= this.itemSize;
  5653. this.array[ index + 0 ] = x;
  5654. this.array[ index + 1 ] = y;
  5655. return this;
  5656. }
  5657. setXYZ( index, x, y, z ) {
  5658. index *= this.itemSize;
  5659. this.array[ index + 0 ] = x;
  5660. this.array[ index + 1 ] = y;
  5661. this.array[ index + 2 ] = z;
  5662. return this;
  5663. }
  5664. setXYZW( index, x, y, z, w ) {
  5665. index *= this.itemSize;
  5666. this.array[ index + 0 ] = x;
  5667. this.array[ index + 1 ] = y;
  5668. this.array[ index + 2 ] = z;
  5669. this.array[ index + 3 ] = w;
  5670. return this;
  5671. }
  5672. onUpload( callback ) {
  5673. this.onUploadCallback = callback;
  5674. return this;
  5675. }
  5676. clone() {
  5677. return new this.constructor( this.array, this.itemSize ).copy( this );
  5678. }
  5679. toJSON() {
  5680. const data = {
  5681. itemSize: this.itemSize,
  5682. type: this.array.constructor.name,
  5683. array: Array.prototype.slice.call( this.array ),
  5684. normalized: this.normalized
  5685. };
  5686. if ( this.name !== '' ) data.name = this.name;
  5687. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  5688. if ( this.updateRange.offset !== 0 || this.updateRange.count !== - 1 ) data.updateRange = this.updateRange;
  5689. return data;
  5690. }
  5691. }
  5692. BufferAttribute.prototype.isBufferAttribute = true;
  5693. //
  5694. class Int8BufferAttribute extends BufferAttribute {
  5695. constructor( array, itemSize, normalized ) {
  5696. super( new Int8Array( array ), itemSize, normalized );
  5697. }
  5698. }
  5699. class Uint8BufferAttribute extends BufferAttribute {
  5700. constructor( array, itemSize, normalized ) {
  5701. super( new Uint8Array( array ), itemSize, normalized );
  5702. }
  5703. }
  5704. class Uint8ClampedBufferAttribute extends BufferAttribute {
  5705. constructor( array, itemSize, normalized ) {
  5706. super( new Uint8ClampedArray( array ), itemSize, normalized );
  5707. }
  5708. }
  5709. class Int16BufferAttribute extends BufferAttribute {
  5710. constructor( array, itemSize, normalized ) {
  5711. super( new Int16Array( array ), itemSize, normalized );
  5712. }
  5713. }
  5714. class Uint16BufferAttribute extends BufferAttribute {
  5715. constructor( array, itemSize, normalized ) {
  5716. super( new Uint16Array( array ), itemSize, normalized );
  5717. }
  5718. }
  5719. class Int32BufferAttribute extends BufferAttribute {
  5720. constructor( array, itemSize, normalized ) {
  5721. super( new Int32Array( array ), itemSize, normalized );
  5722. }
  5723. }
  5724. class Uint32BufferAttribute extends BufferAttribute {
  5725. constructor( array, itemSize, normalized ) {
  5726. super( new Uint32Array( array ), itemSize, normalized );
  5727. }
  5728. }
  5729. class Float16BufferAttribute extends BufferAttribute {
  5730. constructor( array, itemSize, normalized ) {
  5731. super( new Uint16Array( array ), itemSize, normalized );
  5732. }
  5733. }
  5734. Float16BufferAttribute.prototype.isFloat16BufferAttribute = true;
  5735. class Float32BufferAttribute extends BufferAttribute {
  5736. constructor( array, itemSize, normalized ) {
  5737. super( new Float32Array( array ), itemSize, normalized );
  5738. }
  5739. }
  5740. class Float64BufferAttribute extends BufferAttribute {
  5741. constructor( array, itemSize, normalized ) {
  5742. super( new Float64Array( array ), itemSize, normalized );
  5743. }
  5744. }
  5745. let _id = 0;
  5746. const _m1 = /*@__PURE__*/ new Matrix4();
  5747. const _obj = /*@__PURE__*/ new Object3D();
  5748. const _offset = /*@__PURE__*/ new Vector3();
  5749. const _box$1 = /*@__PURE__*/ new Box3();
  5750. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  5751. const _vector$8 = /*@__PURE__*/ new Vector3();
  5752. class BufferGeometry extends EventDispatcher {
  5753. constructor() {
  5754. super();
  5755. Object.defineProperty( this, 'id', { value: _id ++ } );
  5756. this.uuid = generateUUID();
  5757. this.name = '';
  5758. this.type = 'BufferGeometry';
  5759. this.index = null;
  5760. this.attributes = {};
  5761. this.morphAttributes = {};
  5762. this.morphTargetsRelative = false;
  5763. this.groups = [];
  5764. this.boundingBox = null;
  5765. this.boundingSphere = null;
  5766. this.drawRange = { start: 0, count: Infinity };
  5767. this.userData = {};
  5768. }
  5769. getIndex() {
  5770. return this.index;
  5771. }
  5772. setIndex( index ) {
  5773. if ( Array.isArray( index ) ) {
  5774. this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  5775. } else {
  5776. this.index = index;
  5777. }
  5778. return this;
  5779. }
  5780. getAttribute( name ) {
  5781. return this.attributes[ name ];
  5782. }
  5783. setAttribute( name, attribute ) {
  5784. this.attributes[ name ] = attribute;
  5785. return this;
  5786. }
  5787. deleteAttribute( name ) {
  5788. delete this.attributes[ name ];
  5789. return this;
  5790. }
  5791. hasAttribute( name ) {
  5792. return this.attributes[ name ] !== undefined;
  5793. }
  5794. addGroup( start, count, materialIndex = 0 ) {
  5795. this.groups.push( {
  5796. start: start,
  5797. count: count,
  5798. materialIndex: materialIndex
  5799. } );
  5800. }
  5801. clearGroups() {
  5802. this.groups = [];
  5803. }
  5804. setDrawRange( start, count ) {
  5805. this.drawRange.start = start;
  5806. this.drawRange.count = count;
  5807. }
  5808. applyMatrix4( matrix ) {
  5809. const position = this.attributes.position;
  5810. if ( position !== undefined ) {
  5811. position.applyMatrix4( matrix );
  5812. position.needsUpdate = true;
  5813. }
  5814. const normal = this.attributes.normal;
  5815. if ( normal !== undefined ) {
  5816. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  5817. normal.applyNormalMatrix( normalMatrix );
  5818. normal.needsUpdate = true;
  5819. }
  5820. const tangent = this.attributes.tangent;
  5821. if ( tangent !== undefined ) {
  5822. tangent.transformDirection( matrix );
  5823. tangent.needsUpdate = true;
  5824. }
  5825. if ( this.boundingBox !== null ) {
  5826. this.computeBoundingBox();
  5827. }
  5828. if ( this.boundingSphere !== null ) {
  5829. this.computeBoundingSphere();
  5830. }
  5831. return this;
  5832. }
  5833. applyQuaternion( q ) {
  5834. _m1.makeRotationFromQuaternion( q );
  5835. this.applyMatrix4( _m1 );
  5836. return this;
  5837. }
  5838. rotateX( angle ) {
  5839. // rotate geometry around world x-axis
  5840. _m1.makeRotationX( angle );
  5841. this.applyMatrix4( _m1 );
  5842. return this;
  5843. }
  5844. rotateY( angle ) {
  5845. // rotate geometry around world y-axis
  5846. _m1.makeRotationY( angle );
  5847. this.applyMatrix4( _m1 );
  5848. return this;
  5849. }
  5850. rotateZ( angle ) {
  5851. // rotate geometry around world z-axis
  5852. _m1.makeRotationZ( angle );
  5853. this.applyMatrix4( _m1 );
  5854. return this;
  5855. }
  5856. translate( x, y, z ) {
  5857. // translate geometry
  5858. _m1.makeTranslation( x, y, z );
  5859. this.applyMatrix4( _m1 );
  5860. return this;
  5861. }
  5862. scale( x, y, z ) {
  5863. // scale geometry
  5864. _m1.makeScale( x, y, z );
  5865. this.applyMatrix4( _m1 );
  5866. return this;
  5867. }
  5868. lookAt( vector ) {
  5869. _obj.lookAt( vector );
  5870. _obj.updateMatrix();
  5871. this.applyMatrix4( _obj.matrix );
  5872. return this;
  5873. }
  5874. center() {
  5875. this.computeBoundingBox();
  5876. this.boundingBox.getCenter( _offset ).negate();
  5877. this.translate( _offset.x, _offset.y, _offset.z );
  5878. return this;
  5879. }
  5880. setFromPoints( points ) {
  5881. const position = [];
  5882. for ( let i = 0, l = points.length; i < l; i ++ ) {
  5883. const point = points[ i ];
  5884. position.push( point.x, point.y, point.z || 0 );
  5885. }
  5886. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  5887. return this;
  5888. }
  5889. computeBoundingBox() {
  5890. if ( this.boundingBox === null ) {
  5891. this.boundingBox = new Box3();
  5892. }
  5893. const position = this.attributes.position;
  5894. const morphAttributesPosition = this.morphAttributes.position;
  5895. if ( position && position.isGLBufferAttribute ) {
  5896. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this );
  5897. this.boundingBox.set(
  5898. new Vector3( - Infinity, - Infinity, - Infinity ),
  5899. new Vector3( + Infinity, + Infinity, + Infinity )
  5900. );
  5901. return;
  5902. }
  5903. if ( position !== undefined ) {
  5904. this.boundingBox.setFromBufferAttribute( position );
  5905. // process morph attributes if present
  5906. if ( morphAttributesPosition ) {
  5907. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  5908. const morphAttribute = morphAttributesPosition[ i ];
  5909. _box$1.setFromBufferAttribute( morphAttribute );
  5910. if ( this.morphTargetsRelative ) {
  5911. _vector$8.addVectors( this.boundingBox.min, _box$1.min );
  5912. this.boundingBox.expandByPoint( _vector$8 );
  5913. _vector$8.addVectors( this.boundingBox.max, _box$1.max );
  5914. this.boundingBox.expandByPoint( _vector$8 );
  5915. } else {
  5916. this.boundingBox.expandByPoint( _box$1.min );
  5917. this.boundingBox.expandByPoint( _box$1.max );
  5918. }
  5919. }
  5920. }
  5921. } else {
  5922. this.boundingBox.makeEmpty();
  5923. }
  5924. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  5925. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  5926. }
  5927. }
  5928. computeBoundingSphere() {
  5929. if ( this.boundingSphere === null ) {
  5930. this.boundingSphere = new Sphere();
  5931. }
  5932. const position = this.attributes.position;
  5933. const morphAttributesPosition = this.morphAttributes.position;
  5934. if ( position && position.isGLBufferAttribute ) {
  5935. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this );
  5936. this.boundingSphere.set( new Vector3(), Infinity );
  5937. return;
  5938. }
  5939. if ( position ) {
  5940. // first, find the center of the bounding sphere
  5941. const center = this.boundingSphere.center;
  5942. _box$1.setFromBufferAttribute( position );
  5943. // process morph attributes if present
  5944. if ( morphAttributesPosition ) {
  5945. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  5946. const morphAttribute = morphAttributesPosition[ i ];
  5947. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  5948. if ( this.morphTargetsRelative ) {
  5949. _vector$8.addVectors( _box$1.min, _boxMorphTargets.min );
  5950. _box$1.expandByPoint( _vector$8 );
  5951. _vector$8.addVectors( _box$1.max, _boxMorphTargets.max );
  5952. _box$1.expandByPoint( _vector$8 );
  5953. } else {
  5954. _box$1.expandByPoint( _boxMorphTargets.min );
  5955. _box$1.expandByPoint( _boxMorphTargets.max );
  5956. }
  5957. }
  5958. }
  5959. _box$1.getCenter( center );
  5960. // second, try to find a boundingSphere with a radius smaller than the
  5961. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  5962. let maxRadiusSq = 0;
  5963. for ( let i = 0, il = position.count; i < il; i ++ ) {
  5964. _vector$8.fromBufferAttribute( position, i );
  5965. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  5966. }
  5967. // process morph attributes if present
  5968. if ( morphAttributesPosition ) {
  5969. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  5970. const morphAttribute = morphAttributesPosition[ i ];
  5971. const morphTargetsRelative = this.morphTargetsRelative;
  5972. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  5973. _vector$8.fromBufferAttribute( morphAttribute, j );
  5974. if ( morphTargetsRelative ) {
  5975. _offset.fromBufferAttribute( position, j );
  5976. _vector$8.add( _offset );
  5977. }
  5978. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  5979. }
  5980. }
  5981. }
  5982. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  5983. if ( isNaN( this.boundingSphere.radius ) ) {
  5984. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  5985. }
  5986. }
  5987. }
  5988. computeTangents() {
  5989. const index = this.index;
  5990. const attributes = this.attributes;
  5991. // based on http://www.terathon.com/code/tangent.html
  5992. // (per vertex tangents)
  5993. if ( index === null ||
  5994. attributes.position === undefined ||
  5995. attributes.normal === undefined ||
  5996. attributes.uv === undefined ) {
  5997. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  5998. return;
  5999. }
  6000. const indices = index.array;
  6001. const positions = attributes.position.array;
  6002. const normals = attributes.normal.array;
  6003. const uvs = attributes.uv.array;
  6004. const nVertices = positions.length / 3;
  6005. if ( attributes.tangent === undefined ) {
  6006. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) );
  6007. }
  6008. const tangents = attributes.tangent.array;
  6009. const tan1 = [], tan2 = [];
  6010. for ( let i = 0; i < nVertices; i ++ ) {
  6011. tan1[ i ] = new Vector3();
  6012. tan2[ i ] = new Vector3();
  6013. }
  6014. const vA = new Vector3(),
  6015. vB = new Vector3(),
  6016. vC = new Vector3(),
  6017. uvA = new Vector2(),
  6018. uvB = new Vector2(),
  6019. uvC = new Vector2(),
  6020. sdir = new Vector3(),
  6021. tdir = new Vector3();
  6022. function handleTriangle( a, b, c ) {
  6023. vA.fromArray( positions, a * 3 );
  6024. vB.fromArray( positions, b * 3 );
  6025. vC.fromArray( positions, c * 3 );
  6026. uvA.fromArray( uvs, a * 2 );
  6027. uvB.fromArray( uvs, b * 2 );
  6028. uvC.fromArray( uvs, c * 2 );
  6029. vB.sub( vA );
  6030. vC.sub( vA );
  6031. uvB.sub( uvA );
  6032. uvC.sub( uvA );
  6033. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6034. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6035. if ( ! isFinite( r ) ) return;
  6036. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6037. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6038. tan1[ a ].add( sdir );
  6039. tan1[ b ].add( sdir );
  6040. tan1[ c ].add( sdir );
  6041. tan2[ a ].add( tdir );
  6042. tan2[ b ].add( tdir );
  6043. tan2[ c ].add( tdir );
  6044. }
  6045. let groups = this.groups;
  6046. if ( groups.length === 0 ) {
  6047. groups = [ {
  6048. start: 0,
  6049. count: indices.length
  6050. } ];
  6051. }
  6052. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6053. const group = groups[ i ];
  6054. const start = group.start;
  6055. const count = group.count;
  6056. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6057. handleTriangle(
  6058. indices[ j + 0 ],
  6059. indices[ j + 1 ],
  6060. indices[ j + 2 ]
  6061. );
  6062. }
  6063. }
  6064. const tmp = new Vector3(), tmp2 = new Vector3();
  6065. const n = new Vector3(), n2 = new Vector3();
  6066. function handleVertex( v ) {
  6067. n.fromArray( normals, v * 3 );
  6068. n2.copy( n );
  6069. const t = tan1[ v ];
  6070. // Gram-Schmidt orthogonalize
  6071. tmp.copy( t );
  6072. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6073. // Calculate handedness
  6074. tmp2.crossVectors( n2, t );
  6075. const test = tmp2.dot( tan2[ v ] );
  6076. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6077. tangents[ v * 4 ] = tmp.x;
  6078. tangents[ v * 4 + 1 ] = tmp.y;
  6079. tangents[ v * 4 + 2 ] = tmp.z;
  6080. tangents[ v * 4 + 3 ] = w;
  6081. }
  6082. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6083. const group = groups[ i ];
  6084. const start = group.start;
  6085. const count = group.count;
  6086. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6087. handleVertex( indices[ j + 0 ] );
  6088. handleVertex( indices[ j + 1 ] );
  6089. handleVertex( indices[ j + 2 ] );
  6090. }
  6091. }
  6092. }
  6093. computeVertexNormals() {
  6094. const index = this.index;
  6095. const positionAttribute = this.getAttribute( 'position' );
  6096. if ( positionAttribute !== undefined ) {
  6097. let normalAttribute = this.getAttribute( 'normal' );
  6098. if ( normalAttribute === undefined ) {
  6099. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6100. this.setAttribute( 'normal', normalAttribute );
  6101. } else {
  6102. // reset existing normals to zero
  6103. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6104. normalAttribute.setXYZ( i, 0, 0, 0 );
  6105. }
  6106. }
  6107. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6108. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6109. const cb = new Vector3(), ab = new Vector3();
  6110. // indexed elements
  6111. if ( index ) {
  6112. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6113. const vA = index.getX( i + 0 );
  6114. const vB = index.getX( i + 1 );
  6115. const vC = index.getX( i + 2 );
  6116. pA.fromBufferAttribute( positionAttribute, vA );
  6117. pB.fromBufferAttribute( positionAttribute, vB );
  6118. pC.fromBufferAttribute( positionAttribute, vC );
  6119. cb.subVectors( pC, pB );
  6120. ab.subVectors( pA, pB );
  6121. cb.cross( ab );
  6122. nA.fromBufferAttribute( normalAttribute, vA );
  6123. nB.fromBufferAttribute( normalAttribute, vB );
  6124. nC.fromBufferAttribute( normalAttribute, vC );
  6125. nA.add( cb );
  6126. nB.add( cb );
  6127. nC.add( cb );
  6128. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6129. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6130. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6131. }
  6132. } else {
  6133. // non-indexed elements (unconnected triangle soup)
  6134. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6135. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6136. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6137. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6138. cb.subVectors( pC, pB );
  6139. ab.subVectors( pA, pB );
  6140. cb.cross( ab );
  6141. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6142. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6143. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6144. }
  6145. }
  6146. this.normalizeNormals();
  6147. normalAttribute.needsUpdate = true;
  6148. }
  6149. }
  6150. merge( geometry, offset ) {
  6151. if ( ! ( geometry && geometry.isBufferGeometry ) ) {
  6152. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  6153. return;
  6154. }
  6155. if ( offset === undefined ) {
  6156. offset = 0;
  6157. console.warn(
  6158. 'THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. '
  6159. + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.'
  6160. );
  6161. }
  6162. const attributes = this.attributes;
  6163. for ( const key in attributes ) {
  6164. if ( geometry.attributes[ key ] === undefined ) continue;
  6165. const attribute1 = attributes[ key ];
  6166. const attributeArray1 = attribute1.array;
  6167. const attribute2 = geometry.attributes[ key ];
  6168. const attributeArray2 = attribute2.array;
  6169. const attributeOffset = attribute2.itemSize * offset;
  6170. const length = Math.min( attributeArray2.length, attributeArray1.length - attributeOffset );
  6171. for ( let i = 0, j = attributeOffset; i < length; i ++, j ++ ) {
  6172. attributeArray1[ j ] = attributeArray2[ i ];
  6173. }
  6174. }
  6175. return this;
  6176. }
  6177. normalizeNormals() {
  6178. const normals = this.attributes.normal;
  6179. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6180. _vector$8.fromBufferAttribute( normals, i );
  6181. _vector$8.normalize();
  6182. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  6183. }
  6184. }
  6185. toNonIndexed() {
  6186. function convertBufferAttribute( attribute, indices ) {
  6187. const array = attribute.array;
  6188. const itemSize = attribute.itemSize;
  6189. const normalized = attribute.normalized;
  6190. const array2 = new array.constructor( indices.length * itemSize );
  6191. let index = 0, index2 = 0;
  6192. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6193. if ( attribute.isInterleavedBufferAttribute ) {
  6194. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6195. } else {
  6196. index = indices[ i ] * itemSize;
  6197. }
  6198. for ( let j = 0; j < itemSize; j ++ ) {
  6199. array2[ index2 ++ ] = array[ index ++ ];
  6200. }
  6201. }
  6202. return new BufferAttribute( array2, itemSize, normalized );
  6203. }
  6204. //
  6205. if ( this.index === null ) {
  6206. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6207. return this;
  6208. }
  6209. const geometry2 = new BufferGeometry();
  6210. const indices = this.index.array;
  6211. const attributes = this.attributes;
  6212. // attributes
  6213. for ( const name in attributes ) {
  6214. const attribute = attributes[ name ];
  6215. const newAttribute = convertBufferAttribute( attribute, indices );
  6216. geometry2.setAttribute( name, newAttribute );
  6217. }
  6218. // morph attributes
  6219. const morphAttributes = this.morphAttributes;
  6220. for ( const name in morphAttributes ) {
  6221. const morphArray = [];
  6222. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6223. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6224. const attribute = morphAttribute[ i ];
  6225. const newAttribute = convertBufferAttribute( attribute, indices );
  6226. morphArray.push( newAttribute );
  6227. }
  6228. geometry2.morphAttributes[ name ] = morphArray;
  6229. }
  6230. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6231. // groups
  6232. const groups = this.groups;
  6233. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6234. const group = groups[ i ];
  6235. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6236. }
  6237. return geometry2;
  6238. }
  6239. toJSON() {
  6240. const data = {
  6241. metadata: {
  6242. version: 4.5,
  6243. type: 'BufferGeometry',
  6244. generator: 'BufferGeometry.toJSON'
  6245. }
  6246. };
  6247. // standard BufferGeometry serialization
  6248. data.uuid = this.uuid;
  6249. data.type = this.type;
  6250. if ( this.name !== '' ) data.name = this.name;
  6251. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6252. if ( this.parameters !== undefined ) {
  6253. const parameters = this.parameters;
  6254. for ( const key in parameters ) {
  6255. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6256. }
  6257. return data;
  6258. }
  6259. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6260. data.data = { attributes: {} };
  6261. const index = this.index;
  6262. if ( index !== null ) {
  6263. data.data.index = {
  6264. type: index.array.constructor.name,
  6265. array: Array.prototype.slice.call( index.array )
  6266. };
  6267. }
  6268. const attributes = this.attributes;
  6269. for ( const key in attributes ) {
  6270. const attribute = attributes[ key ];
  6271. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6272. }
  6273. const morphAttributes = {};
  6274. let hasMorphAttributes = false;
  6275. for ( const key in this.morphAttributes ) {
  6276. const attributeArray = this.morphAttributes[ key ];
  6277. const array = [];
  6278. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6279. const attribute = attributeArray[ i ];
  6280. array.push( attribute.toJSON( data.data ) );
  6281. }
  6282. if ( array.length > 0 ) {
  6283. morphAttributes[ key ] = array;
  6284. hasMorphAttributes = true;
  6285. }
  6286. }
  6287. if ( hasMorphAttributes ) {
  6288. data.data.morphAttributes = morphAttributes;
  6289. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6290. }
  6291. const groups = this.groups;
  6292. if ( groups.length > 0 ) {
  6293. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6294. }
  6295. const boundingSphere = this.boundingSphere;
  6296. if ( boundingSphere !== null ) {
  6297. data.data.boundingSphere = {
  6298. center: boundingSphere.center.toArray(),
  6299. radius: boundingSphere.radius
  6300. };
  6301. }
  6302. return data;
  6303. }
  6304. clone() {
  6305. return new this.constructor().copy( this );
  6306. }
  6307. copy( source ) {
  6308. // reset
  6309. this.index = null;
  6310. this.attributes = {};
  6311. this.morphAttributes = {};
  6312. this.groups = [];
  6313. this.boundingBox = null;
  6314. this.boundingSphere = null;
  6315. // used for storing cloned, shared data
  6316. const data = {};
  6317. // name
  6318. this.name = source.name;
  6319. // index
  6320. const index = source.index;
  6321. if ( index !== null ) {
  6322. this.setIndex( index.clone( data ) );
  6323. }
  6324. // attributes
  6325. const attributes = source.attributes;
  6326. for ( const name in attributes ) {
  6327. const attribute = attributes[ name ];
  6328. this.setAttribute( name, attribute.clone( data ) );
  6329. }
  6330. // morph attributes
  6331. const morphAttributes = source.morphAttributes;
  6332. for ( const name in morphAttributes ) {
  6333. const array = [];
  6334. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6335. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6336. array.push( morphAttribute[ i ].clone( data ) );
  6337. }
  6338. this.morphAttributes[ name ] = array;
  6339. }
  6340. this.morphTargetsRelative = source.morphTargetsRelative;
  6341. // groups
  6342. const groups = source.groups;
  6343. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6344. const group = groups[ i ];
  6345. this.addGroup( group.start, group.count, group.materialIndex );
  6346. }
  6347. // bounding box
  6348. const boundingBox = source.boundingBox;
  6349. if ( boundingBox !== null ) {
  6350. this.boundingBox = boundingBox.clone();
  6351. }
  6352. // bounding sphere
  6353. const boundingSphere = source.boundingSphere;
  6354. if ( boundingSphere !== null ) {
  6355. this.boundingSphere = boundingSphere.clone();
  6356. }
  6357. // draw range
  6358. this.drawRange.start = source.drawRange.start;
  6359. this.drawRange.count = source.drawRange.count;
  6360. // user data
  6361. this.userData = source.userData;
  6362. // geometry generator parameters
  6363. if ( source.parameters !== undefined ) this.parameters = Object.assign( {}, source.parameters );
  6364. return this;
  6365. }
  6366. dispose() {
  6367. this.dispatchEvent( { type: 'dispose' } );
  6368. }
  6369. }
  6370. BufferGeometry.prototype.isBufferGeometry = true;
  6371. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  6372. const _ray$2 = /*@__PURE__*/ new Ray();
  6373. const _sphere$3 = /*@__PURE__*/ new Sphere();
  6374. const _vA$1 = /*@__PURE__*/ new Vector3();
  6375. const _vB$1 = /*@__PURE__*/ new Vector3();
  6376. const _vC$1 = /*@__PURE__*/ new Vector3();
  6377. const _tempA = /*@__PURE__*/ new Vector3();
  6378. const _tempB = /*@__PURE__*/ new Vector3();
  6379. const _tempC = /*@__PURE__*/ new Vector3();
  6380. const _morphA = /*@__PURE__*/ new Vector3();
  6381. const _morphB = /*@__PURE__*/ new Vector3();
  6382. const _morphC = /*@__PURE__*/ new Vector3();
  6383. const _uvA$1 = /*@__PURE__*/ new Vector2();
  6384. const _uvB$1 = /*@__PURE__*/ new Vector2();
  6385. const _uvC$1 = /*@__PURE__*/ new Vector2();
  6386. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6387. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6388. class Mesh extends Object3D {
  6389. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6390. super();
  6391. this.type = 'Mesh';
  6392. this.geometry = geometry;
  6393. this.material = material;
  6394. this.updateMorphTargets();
  6395. }
  6396. copy( source ) {
  6397. super.copy( source );
  6398. if ( source.morphTargetInfluences !== undefined ) {
  6399. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6400. }
  6401. if ( source.morphTargetDictionary !== undefined ) {
  6402. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6403. }
  6404. this.material = source.material;
  6405. this.geometry = source.geometry;
  6406. return this;
  6407. }
  6408. updateMorphTargets() {
  6409. const geometry = this.geometry;
  6410. if ( geometry.isBufferGeometry ) {
  6411. const morphAttributes = geometry.morphAttributes;
  6412. const keys = Object.keys( morphAttributes );
  6413. if ( keys.length > 0 ) {
  6414. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6415. if ( morphAttribute !== undefined ) {
  6416. this.morphTargetInfluences = [];
  6417. this.morphTargetDictionary = {};
  6418. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6419. const name = morphAttribute[ m ].name || String( m );
  6420. this.morphTargetInfluences.push( 0 );
  6421. this.morphTargetDictionary[ name ] = m;
  6422. }
  6423. }
  6424. }
  6425. } else {
  6426. const morphTargets = geometry.morphTargets;
  6427. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  6428. console.error( 'THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  6429. }
  6430. }
  6431. }
  6432. raycast( raycaster, intersects ) {
  6433. const geometry = this.geometry;
  6434. const material = this.material;
  6435. const matrixWorld = this.matrixWorld;
  6436. if ( material === undefined ) return;
  6437. // Checking boundingSphere distance to ray
  6438. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6439. _sphere$3.copy( geometry.boundingSphere );
  6440. _sphere$3.applyMatrix4( matrixWorld );
  6441. if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return;
  6442. //
  6443. _inverseMatrix$2.copy( matrixWorld ).invert();
  6444. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  6445. // Check boundingBox before continuing
  6446. if ( geometry.boundingBox !== null ) {
  6447. if ( _ray$2.intersectsBox( geometry.boundingBox ) === false ) return;
  6448. }
  6449. let intersection;
  6450. if ( geometry.isBufferGeometry ) {
  6451. const index = geometry.index;
  6452. const position = geometry.attributes.position;
  6453. const morphPosition = geometry.morphAttributes.position;
  6454. const morphTargetsRelative = geometry.morphTargetsRelative;
  6455. const uv = geometry.attributes.uv;
  6456. const uv2 = geometry.attributes.uv2;
  6457. const groups = geometry.groups;
  6458. const drawRange = geometry.drawRange;
  6459. if ( index !== null ) {
  6460. // indexed buffer geometry
  6461. if ( Array.isArray( material ) ) {
  6462. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6463. const group = groups[ i ];
  6464. const groupMaterial = material[ group.materialIndex ];
  6465. const start = Math.max( group.start, drawRange.start );
  6466. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6467. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6468. const a = index.getX( j );
  6469. const b = index.getX( j + 1 );
  6470. const c = index.getX( j + 2 );
  6471. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6472. if ( intersection ) {
  6473. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  6474. intersection.face.materialIndex = group.materialIndex;
  6475. intersects.push( intersection );
  6476. }
  6477. }
  6478. }
  6479. } else {
  6480. const start = Math.max( 0, drawRange.start );
  6481. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  6482. for ( let i = start, il = end; i < il; i += 3 ) {
  6483. const a = index.getX( i );
  6484. const b = index.getX( i + 1 );
  6485. const c = index.getX( i + 2 );
  6486. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6487. if ( intersection ) {
  6488. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  6489. intersects.push( intersection );
  6490. }
  6491. }
  6492. }
  6493. } else if ( position !== undefined ) {
  6494. // non-indexed buffer geometry
  6495. if ( Array.isArray( material ) ) {
  6496. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6497. const group = groups[ i ];
  6498. const groupMaterial = material[ group.materialIndex ];
  6499. const start = Math.max( group.start, drawRange.start );
  6500. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6501. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6502. const a = j;
  6503. const b = j + 1;
  6504. const c = j + 2;
  6505. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6506. if ( intersection ) {
  6507. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  6508. intersection.face.materialIndex = group.materialIndex;
  6509. intersects.push( intersection );
  6510. }
  6511. }
  6512. }
  6513. } else {
  6514. const start = Math.max( 0, drawRange.start );
  6515. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  6516. for ( let i = start, il = end; i < il; i += 3 ) {
  6517. const a = i;
  6518. const b = i + 1;
  6519. const c = i + 2;
  6520. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6521. if ( intersection ) {
  6522. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  6523. intersects.push( intersection );
  6524. }
  6525. }
  6526. }
  6527. }
  6528. } else if ( geometry.isGeometry ) {
  6529. console.error( 'THREE.Mesh.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  6530. }
  6531. }
  6532. }
  6533. Mesh.prototype.isMesh = true;
  6534. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  6535. let intersect;
  6536. if ( material.side === BackSide ) {
  6537. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  6538. } else {
  6539. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  6540. }
  6541. if ( intersect === null ) return null;
  6542. _intersectionPointWorld.copy( point );
  6543. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  6544. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  6545. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  6546. return {
  6547. distance: distance,
  6548. point: _intersectionPointWorld.clone(),
  6549. object: object
  6550. };
  6551. }
  6552. function checkBufferGeometryIntersection( object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ) {
  6553. _vA$1.fromBufferAttribute( position, a );
  6554. _vB$1.fromBufferAttribute( position, b );
  6555. _vC$1.fromBufferAttribute( position, c );
  6556. const morphInfluences = object.morphTargetInfluences;
  6557. if ( morphPosition && morphInfluences ) {
  6558. _morphA.set( 0, 0, 0 );
  6559. _morphB.set( 0, 0, 0 );
  6560. _morphC.set( 0, 0, 0 );
  6561. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6562. const influence = morphInfluences[ i ];
  6563. const morphAttribute = morphPosition[ i ];
  6564. if ( influence === 0 ) continue;
  6565. _tempA.fromBufferAttribute( morphAttribute, a );
  6566. _tempB.fromBufferAttribute( morphAttribute, b );
  6567. _tempC.fromBufferAttribute( morphAttribute, c );
  6568. if ( morphTargetsRelative ) {
  6569. _morphA.addScaledVector( _tempA, influence );
  6570. _morphB.addScaledVector( _tempB, influence );
  6571. _morphC.addScaledVector( _tempC, influence );
  6572. } else {
  6573. _morphA.addScaledVector( _tempA.sub( _vA$1 ), influence );
  6574. _morphB.addScaledVector( _tempB.sub( _vB$1 ), influence );
  6575. _morphC.addScaledVector( _tempC.sub( _vC$1 ), influence );
  6576. }
  6577. }
  6578. _vA$1.add( _morphA );
  6579. _vB$1.add( _morphB );
  6580. _vC$1.add( _morphC );
  6581. }
  6582. if ( object.isSkinnedMesh ) {
  6583. object.boneTransform( a, _vA$1 );
  6584. object.boneTransform( b, _vB$1 );
  6585. object.boneTransform( c, _vC$1 );
  6586. }
  6587. const intersection = checkIntersection( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  6588. if ( intersection ) {
  6589. if ( uv ) {
  6590. _uvA$1.fromBufferAttribute( uv, a );
  6591. _uvB$1.fromBufferAttribute( uv, b );
  6592. _uvC$1.fromBufferAttribute( uv, c );
  6593. intersection.uv = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6594. }
  6595. if ( uv2 ) {
  6596. _uvA$1.fromBufferAttribute( uv2, a );
  6597. _uvB$1.fromBufferAttribute( uv2, b );
  6598. _uvC$1.fromBufferAttribute( uv2, c );
  6599. intersection.uv2 = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6600. }
  6601. const face = {
  6602. a: a,
  6603. b: b,
  6604. c: c,
  6605. normal: new Vector3(),
  6606. materialIndex: 0
  6607. };
  6608. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  6609. intersection.face = face;
  6610. }
  6611. return intersection;
  6612. }
  6613. class BoxGeometry extends BufferGeometry {
  6614. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  6615. super();
  6616. this.type = 'BoxGeometry';
  6617. this.parameters = {
  6618. width: width,
  6619. height: height,
  6620. depth: depth,
  6621. widthSegments: widthSegments,
  6622. heightSegments: heightSegments,
  6623. depthSegments: depthSegments
  6624. };
  6625. const scope = this;
  6626. // segments
  6627. widthSegments = Math.floor( widthSegments );
  6628. heightSegments = Math.floor( heightSegments );
  6629. depthSegments = Math.floor( depthSegments );
  6630. // buffers
  6631. const indices = [];
  6632. const vertices = [];
  6633. const normals = [];
  6634. const uvs = [];
  6635. // helper variables
  6636. let numberOfVertices = 0;
  6637. let groupStart = 0;
  6638. // build each side of the box geometry
  6639. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  6640. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  6641. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  6642. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  6643. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  6644. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  6645. // build geometry
  6646. this.setIndex( indices );
  6647. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  6648. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  6649. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  6650. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  6651. const segmentWidth = width / gridX;
  6652. const segmentHeight = height / gridY;
  6653. const widthHalf = width / 2;
  6654. const heightHalf = height / 2;
  6655. const depthHalf = depth / 2;
  6656. const gridX1 = gridX + 1;
  6657. const gridY1 = gridY + 1;
  6658. let vertexCounter = 0;
  6659. let groupCount = 0;
  6660. const vector = new Vector3();
  6661. // generate vertices, normals and uvs
  6662. for ( let iy = 0; iy < gridY1; iy ++ ) {
  6663. const y = iy * segmentHeight - heightHalf;
  6664. for ( let ix = 0; ix < gridX1; ix ++ ) {
  6665. const x = ix * segmentWidth - widthHalf;
  6666. // set values to correct vector component
  6667. vector[ u ] = x * udir;
  6668. vector[ v ] = y * vdir;
  6669. vector[ w ] = depthHalf;
  6670. // now apply vector to vertex buffer
  6671. vertices.push( vector.x, vector.y, vector.z );
  6672. // set values to correct vector component
  6673. vector[ u ] = 0;
  6674. vector[ v ] = 0;
  6675. vector[ w ] = depth > 0 ? 1 : - 1;
  6676. // now apply vector to normal buffer
  6677. normals.push( vector.x, vector.y, vector.z );
  6678. // uvs
  6679. uvs.push( ix / gridX );
  6680. uvs.push( 1 - ( iy / gridY ) );
  6681. // counters
  6682. vertexCounter += 1;
  6683. }
  6684. }
  6685. // indices
  6686. // 1. you need three indices to draw a single face
  6687. // 2. a single segment consists of two faces
  6688. // 3. so we need to generate six (2*3) indices per segment
  6689. for ( let iy = 0; iy < gridY; iy ++ ) {
  6690. for ( let ix = 0; ix < gridX; ix ++ ) {
  6691. const a = numberOfVertices + ix + gridX1 * iy;
  6692. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  6693. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  6694. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  6695. // faces
  6696. indices.push( a, b, d );
  6697. indices.push( b, c, d );
  6698. // increase counter
  6699. groupCount += 6;
  6700. }
  6701. }
  6702. // add a group to the geometry. this will ensure multi material support
  6703. scope.addGroup( groupStart, groupCount, materialIndex );
  6704. // calculate new start value for groups
  6705. groupStart += groupCount;
  6706. // update total number of vertices
  6707. numberOfVertices += vertexCounter;
  6708. }
  6709. }
  6710. static fromJSON( data ) {
  6711. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  6712. }
  6713. }
  6714. /**
  6715. * Uniform Utilities
  6716. */
  6717. function cloneUniforms( src ) {
  6718. const dst = {};
  6719. for ( const u in src ) {
  6720. dst[ u ] = {};
  6721. for ( const p in src[ u ] ) {
  6722. const property = src[ u ][ p ];
  6723. if ( property && ( property.isColor ||
  6724. property.isMatrix3 || property.isMatrix4 ||
  6725. property.isVector2 || property.isVector3 || property.isVector4 ||
  6726. property.isTexture || property.isQuaternion ) ) {
  6727. dst[ u ][ p ] = property.clone();
  6728. } else if ( Array.isArray( property ) ) {
  6729. dst[ u ][ p ] = property.slice();
  6730. } else {
  6731. dst[ u ][ p ] = property;
  6732. }
  6733. }
  6734. }
  6735. return dst;
  6736. }
  6737. function mergeUniforms( uniforms ) {
  6738. const merged = {};
  6739. for ( let u = 0; u < uniforms.length; u ++ ) {
  6740. const tmp = cloneUniforms( uniforms[ u ] );
  6741. for ( const p in tmp ) {
  6742. merged[ p ] = tmp[ p ];
  6743. }
  6744. }
  6745. return merged;
  6746. }
  6747. // Legacy
  6748. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  6749. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  6750. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  6751. /**
  6752. * parameters = {
  6753. * defines: { "label" : "value" },
  6754. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  6755. *
  6756. * fragmentShader: <string>,
  6757. * vertexShader: <string>,
  6758. *
  6759. * wireframe: <boolean>,
  6760. * wireframeLinewidth: <float>,
  6761. *
  6762. * lights: <bool>
  6763. * }
  6764. */
  6765. class ShaderMaterial extends Material {
  6766. constructor( parameters ) {
  6767. super();
  6768. this.type = 'ShaderMaterial';
  6769. this.defines = {};
  6770. this.uniforms = {};
  6771. this.vertexShader = default_vertex;
  6772. this.fragmentShader = default_fragment;
  6773. this.linewidth = 1;
  6774. this.wireframe = false;
  6775. this.wireframeLinewidth = 1;
  6776. this.fog = false; // set to use scene fog
  6777. this.lights = false; // set to use scene lights
  6778. this.clipping = false; // set to use user-defined clipping planes
  6779. this.extensions = {
  6780. derivatives: false, // set to use derivatives
  6781. fragDepth: false, // set to use fragment depth values
  6782. drawBuffers: false, // set to use draw buffers
  6783. shaderTextureLOD: false // set to use shader texture LOD
  6784. };
  6785. // When rendered geometry doesn't include these attributes but the material does,
  6786. // use these default values in WebGL. This avoids errors when buffer data is missing.
  6787. this.defaultAttributeValues = {
  6788. 'color': [ 1, 1, 1 ],
  6789. 'uv': [ 0, 0 ],
  6790. 'uv2': [ 0, 0 ]
  6791. };
  6792. this.index0AttributeName = undefined;
  6793. this.uniformsNeedUpdate = false;
  6794. this.glslVersion = null;
  6795. if ( parameters !== undefined ) {
  6796. if ( parameters.attributes !== undefined ) {
  6797. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  6798. }
  6799. this.setValues( parameters );
  6800. }
  6801. }
  6802. copy( source ) {
  6803. super.copy( source );
  6804. this.fragmentShader = source.fragmentShader;
  6805. this.vertexShader = source.vertexShader;
  6806. this.uniforms = cloneUniforms( source.uniforms );
  6807. this.defines = Object.assign( {}, source.defines );
  6808. this.wireframe = source.wireframe;
  6809. this.wireframeLinewidth = source.wireframeLinewidth;
  6810. this.lights = source.lights;
  6811. this.clipping = source.clipping;
  6812. this.extensions = Object.assign( {}, source.extensions );
  6813. this.glslVersion = source.glslVersion;
  6814. return this;
  6815. }
  6816. toJSON( meta ) {
  6817. const data = super.toJSON( meta );
  6818. data.glslVersion = this.glslVersion;
  6819. data.uniforms = {};
  6820. for ( const name in this.uniforms ) {
  6821. const uniform = this.uniforms[ name ];
  6822. const value = uniform.value;
  6823. if ( value && value.isTexture ) {
  6824. data.uniforms[ name ] = {
  6825. type: 't',
  6826. value: value.toJSON( meta ).uuid
  6827. };
  6828. } else if ( value && value.isColor ) {
  6829. data.uniforms[ name ] = {
  6830. type: 'c',
  6831. value: value.getHex()
  6832. };
  6833. } else if ( value && value.isVector2 ) {
  6834. data.uniforms[ name ] = {
  6835. type: 'v2',
  6836. value: value.toArray()
  6837. };
  6838. } else if ( value && value.isVector3 ) {
  6839. data.uniforms[ name ] = {
  6840. type: 'v3',
  6841. value: value.toArray()
  6842. };
  6843. } else if ( value && value.isVector4 ) {
  6844. data.uniforms[ name ] = {
  6845. type: 'v4',
  6846. value: value.toArray()
  6847. };
  6848. } else if ( value && value.isMatrix3 ) {
  6849. data.uniforms[ name ] = {
  6850. type: 'm3',
  6851. value: value.toArray()
  6852. };
  6853. } else if ( value && value.isMatrix4 ) {
  6854. data.uniforms[ name ] = {
  6855. type: 'm4',
  6856. value: value.toArray()
  6857. };
  6858. } else {
  6859. data.uniforms[ name ] = {
  6860. value: value
  6861. };
  6862. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  6863. }
  6864. }
  6865. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  6866. data.vertexShader = this.vertexShader;
  6867. data.fragmentShader = this.fragmentShader;
  6868. const extensions = {};
  6869. for ( const key in this.extensions ) {
  6870. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  6871. }
  6872. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  6873. return data;
  6874. }
  6875. }
  6876. ShaderMaterial.prototype.isShaderMaterial = true;
  6877. class Camera extends Object3D {
  6878. constructor() {
  6879. super();
  6880. this.type = 'Camera';
  6881. this.matrixWorldInverse = new Matrix4();
  6882. this.projectionMatrix = new Matrix4();
  6883. this.projectionMatrixInverse = new Matrix4();
  6884. }
  6885. copy( source, recursive ) {
  6886. super.copy( source, recursive );
  6887. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  6888. this.projectionMatrix.copy( source.projectionMatrix );
  6889. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  6890. return this;
  6891. }
  6892. getWorldDirection( target ) {
  6893. this.updateWorldMatrix( true, false );
  6894. const e = this.matrixWorld.elements;
  6895. return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize();
  6896. }
  6897. updateMatrixWorld( force ) {
  6898. super.updateMatrixWorld( force );
  6899. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  6900. }
  6901. updateWorldMatrix( updateParents, updateChildren ) {
  6902. super.updateWorldMatrix( updateParents, updateChildren );
  6903. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  6904. }
  6905. clone() {
  6906. return new this.constructor().copy( this );
  6907. }
  6908. }
  6909. Camera.prototype.isCamera = true;
  6910. class PerspectiveCamera extends Camera {
  6911. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  6912. super();
  6913. this.type = 'PerspectiveCamera';
  6914. this.fov = fov;
  6915. this.zoom = 1;
  6916. this.near = near;
  6917. this.far = far;
  6918. this.focus = 10;
  6919. this.aspect = aspect;
  6920. this.view = null;
  6921. this.filmGauge = 35; // width of the film (default in millimeters)
  6922. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  6923. this.updateProjectionMatrix();
  6924. }
  6925. copy( source, recursive ) {
  6926. super.copy( source, recursive );
  6927. this.fov = source.fov;
  6928. this.zoom = source.zoom;
  6929. this.near = source.near;
  6930. this.far = source.far;
  6931. this.focus = source.focus;
  6932. this.aspect = source.aspect;
  6933. this.view = source.view === null ? null : Object.assign( {}, source.view );
  6934. this.filmGauge = source.filmGauge;
  6935. this.filmOffset = source.filmOffset;
  6936. return this;
  6937. }
  6938. /**
  6939. * Sets the FOV by focal length in respect to the current .filmGauge.
  6940. *
  6941. * The default film gauge is 35, so that the focal length can be specified for
  6942. * a 35mm (full frame) camera.
  6943. *
  6944. * Values for focal length and film gauge must have the same unit.
  6945. */
  6946. setFocalLength( focalLength ) {
  6947. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  6948. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  6949. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  6950. this.updateProjectionMatrix();
  6951. }
  6952. /**
  6953. * Calculates the focal length from the current .fov and .filmGauge.
  6954. */
  6955. getFocalLength() {
  6956. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  6957. return 0.5 * this.getFilmHeight() / vExtentSlope;
  6958. }
  6959. getEffectiveFOV() {
  6960. return RAD2DEG * 2 * Math.atan(
  6961. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  6962. }
  6963. getFilmWidth() {
  6964. // film not completely covered in portrait format (aspect < 1)
  6965. return this.filmGauge * Math.min( this.aspect, 1 );
  6966. }
  6967. getFilmHeight() {
  6968. // film not completely covered in landscape format (aspect > 1)
  6969. return this.filmGauge / Math.max( this.aspect, 1 );
  6970. }
  6971. /**
  6972. * Sets an offset in a larger frustum. This is useful for multi-window or
  6973. * multi-monitor/multi-machine setups.
  6974. *
  6975. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  6976. * the monitors are in grid like this
  6977. *
  6978. * +---+---+---+
  6979. * | A | B | C |
  6980. * +---+---+---+
  6981. * | D | E | F |
  6982. * +---+---+---+
  6983. *
  6984. * then for each monitor you would call it like this
  6985. *
  6986. * const w = 1920;
  6987. * const h = 1080;
  6988. * const fullWidth = w * 3;
  6989. * const fullHeight = h * 2;
  6990. *
  6991. * --A--
  6992. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  6993. * --B--
  6994. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  6995. * --C--
  6996. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  6997. * --D--
  6998. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  6999. * --E--
  7000. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7001. * --F--
  7002. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7003. *
  7004. * Note there is no reason monitors have to be the same size or in a grid.
  7005. */
  7006. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  7007. this.aspect = fullWidth / fullHeight;
  7008. if ( this.view === null ) {
  7009. this.view = {
  7010. enabled: true,
  7011. fullWidth: 1,
  7012. fullHeight: 1,
  7013. offsetX: 0,
  7014. offsetY: 0,
  7015. width: 1,
  7016. height: 1
  7017. };
  7018. }
  7019. this.view.enabled = true;
  7020. this.view.fullWidth = fullWidth;
  7021. this.view.fullHeight = fullHeight;
  7022. this.view.offsetX = x;
  7023. this.view.offsetY = y;
  7024. this.view.width = width;
  7025. this.view.height = height;
  7026. this.updateProjectionMatrix();
  7027. }
  7028. clearViewOffset() {
  7029. if ( this.view !== null ) {
  7030. this.view.enabled = false;
  7031. }
  7032. this.updateProjectionMatrix();
  7033. }
  7034. updateProjectionMatrix() {
  7035. const near = this.near;
  7036. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7037. let height = 2 * top;
  7038. let width = this.aspect * height;
  7039. let left = - 0.5 * width;
  7040. const view = this.view;
  7041. if ( this.view !== null && this.view.enabled ) {
  7042. const fullWidth = view.fullWidth,
  7043. fullHeight = view.fullHeight;
  7044. left += view.offsetX * width / fullWidth;
  7045. top -= view.offsetY * height / fullHeight;
  7046. width *= view.width / fullWidth;
  7047. height *= view.height / fullHeight;
  7048. }
  7049. const skew = this.filmOffset;
  7050. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7051. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  7052. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7053. }
  7054. toJSON( meta ) {
  7055. const data = super.toJSON( meta );
  7056. data.object.fov = this.fov;
  7057. data.object.zoom = this.zoom;
  7058. data.object.near = this.near;
  7059. data.object.far = this.far;
  7060. data.object.focus = this.focus;
  7061. data.object.aspect = this.aspect;
  7062. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7063. data.object.filmGauge = this.filmGauge;
  7064. data.object.filmOffset = this.filmOffset;
  7065. return data;
  7066. }
  7067. }
  7068. PerspectiveCamera.prototype.isPerspectiveCamera = true;
  7069. const fov = 90, aspect = 1;
  7070. class CubeCamera extends Object3D {
  7071. constructor( near, far, renderTarget ) {
  7072. super();
  7073. this.type = 'CubeCamera';
  7074. if ( renderTarget.isWebGLCubeRenderTarget !== true ) {
  7075. console.error( 'THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.' );
  7076. return;
  7077. }
  7078. this.renderTarget = renderTarget;
  7079. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7080. cameraPX.layers = this.layers;
  7081. cameraPX.up.set( 0, - 1, 0 );
  7082. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  7083. this.add( cameraPX );
  7084. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7085. cameraNX.layers = this.layers;
  7086. cameraNX.up.set( 0, - 1, 0 );
  7087. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  7088. this.add( cameraNX );
  7089. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7090. cameraPY.layers = this.layers;
  7091. cameraPY.up.set( 0, 0, 1 );
  7092. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  7093. this.add( cameraPY );
  7094. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7095. cameraNY.layers = this.layers;
  7096. cameraNY.up.set( 0, 0, - 1 );
  7097. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  7098. this.add( cameraNY );
  7099. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7100. cameraPZ.layers = this.layers;
  7101. cameraPZ.up.set( 0, - 1, 0 );
  7102. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  7103. this.add( cameraPZ );
  7104. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7105. cameraNZ.layers = this.layers;
  7106. cameraNZ.up.set( 0, - 1, 0 );
  7107. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  7108. this.add( cameraNZ );
  7109. }
  7110. update( renderer, scene ) {
  7111. if ( this.parent === null ) this.updateMatrixWorld();
  7112. const renderTarget = this.renderTarget;
  7113. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7114. const currentXrEnabled = renderer.xr.enabled;
  7115. const currentRenderTarget = renderer.getRenderTarget();
  7116. renderer.xr.enabled = false;
  7117. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7118. renderTarget.texture.generateMipmaps = false;
  7119. renderer.setRenderTarget( renderTarget, 0 );
  7120. renderer.render( scene, cameraPX );
  7121. renderer.setRenderTarget( renderTarget, 1 );
  7122. renderer.render( scene, cameraNX );
  7123. renderer.setRenderTarget( renderTarget, 2 );
  7124. renderer.render( scene, cameraPY );
  7125. renderer.setRenderTarget( renderTarget, 3 );
  7126. renderer.render( scene, cameraNY );
  7127. renderer.setRenderTarget( renderTarget, 4 );
  7128. renderer.render( scene, cameraPZ );
  7129. renderTarget.texture.generateMipmaps = generateMipmaps;
  7130. renderer.setRenderTarget( renderTarget, 5 );
  7131. renderer.render( scene, cameraNZ );
  7132. renderer.setRenderTarget( currentRenderTarget );
  7133. renderer.xr.enabled = currentXrEnabled;
  7134. }
  7135. }
  7136. class CubeTexture extends Texture {
  7137. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  7138. images = images !== undefined ? images : [];
  7139. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7140. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  7141. this.flipY = false;
  7142. }
  7143. get images() {
  7144. return this.image;
  7145. }
  7146. set images( value ) {
  7147. this.image = value;
  7148. }
  7149. }
  7150. CubeTexture.prototype.isCubeTexture = true;
  7151. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7152. constructor( size, options, dummy ) {
  7153. if ( Number.isInteger( options ) ) {
  7154. console.warn( 'THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )' );
  7155. options = dummy;
  7156. }
  7157. super( size, size, options );
  7158. options = options || {};
  7159. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7160. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7161. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7162. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7163. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7164. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7165. this.texture = new CubeTexture( undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  7166. this.texture.isRenderTargetTexture = true;
  7167. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7168. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7169. this.texture._needsFlipEnvMap = false;
  7170. }
  7171. fromEquirectangularTexture( renderer, texture ) {
  7172. this.texture.type = texture.type;
  7173. this.texture.format = RGBAFormat; // see #18859
  7174. this.texture.encoding = texture.encoding;
  7175. this.texture.generateMipmaps = texture.generateMipmaps;
  7176. this.texture.minFilter = texture.minFilter;
  7177. this.texture.magFilter = texture.magFilter;
  7178. const shader = {
  7179. uniforms: {
  7180. tEquirect: { value: null },
  7181. },
  7182. vertexShader: /* glsl */`
  7183. varying vec3 vWorldDirection;
  7184. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7185. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7186. }
  7187. void main() {
  7188. vWorldDirection = transformDirection( position, modelMatrix );
  7189. #include <begin_vertex>
  7190. #include <project_vertex>
  7191. }
  7192. `,
  7193. fragmentShader: /* glsl */`
  7194. uniform sampler2D tEquirect;
  7195. varying vec3 vWorldDirection;
  7196. #include <common>
  7197. void main() {
  7198. vec3 direction = normalize( vWorldDirection );
  7199. vec2 sampleUV = equirectUv( direction );
  7200. gl_FragColor = texture2D( tEquirect, sampleUV );
  7201. }
  7202. `
  7203. };
  7204. const geometry = new BoxGeometry( 5, 5, 5 );
  7205. const material = new ShaderMaterial( {
  7206. name: 'CubemapFromEquirect',
  7207. uniforms: cloneUniforms( shader.uniforms ),
  7208. vertexShader: shader.vertexShader,
  7209. fragmentShader: shader.fragmentShader,
  7210. side: BackSide,
  7211. blending: NoBlending
  7212. } );
  7213. material.uniforms.tEquirect.value = texture;
  7214. const mesh = new Mesh( geometry, material );
  7215. const currentMinFilter = texture.minFilter;
  7216. // Avoid blurred poles
  7217. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7218. const camera = new CubeCamera( 1, 10, this );
  7219. camera.update( renderer, mesh );
  7220. texture.minFilter = currentMinFilter;
  7221. mesh.geometry.dispose();
  7222. mesh.material.dispose();
  7223. return this;
  7224. }
  7225. clear( renderer, color, depth, stencil ) {
  7226. const currentRenderTarget = renderer.getRenderTarget();
  7227. for ( let i = 0; i < 6; i ++ ) {
  7228. renderer.setRenderTarget( this, i );
  7229. renderer.clear( color, depth, stencil );
  7230. }
  7231. renderer.setRenderTarget( currentRenderTarget );
  7232. }
  7233. }
  7234. WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
  7235. const _vector1 = /*@__PURE__*/ new Vector3();
  7236. const _vector2 = /*@__PURE__*/ new Vector3();
  7237. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  7238. class Plane {
  7239. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  7240. // normal is assumed to be normalized
  7241. this.normal = normal;
  7242. this.constant = constant;
  7243. }
  7244. set( normal, constant ) {
  7245. this.normal.copy( normal );
  7246. this.constant = constant;
  7247. return this;
  7248. }
  7249. setComponents( x, y, z, w ) {
  7250. this.normal.set( x, y, z );
  7251. this.constant = w;
  7252. return this;
  7253. }
  7254. setFromNormalAndCoplanarPoint( normal, point ) {
  7255. this.normal.copy( normal );
  7256. this.constant = - point.dot( this.normal );
  7257. return this;
  7258. }
  7259. setFromCoplanarPoints( a, b, c ) {
  7260. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  7261. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7262. this.setFromNormalAndCoplanarPoint( normal, a );
  7263. return this;
  7264. }
  7265. copy( plane ) {
  7266. this.normal.copy( plane.normal );
  7267. this.constant = plane.constant;
  7268. return this;
  7269. }
  7270. normalize() {
  7271. // Note: will lead to a divide by zero if the plane is invalid.
  7272. const inverseNormalLength = 1.0 / this.normal.length();
  7273. this.normal.multiplyScalar( inverseNormalLength );
  7274. this.constant *= inverseNormalLength;
  7275. return this;
  7276. }
  7277. negate() {
  7278. this.constant *= - 1;
  7279. this.normal.negate();
  7280. return this;
  7281. }
  7282. distanceToPoint( point ) {
  7283. return this.normal.dot( point ) + this.constant;
  7284. }
  7285. distanceToSphere( sphere ) {
  7286. return this.distanceToPoint( sphere.center ) - sphere.radius;
  7287. }
  7288. projectPoint( point, target ) {
  7289. return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point );
  7290. }
  7291. intersectLine( line, target ) {
  7292. const direction = line.delta( _vector1 );
  7293. const denominator = this.normal.dot( direction );
  7294. if ( denominator === 0 ) {
  7295. // line is coplanar, return origin
  7296. if ( this.distanceToPoint( line.start ) === 0 ) {
  7297. return target.copy( line.start );
  7298. }
  7299. // Unsure if this is the correct method to handle this case.
  7300. return null;
  7301. }
  7302. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  7303. if ( t < 0 || t > 1 ) {
  7304. return null;
  7305. }
  7306. return target.copy( direction ).multiplyScalar( t ).add( line.start );
  7307. }
  7308. intersectsLine( line ) {
  7309. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7310. const startSign = this.distanceToPoint( line.start );
  7311. const endSign = this.distanceToPoint( line.end );
  7312. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  7313. }
  7314. intersectsBox( box ) {
  7315. return box.intersectsPlane( this );
  7316. }
  7317. intersectsSphere( sphere ) {
  7318. return sphere.intersectsPlane( this );
  7319. }
  7320. coplanarPoint( target ) {
  7321. return target.copy( this.normal ).multiplyScalar( - this.constant );
  7322. }
  7323. applyMatrix4( matrix, optionalNormalMatrix ) {
  7324. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  7325. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  7326. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  7327. this.constant = - referencePoint.dot( normal );
  7328. return this;
  7329. }
  7330. translate( offset ) {
  7331. this.constant -= offset.dot( this.normal );
  7332. return this;
  7333. }
  7334. equals( plane ) {
  7335. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  7336. }
  7337. clone() {
  7338. return new this.constructor().copy( this );
  7339. }
  7340. }
  7341. Plane.prototype.isPlane = true;
  7342. const _sphere$2 = /*@__PURE__*/ new Sphere();
  7343. const _vector$7 = /*@__PURE__*/ new Vector3();
  7344. class Frustum {
  7345. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  7346. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  7347. }
  7348. set( p0, p1, p2, p3, p4, p5 ) {
  7349. const planes = this.planes;
  7350. planes[ 0 ].copy( p0 );
  7351. planes[ 1 ].copy( p1 );
  7352. planes[ 2 ].copy( p2 );
  7353. planes[ 3 ].copy( p3 );
  7354. planes[ 4 ].copy( p4 );
  7355. planes[ 5 ].copy( p5 );
  7356. return this;
  7357. }
  7358. copy( frustum ) {
  7359. const planes = this.planes;
  7360. for ( let i = 0; i < 6; i ++ ) {
  7361. planes[ i ].copy( frustum.planes[ i ] );
  7362. }
  7363. return this;
  7364. }
  7365. setFromProjectionMatrix( m ) {
  7366. const planes = this.planes;
  7367. const me = m.elements;
  7368. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  7369. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  7370. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  7371. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  7372. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  7373. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  7374. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  7375. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  7376. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  7377. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  7378. return this;
  7379. }
  7380. intersectsObject( object ) {
  7381. const geometry = object.geometry;
  7382. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7383. _sphere$2.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  7384. return this.intersectsSphere( _sphere$2 );
  7385. }
  7386. intersectsSprite( sprite ) {
  7387. _sphere$2.center.set( 0, 0, 0 );
  7388. _sphere$2.radius = 0.7071067811865476;
  7389. _sphere$2.applyMatrix4( sprite.matrixWorld );
  7390. return this.intersectsSphere( _sphere$2 );
  7391. }
  7392. intersectsSphere( sphere ) {
  7393. const planes = this.planes;
  7394. const center = sphere.center;
  7395. const negRadius = - sphere.radius;
  7396. for ( let i = 0; i < 6; i ++ ) {
  7397. const distance = planes[ i ].distanceToPoint( center );
  7398. if ( distance < negRadius ) {
  7399. return false;
  7400. }
  7401. }
  7402. return true;
  7403. }
  7404. intersectsBox( box ) {
  7405. const planes = this.planes;
  7406. for ( let i = 0; i < 6; i ++ ) {
  7407. const plane = planes[ i ];
  7408. // corner at max distance
  7409. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7410. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7411. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7412. if ( plane.distanceToPoint( _vector$7 ) < 0 ) {
  7413. return false;
  7414. }
  7415. }
  7416. return true;
  7417. }
  7418. containsPoint( point ) {
  7419. const planes = this.planes;
  7420. for ( let i = 0; i < 6; i ++ ) {
  7421. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  7422. return false;
  7423. }
  7424. }
  7425. return true;
  7426. }
  7427. clone() {
  7428. return new this.constructor().copy( this );
  7429. }
  7430. }
  7431. function WebGLAnimation() {
  7432. let context = null;
  7433. let isAnimating = false;
  7434. let animationLoop = null;
  7435. let requestId = null;
  7436. function onAnimationFrame( time, frame ) {
  7437. animationLoop( time, frame );
  7438. requestId = context.requestAnimationFrame( onAnimationFrame );
  7439. }
  7440. return {
  7441. start: function () {
  7442. if ( isAnimating === true ) return;
  7443. if ( animationLoop === null ) return;
  7444. requestId = context.requestAnimationFrame( onAnimationFrame );
  7445. isAnimating = true;
  7446. },
  7447. stop: function () {
  7448. context.cancelAnimationFrame( requestId );
  7449. isAnimating = false;
  7450. },
  7451. setAnimationLoop: function ( callback ) {
  7452. animationLoop = callback;
  7453. },
  7454. setContext: function ( value ) {
  7455. context = value;
  7456. }
  7457. };
  7458. }
  7459. function WebGLAttributes( gl, capabilities ) {
  7460. const isWebGL2 = capabilities.isWebGL2;
  7461. const buffers = new WeakMap();
  7462. function createBuffer( attribute, bufferType ) {
  7463. const array = attribute.array;
  7464. const usage = attribute.usage;
  7465. const buffer = gl.createBuffer();
  7466. gl.bindBuffer( bufferType, buffer );
  7467. gl.bufferData( bufferType, array, usage );
  7468. attribute.onUploadCallback();
  7469. let type = 5126;
  7470. if ( array instanceof Float32Array ) {
  7471. type = 5126;
  7472. } else if ( array instanceof Float64Array ) {
  7473. console.warn( 'THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.' );
  7474. } else if ( array instanceof Uint16Array ) {
  7475. if ( attribute.isFloat16BufferAttribute ) {
  7476. if ( isWebGL2 ) {
  7477. type = 5131;
  7478. } else {
  7479. console.warn( 'THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.' );
  7480. }
  7481. } else {
  7482. type = 5123;
  7483. }
  7484. } else if ( array instanceof Int16Array ) {
  7485. type = 5122;
  7486. } else if ( array instanceof Uint32Array ) {
  7487. type = 5125;
  7488. } else if ( array instanceof Int32Array ) {
  7489. type = 5124;
  7490. } else if ( array instanceof Int8Array ) {
  7491. type = 5120;
  7492. } else if ( array instanceof Uint8Array ) {
  7493. type = 5121;
  7494. } else if ( array instanceof Uint8ClampedArray ) {
  7495. type = 5121;
  7496. }
  7497. return {
  7498. buffer: buffer,
  7499. type: type,
  7500. bytesPerElement: array.BYTES_PER_ELEMENT,
  7501. version: attribute.version
  7502. };
  7503. }
  7504. function updateBuffer( buffer, attribute, bufferType ) {
  7505. const array = attribute.array;
  7506. const updateRange = attribute.updateRange;
  7507. gl.bindBuffer( bufferType, buffer );
  7508. if ( updateRange.count === - 1 ) {
  7509. // Not using update ranges
  7510. gl.bufferSubData( bufferType, 0, array );
  7511. } else {
  7512. if ( isWebGL2 ) {
  7513. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7514. array, updateRange.offset, updateRange.count );
  7515. } else {
  7516. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7517. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  7518. }
  7519. updateRange.count = - 1; // reset range
  7520. }
  7521. }
  7522. //
  7523. function get( attribute ) {
  7524. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7525. return buffers.get( attribute );
  7526. }
  7527. function remove( attribute ) {
  7528. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7529. const data = buffers.get( attribute );
  7530. if ( data ) {
  7531. gl.deleteBuffer( data.buffer );
  7532. buffers.delete( attribute );
  7533. }
  7534. }
  7535. function update( attribute, bufferType ) {
  7536. if ( attribute.isGLBufferAttribute ) {
  7537. const cached = buffers.get( attribute );
  7538. if ( ! cached || cached.version < attribute.version ) {
  7539. buffers.set( attribute, {
  7540. buffer: attribute.buffer,
  7541. type: attribute.type,
  7542. bytesPerElement: attribute.elementSize,
  7543. version: attribute.version
  7544. } );
  7545. }
  7546. return;
  7547. }
  7548. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7549. const data = buffers.get( attribute );
  7550. if ( data === undefined ) {
  7551. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  7552. } else if ( data.version < attribute.version ) {
  7553. updateBuffer( data.buffer, attribute, bufferType );
  7554. data.version = attribute.version;
  7555. }
  7556. }
  7557. return {
  7558. get: get,
  7559. remove: remove,
  7560. update: update
  7561. };
  7562. }
  7563. class PlaneGeometry extends BufferGeometry {
  7564. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  7565. super();
  7566. this.type = 'PlaneGeometry';
  7567. this.parameters = {
  7568. width: width,
  7569. height: height,
  7570. widthSegments: widthSegments,
  7571. heightSegments: heightSegments
  7572. };
  7573. const width_half = width / 2;
  7574. const height_half = height / 2;
  7575. const gridX = Math.floor( widthSegments );
  7576. const gridY = Math.floor( heightSegments );
  7577. const gridX1 = gridX + 1;
  7578. const gridY1 = gridY + 1;
  7579. const segment_width = width / gridX;
  7580. const segment_height = height / gridY;
  7581. //
  7582. const indices = [];
  7583. const vertices = [];
  7584. const normals = [];
  7585. const uvs = [];
  7586. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7587. const y = iy * segment_height - height_half;
  7588. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7589. const x = ix * segment_width - width_half;
  7590. vertices.push( x, - y, 0 );
  7591. normals.push( 0, 0, 1 );
  7592. uvs.push( ix / gridX );
  7593. uvs.push( 1 - ( iy / gridY ) );
  7594. }
  7595. }
  7596. for ( let iy = 0; iy < gridY; iy ++ ) {
  7597. for ( let ix = 0; ix < gridX; ix ++ ) {
  7598. const a = ix + gridX1 * iy;
  7599. const b = ix + gridX1 * ( iy + 1 );
  7600. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  7601. const d = ( ix + 1 ) + gridX1 * iy;
  7602. indices.push( a, b, d );
  7603. indices.push( b, c, d );
  7604. }
  7605. }
  7606. this.setIndex( indices );
  7607. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7608. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7609. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7610. }
  7611. static fromJSON( data ) {
  7612. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  7613. }
  7614. }
  7615. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  7616. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7617. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif";
  7618. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  7619. var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif";
  7620. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7621. var begin_vertex = "vec3 transformed = vec3( position );";
  7622. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  7623. var bsdfs = "vec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenTint, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenTint * ( D * V );\n}\n#endif";
  7624. 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";
  7625. 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";
  7626. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  7627. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  7628. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  7629. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7630. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7631. 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";
  7632. 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";
  7633. var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}";
  7634. 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";
  7635. 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";
  7636. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  7637. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  7638. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  7639. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  7640. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  7641. 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}";
  7642. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t\tenvColor = envMapTexelToLinear( envColor );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";
  7643. 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";
  7644. 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";
  7645. 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";
  7646. 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";
  7647. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  7648. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  7649. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif";
  7650. var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif";
  7651. 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}";
  7652. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tlightMapIrradiance *= PI;\n\t#endif\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
  7653. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7654. var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\nvIndirectFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n\tvIndirectBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\nvIndirectFront += getAmbientLightIrradiance( ambientLightColor );\nvIndirectFront += getLightProbeIrradiance( lightProbe, geometry.normal );\n#ifdef DOUBLE_SIDED\n\tvIndirectBack += getAmbientLightIrradiance( ambientLightColor );\n\tvIndirectBack += getLightProbeIrradiance( lightProbe, backGeometry.normal );\n#endif\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointLightInfo( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotLightInfo( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalLightInfo( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry.normal );\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif";
  7655. var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tif ( cutoffDistance > 0.0 ) {\n\t\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t}\n\t\treturn distanceFalloff;\n\t#else\n\t\tif ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\t\treturn pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t\t}\n\t\treturn 1.0;\n\t#endif\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif";
  7656. var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 reflectVec;\n\t\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\t\treflectVec = reflect( - viewDir, normal );\n\t\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\t#else\n\t\t\t\treflectVec = refract( - viewDir, normal, refractionRatio );\n\t\t\t#endif\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n#endif";
  7657. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  7658. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n#define Material_LightProbeLOD( material )\t(0)";
  7659. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  7660. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)";
  7661. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\t#ifdef SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularTintFactor = specularTint;\n\t\t#ifdef USE_SPECULARINTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a;\n\t\t#endif\n\t\t#ifdef USE_SPECULARTINTMAP\n\t\t\tspecularTintFactor *= specularTintMapTexelToLinear( texture2D( specularTintMap, vUv ) ).rgb;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularTintFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( ior - 1.0 ) / ( ior + 1.0 ) ) * specularTintFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenTint = sheenTint;\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n#endif";
  7662. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenTint;\n\t\tfloat sheenRoughness;\n\t#endif\n};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\tvec3 FssEss = specularColor * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecular += ccIrradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.clearcoatNormal, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\treflectedLight.directSpecular += irradiance * BRDF_Sheen( directLight.direction, geometry.viewDir, geometry.normal, material.sheenTint, material.sheenRoughness );\n\t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.roughness );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tcomputeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}";
  7663. var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef USE_CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry.normal );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif";
  7664. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometry.normal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness );\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif";
  7665. 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";
  7666. 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";
  7667. 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";
  7668. 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";
  7669. 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";
  7670. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  7671. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  7672. 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";
  7673. 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";
  7674. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  7675. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  7676. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] > 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1, 2 ) * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\t\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\t\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\t\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n\t#endif\n#endif";
  7677. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\tuniform sampler2DArray morphTargetsTexture;\n\t\tuniform vec2 morphTargetsTextureSize;\n\t\tvec3 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset, const in int stride ) {\n\t\t\tfloat texelIndex = float( vertexIndex * stride + offset );\n\t\t\tfloat y = floor( texelIndex / morphTargetsTextureSize.x );\n\t\t\tfloat x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tvec3 morphUV = vec3( ( x + 0.5 ) / morphTargetsTextureSize.x, y / morphTargetsTextureSize.y, morphTargetIndex );\n\t\t\treturn texture( morphTargetsTexture, morphUV ).xyz;\n\t\t}\n\t#else\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\tuniform float morphTargetInfluences[ 8 ];\n\t\t#else\n\t\t\tuniform float morphTargetInfluences[ 4 ];\n\t\t#endif\n\t#endif\n#endif";
  7678. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\t#ifndef USE_MORPHNORMALS\n\t\t\t\tif ( morphTargetInfluences[ i ] > 0.0 ) transformed += getMorph( gl_VertexID, i, 0, 1 ) * morphTargetInfluences[ i ];\n\t\t\t#else\n\t\t\t\tif ( morphTargetInfluences[ i ] > 0.0 ) transformed += getMorph( gl_VertexID, i, 0, 2 ) * morphTargetInfluences[ i ];\n\t\t\t#endif\n\t\t}\n\t#else\n\t\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\t\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\t\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\t\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t\t#endif\n\t#endif\n#endif";
  7679. 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;";
  7680. 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";
  7681. var normal_pars_fragment = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif";
  7682. var normal_pars_vertex = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif";
  7683. var normal_vertex = "#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif";
  7684. 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";
  7685. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  7686. 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";
  7687. 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";
  7688. var output_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= transmissionAlpha + 0.1;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );";
  7689. 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}";
  7690. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  7691. 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;";
  7692. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  7693. 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";
  7694. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  7695. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  7696. 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";
  7697. 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";
  7698. 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";
  7699. 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}";
  7700. 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";
  7701. 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";
  7702. 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";
  7703. 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";
  7704. 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";
  7705. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  7706. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  7707. 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; }";
  7708. var transmission_fragment = "#ifdef USE_TRANSMISSION\n\tfloat transmissionAlpha = 1.0;\n\tfloat transmissionFactor = transmission;\n\tfloat thicknessFactor = thickness;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\ttransmissionFactor *= texture2D( transmissionMap, vUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tthicknessFactor *= texture2D( thicknessMap, vUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmission = getIBLVolumeRefraction(\n\t\tn, v, roughnessFactor, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, ior, thicknessFactor,\n\t\tattenuationTint, attenuationDistance );\n\ttotalDiffuse = mix( totalDiffuse, transmission.rgb, transmissionFactor );\n\ttransmissionAlpha = mix( transmissionAlpha, transmission.a, transmissionFactor );\n#endif";
  7709. var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationTint;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tvec3 getVolumeTransmissionRay( vec3 n, vec3 v, float thickness, float ior, mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( float roughness, float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( vec2 fragCoord, float roughness, float ior ) {\n\t\tfloat framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\treturn texture2DLodEXT( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#else\n\t\t\treturn texture2D( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#endif\n\t}\n\tvec3 applyVolumeAttenuation( vec3 radiance, float transmissionDistance, vec3 attenuationColor, float attenuationDistance ) {\n\t\tif ( attenuationDistance == 0.0 ) {\n\t\t\treturn radiance;\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance * radiance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( vec3 n, vec3 v, float roughness, vec3 diffuseColor, vec3 specularColor, float specularF90,\n\t\tvec3 position, mat4 modelMatrix, mat4 viewMatrix, mat4 projMatrix, float ior, float thickness,\n\t\tvec3 attenuationColor, float attenuationDistance ) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\tvec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );\n\t}\n#endif";
  7710. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  7711. 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";
  7712. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  7713. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  7714. 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";
  7715. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  7716. 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";
  7717. const vertex$g = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}";
  7718. const fragment$g = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7719. const vertex$f = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}";
  7720. const fragment$f = "#include <envmap_common_pars_fragment>\nuniform float opacity;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\tvec3 vReflect = vWorldDirection;\n\t#include <envmap_fragment>\n\tgl_FragColor = envColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7721. const vertex$e = "#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvHighPrecisionZW = gl_Position.zw;\n}";
  7722. const fragment$e = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}";
  7723. const vertex$d = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}";
  7724. const fragment$d = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}";
  7725. const vertex$c = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}";
  7726. const fragment$c = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tvec4 texColor = texture2D( tEquirect, sampleUV );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7727. const vertex$b = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  7728. const fragment$b = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  7729. const vertex$a = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinbase_vertex>\n\t\t#include <skinnormal_vertex>\n\t\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";
  7730. const fragment$a = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7731. const vertex$9 = "#define LAMBERT\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7732. const fragment$9 = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack;\n\t#else\n\t\treflectedLight.indirectDiffuse += vIndirectFront;\n\t#endif\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7733. const vertex$8 = "#define MATCAP\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";
  7734. const fragment$8 = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t\tmatcapColor = matcapTexelToLinear( matcapColor );\n\t#else\n\t\tvec4 matcapColor = vec4( 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7735. const vertex$7 = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
  7736. const fragment$7 = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}";
  7737. const vertex$6 = "#define PHONG\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7738. const fragment$6 = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7739. const vertex$5 = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}";
  7740. const fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularTint;\n\t#ifdef USE_SPECULARINTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n\t#ifdef USE_SPECULARTINTMAP\n\t\tuniform sampler2D specularTintMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenTint;\n\tuniform float sheenRoughness;\n#endif\nvarying vec3 vViewPosition;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_physical_pars_fragment>\n#include <transmission_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include <transmission_fragment>\n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - clearcoat * Fcc ) + clearcoatSpecular * clearcoat;\n\t#endif\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7741. const vertex$4 = "#define TOON\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7742. const fragment$4 = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7743. const vertex$3 = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n}";
  7744. const fragment$3 = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  7745. const vertex$2 = "#include <common>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7746. const fragment$2 = "uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  7747. const vertex$1 = "uniform float rotation;\nuniform vec2 center;\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  7748. const fragment$1 = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  7749. const ShaderChunk = {
  7750. alphamap_fragment: alphamap_fragment,
  7751. alphamap_pars_fragment: alphamap_pars_fragment,
  7752. alphatest_fragment: alphatest_fragment,
  7753. alphatest_pars_fragment: alphatest_pars_fragment,
  7754. aomap_fragment: aomap_fragment,
  7755. aomap_pars_fragment: aomap_pars_fragment,
  7756. begin_vertex: begin_vertex,
  7757. beginnormal_vertex: beginnormal_vertex,
  7758. bsdfs: bsdfs,
  7759. bumpmap_pars_fragment: bumpmap_pars_fragment,
  7760. clipping_planes_fragment: clipping_planes_fragment,
  7761. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  7762. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  7763. clipping_planes_vertex: clipping_planes_vertex,
  7764. color_fragment: color_fragment,
  7765. color_pars_fragment: color_pars_fragment,
  7766. color_pars_vertex: color_pars_vertex,
  7767. color_vertex: color_vertex,
  7768. common: common,
  7769. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  7770. defaultnormal_vertex: defaultnormal_vertex,
  7771. displacementmap_pars_vertex: displacementmap_pars_vertex,
  7772. displacementmap_vertex: displacementmap_vertex,
  7773. emissivemap_fragment: emissivemap_fragment,
  7774. emissivemap_pars_fragment: emissivemap_pars_fragment,
  7775. encodings_fragment: encodings_fragment,
  7776. encodings_pars_fragment: encodings_pars_fragment,
  7777. envmap_fragment: envmap_fragment,
  7778. envmap_common_pars_fragment: envmap_common_pars_fragment,
  7779. envmap_pars_fragment: envmap_pars_fragment,
  7780. envmap_pars_vertex: envmap_pars_vertex,
  7781. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  7782. envmap_vertex: envmap_vertex,
  7783. fog_vertex: fog_vertex,
  7784. fog_pars_vertex: fog_pars_vertex,
  7785. fog_fragment: fog_fragment,
  7786. fog_pars_fragment: fog_pars_fragment,
  7787. gradientmap_pars_fragment: gradientmap_pars_fragment,
  7788. lightmap_fragment: lightmap_fragment,
  7789. lightmap_pars_fragment: lightmap_pars_fragment,
  7790. lights_lambert_vertex: lights_lambert_vertex,
  7791. lights_pars_begin: lights_pars_begin,
  7792. lights_toon_fragment: lights_toon_fragment,
  7793. lights_toon_pars_fragment: lights_toon_pars_fragment,
  7794. lights_phong_fragment: lights_phong_fragment,
  7795. lights_phong_pars_fragment: lights_phong_pars_fragment,
  7796. lights_physical_fragment: lights_physical_fragment,
  7797. lights_physical_pars_fragment: lights_physical_pars_fragment,
  7798. lights_fragment_begin: lights_fragment_begin,
  7799. lights_fragment_maps: lights_fragment_maps,
  7800. lights_fragment_end: lights_fragment_end,
  7801. logdepthbuf_fragment: logdepthbuf_fragment,
  7802. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  7803. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  7804. logdepthbuf_vertex: logdepthbuf_vertex,
  7805. map_fragment: map_fragment,
  7806. map_pars_fragment: map_pars_fragment,
  7807. map_particle_fragment: map_particle_fragment,
  7808. map_particle_pars_fragment: map_particle_pars_fragment,
  7809. metalnessmap_fragment: metalnessmap_fragment,
  7810. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  7811. morphnormal_vertex: morphnormal_vertex,
  7812. morphtarget_pars_vertex: morphtarget_pars_vertex,
  7813. morphtarget_vertex: morphtarget_vertex,
  7814. normal_fragment_begin: normal_fragment_begin,
  7815. normal_fragment_maps: normal_fragment_maps,
  7816. normal_pars_fragment: normal_pars_fragment,
  7817. normal_pars_vertex: normal_pars_vertex,
  7818. normal_vertex: normal_vertex,
  7819. normalmap_pars_fragment: normalmap_pars_fragment,
  7820. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  7821. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  7822. clearcoat_pars_fragment: clearcoat_pars_fragment,
  7823. output_fragment: output_fragment,
  7824. packing: packing,
  7825. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  7826. project_vertex: project_vertex,
  7827. dithering_fragment: dithering_fragment,
  7828. dithering_pars_fragment: dithering_pars_fragment,
  7829. roughnessmap_fragment: roughnessmap_fragment,
  7830. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  7831. shadowmap_pars_fragment: shadowmap_pars_fragment,
  7832. shadowmap_pars_vertex: shadowmap_pars_vertex,
  7833. shadowmap_vertex: shadowmap_vertex,
  7834. shadowmask_pars_fragment: shadowmask_pars_fragment,
  7835. skinbase_vertex: skinbase_vertex,
  7836. skinning_pars_vertex: skinning_pars_vertex,
  7837. skinning_vertex: skinning_vertex,
  7838. skinnormal_vertex: skinnormal_vertex,
  7839. specularmap_fragment: specularmap_fragment,
  7840. specularmap_pars_fragment: specularmap_pars_fragment,
  7841. tonemapping_fragment: tonemapping_fragment,
  7842. tonemapping_pars_fragment: tonemapping_pars_fragment,
  7843. transmission_fragment: transmission_fragment,
  7844. transmission_pars_fragment: transmission_pars_fragment,
  7845. uv_pars_fragment: uv_pars_fragment,
  7846. uv_pars_vertex: uv_pars_vertex,
  7847. uv_vertex: uv_vertex,
  7848. uv2_pars_fragment: uv2_pars_fragment,
  7849. uv2_pars_vertex: uv2_pars_vertex,
  7850. uv2_vertex: uv2_vertex,
  7851. worldpos_vertex: worldpos_vertex,
  7852. background_vert: vertex$g,
  7853. background_frag: fragment$g,
  7854. cube_vert: vertex$f,
  7855. cube_frag: fragment$f,
  7856. depth_vert: vertex$e,
  7857. depth_frag: fragment$e,
  7858. distanceRGBA_vert: vertex$d,
  7859. distanceRGBA_frag: fragment$d,
  7860. equirect_vert: vertex$c,
  7861. equirect_frag: fragment$c,
  7862. linedashed_vert: vertex$b,
  7863. linedashed_frag: fragment$b,
  7864. meshbasic_vert: vertex$a,
  7865. meshbasic_frag: fragment$a,
  7866. meshlambert_vert: vertex$9,
  7867. meshlambert_frag: fragment$9,
  7868. meshmatcap_vert: vertex$8,
  7869. meshmatcap_frag: fragment$8,
  7870. meshnormal_vert: vertex$7,
  7871. meshnormal_frag: fragment$7,
  7872. meshphong_vert: vertex$6,
  7873. meshphong_frag: fragment$6,
  7874. meshphysical_vert: vertex$5,
  7875. meshphysical_frag: fragment$5,
  7876. meshtoon_vert: vertex$4,
  7877. meshtoon_frag: fragment$4,
  7878. points_vert: vertex$3,
  7879. points_frag: fragment$3,
  7880. shadow_vert: vertex$2,
  7881. shadow_frag: fragment$2,
  7882. sprite_vert: vertex$1,
  7883. sprite_frag: fragment$1
  7884. };
  7885. /**
  7886. * Uniforms library for shared webgl shaders
  7887. */
  7888. const UniformsLib = {
  7889. common: {
  7890. diffuse: { value: new Color( 0xffffff ) },
  7891. opacity: { value: 1.0 },
  7892. map: { value: null },
  7893. uvTransform: { value: new Matrix3() },
  7894. uv2Transform: { value: new Matrix3() },
  7895. alphaMap: { value: null },
  7896. alphaTest: { value: 0 }
  7897. },
  7898. specularmap: {
  7899. specularMap: { value: null },
  7900. },
  7901. envmap: {
  7902. envMap: { value: null },
  7903. flipEnvMap: { value: - 1 },
  7904. reflectivity: { value: 1.0 }, // basic, lambert, phong
  7905. ior: { value: 1.5 }, // standard, physical
  7906. refractionRatio: { value: 0.98 },
  7907. maxMipLevel: { value: 0 }
  7908. },
  7909. aomap: {
  7910. aoMap: { value: null },
  7911. aoMapIntensity: { value: 1 }
  7912. },
  7913. lightmap: {
  7914. lightMap: { value: null },
  7915. lightMapIntensity: { value: 1 }
  7916. },
  7917. emissivemap: {
  7918. emissiveMap: { value: null }
  7919. },
  7920. bumpmap: {
  7921. bumpMap: { value: null },
  7922. bumpScale: { value: 1 }
  7923. },
  7924. normalmap: {
  7925. normalMap: { value: null },
  7926. normalScale: { value: new Vector2( 1, 1 ) }
  7927. },
  7928. displacementmap: {
  7929. displacementMap: { value: null },
  7930. displacementScale: { value: 1 },
  7931. displacementBias: { value: 0 }
  7932. },
  7933. roughnessmap: {
  7934. roughnessMap: { value: null }
  7935. },
  7936. metalnessmap: {
  7937. metalnessMap: { value: null }
  7938. },
  7939. gradientmap: {
  7940. gradientMap: { value: null }
  7941. },
  7942. fog: {
  7943. fogDensity: { value: 0.00025 },
  7944. fogNear: { value: 1 },
  7945. fogFar: { value: 2000 },
  7946. fogColor: { value: new Color( 0xffffff ) }
  7947. },
  7948. lights: {
  7949. ambientLightColor: { value: [] },
  7950. lightProbe: { value: [] },
  7951. directionalLights: { value: [], properties: {
  7952. direction: {},
  7953. color: {}
  7954. } },
  7955. directionalLightShadows: { value: [], properties: {
  7956. shadowBias: {},
  7957. shadowNormalBias: {},
  7958. shadowRadius: {},
  7959. shadowMapSize: {}
  7960. } },
  7961. directionalShadowMap: { value: [] },
  7962. directionalShadowMatrix: { value: [] },
  7963. spotLights: { value: [], properties: {
  7964. color: {},
  7965. position: {},
  7966. direction: {},
  7967. distance: {},
  7968. coneCos: {},
  7969. penumbraCos: {},
  7970. decay: {}
  7971. } },
  7972. spotLightShadows: { value: [], properties: {
  7973. shadowBias: {},
  7974. shadowNormalBias: {},
  7975. shadowRadius: {},
  7976. shadowMapSize: {}
  7977. } },
  7978. spotShadowMap: { value: [] },
  7979. spotShadowMatrix: { value: [] },
  7980. pointLights: { value: [], properties: {
  7981. color: {},
  7982. position: {},
  7983. decay: {},
  7984. distance: {}
  7985. } },
  7986. pointLightShadows: { value: [], properties: {
  7987. shadowBias: {},
  7988. shadowNormalBias: {},
  7989. shadowRadius: {},
  7990. shadowMapSize: {},
  7991. shadowCameraNear: {},
  7992. shadowCameraFar: {}
  7993. } },
  7994. pointShadowMap: { value: [] },
  7995. pointShadowMatrix: { value: [] },
  7996. hemisphereLights: { value: [], properties: {
  7997. direction: {},
  7998. skyColor: {},
  7999. groundColor: {}
  8000. } },
  8001. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8002. rectAreaLights: { value: [], properties: {
  8003. color: {},
  8004. position: {},
  8005. width: {},
  8006. height: {}
  8007. } },
  8008. ltc_1: { value: null },
  8009. ltc_2: { value: null }
  8010. },
  8011. points: {
  8012. diffuse: { value: new Color( 0xffffff ) },
  8013. opacity: { value: 1.0 },
  8014. size: { value: 1.0 },
  8015. scale: { value: 1.0 },
  8016. map: { value: null },
  8017. alphaMap: { value: null },
  8018. alphaTest: { value: 0 },
  8019. uvTransform: { value: new Matrix3() }
  8020. },
  8021. sprite: {
  8022. diffuse: { value: new Color( 0xffffff ) },
  8023. opacity: { value: 1.0 },
  8024. center: { value: new Vector2( 0.5, 0.5 ) },
  8025. rotation: { value: 0.0 },
  8026. map: { value: null },
  8027. alphaMap: { value: null },
  8028. alphaTest: { value: 0 },
  8029. uvTransform: { value: new Matrix3() }
  8030. }
  8031. };
  8032. const ShaderLib = {
  8033. basic: {
  8034. uniforms: mergeUniforms( [
  8035. UniformsLib.common,
  8036. UniformsLib.specularmap,
  8037. UniformsLib.envmap,
  8038. UniformsLib.aomap,
  8039. UniformsLib.lightmap,
  8040. UniformsLib.fog
  8041. ] ),
  8042. vertexShader: ShaderChunk.meshbasic_vert,
  8043. fragmentShader: ShaderChunk.meshbasic_frag
  8044. },
  8045. lambert: {
  8046. uniforms: mergeUniforms( [
  8047. UniformsLib.common,
  8048. UniformsLib.specularmap,
  8049. UniformsLib.envmap,
  8050. UniformsLib.aomap,
  8051. UniformsLib.lightmap,
  8052. UniformsLib.emissivemap,
  8053. UniformsLib.fog,
  8054. UniformsLib.lights,
  8055. {
  8056. emissive: { value: new Color( 0x000000 ) }
  8057. }
  8058. ] ),
  8059. vertexShader: ShaderChunk.meshlambert_vert,
  8060. fragmentShader: ShaderChunk.meshlambert_frag
  8061. },
  8062. phong: {
  8063. uniforms: mergeUniforms( [
  8064. UniformsLib.common,
  8065. UniformsLib.specularmap,
  8066. UniformsLib.envmap,
  8067. UniformsLib.aomap,
  8068. UniformsLib.lightmap,
  8069. UniformsLib.emissivemap,
  8070. UniformsLib.bumpmap,
  8071. UniformsLib.normalmap,
  8072. UniformsLib.displacementmap,
  8073. UniformsLib.fog,
  8074. UniformsLib.lights,
  8075. {
  8076. emissive: { value: new Color( 0x000000 ) },
  8077. specular: { value: new Color( 0x111111 ) },
  8078. shininess: { value: 30 }
  8079. }
  8080. ] ),
  8081. vertexShader: ShaderChunk.meshphong_vert,
  8082. fragmentShader: ShaderChunk.meshphong_frag
  8083. },
  8084. standard: {
  8085. uniforms: mergeUniforms( [
  8086. UniformsLib.common,
  8087. UniformsLib.envmap,
  8088. UniformsLib.aomap,
  8089. UniformsLib.lightmap,
  8090. UniformsLib.emissivemap,
  8091. UniformsLib.bumpmap,
  8092. UniformsLib.normalmap,
  8093. UniformsLib.displacementmap,
  8094. UniformsLib.roughnessmap,
  8095. UniformsLib.metalnessmap,
  8096. UniformsLib.fog,
  8097. UniformsLib.lights,
  8098. {
  8099. emissive: { value: new Color( 0x000000 ) },
  8100. roughness: { value: 1.0 },
  8101. metalness: { value: 0.0 },
  8102. envMapIntensity: { value: 1 } // temporary
  8103. }
  8104. ] ),
  8105. vertexShader: ShaderChunk.meshphysical_vert,
  8106. fragmentShader: ShaderChunk.meshphysical_frag
  8107. },
  8108. toon: {
  8109. uniforms: mergeUniforms( [
  8110. UniformsLib.common,
  8111. UniformsLib.aomap,
  8112. UniformsLib.lightmap,
  8113. UniformsLib.emissivemap,
  8114. UniformsLib.bumpmap,
  8115. UniformsLib.normalmap,
  8116. UniformsLib.displacementmap,
  8117. UniformsLib.gradientmap,
  8118. UniformsLib.fog,
  8119. UniformsLib.lights,
  8120. {
  8121. emissive: { value: new Color( 0x000000 ) }
  8122. }
  8123. ] ),
  8124. vertexShader: ShaderChunk.meshtoon_vert,
  8125. fragmentShader: ShaderChunk.meshtoon_frag
  8126. },
  8127. matcap: {
  8128. uniforms: mergeUniforms( [
  8129. UniformsLib.common,
  8130. UniformsLib.bumpmap,
  8131. UniformsLib.normalmap,
  8132. UniformsLib.displacementmap,
  8133. UniformsLib.fog,
  8134. {
  8135. matcap: { value: null }
  8136. }
  8137. ] ),
  8138. vertexShader: ShaderChunk.meshmatcap_vert,
  8139. fragmentShader: ShaderChunk.meshmatcap_frag
  8140. },
  8141. points: {
  8142. uniforms: mergeUniforms( [
  8143. UniformsLib.points,
  8144. UniformsLib.fog
  8145. ] ),
  8146. vertexShader: ShaderChunk.points_vert,
  8147. fragmentShader: ShaderChunk.points_frag
  8148. },
  8149. dashed: {
  8150. uniforms: mergeUniforms( [
  8151. UniformsLib.common,
  8152. UniformsLib.fog,
  8153. {
  8154. scale: { value: 1 },
  8155. dashSize: { value: 1 },
  8156. totalSize: { value: 2 }
  8157. }
  8158. ] ),
  8159. vertexShader: ShaderChunk.linedashed_vert,
  8160. fragmentShader: ShaderChunk.linedashed_frag
  8161. },
  8162. depth: {
  8163. uniforms: mergeUniforms( [
  8164. UniformsLib.common,
  8165. UniformsLib.displacementmap
  8166. ] ),
  8167. vertexShader: ShaderChunk.depth_vert,
  8168. fragmentShader: ShaderChunk.depth_frag
  8169. },
  8170. normal: {
  8171. uniforms: mergeUniforms( [
  8172. UniformsLib.common,
  8173. UniformsLib.bumpmap,
  8174. UniformsLib.normalmap,
  8175. UniformsLib.displacementmap,
  8176. {
  8177. opacity: { value: 1.0 }
  8178. }
  8179. ] ),
  8180. vertexShader: ShaderChunk.meshnormal_vert,
  8181. fragmentShader: ShaderChunk.meshnormal_frag
  8182. },
  8183. sprite: {
  8184. uniforms: mergeUniforms( [
  8185. UniformsLib.sprite,
  8186. UniformsLib.fog
  8187. ] ),
  8188. vertexShader: ShaderChunk.sprite_vert,
  8189. fragmentShader: ShaderChunk.sprite_frag
  8190. },
  8191. background: {
  8192. uniforms: {
  8193. uvTransform: { value: new Matrix3() },
  8194. t2D: { value: null },
  8195. },
  8196. vertexShader: ShaderChunk.background_vert,
  8197. fragmentShader: ShaderChunk.background_frag
  8198. },
  8199. /* -------------------------------------------------------------------------
  8200. // Cube map shader
  8201. ------------------------------------------------------------------------- */
  8202. cube: {
  8203. uniforms: mergeUniforms( [
  8204. UniformsLib.envmap,
  8205. {
  8206. opacity: { value: 1.0 }
  8207. }
  8208. ] ),
  8209. vertexShader: ShaderChunk.cube_vert,
  8210. fragmentShader: ShaderChunk.cube_frag
  8211. },
  8212. equirect: {
  8213. uniforms: {
  8214. tEquirect: { value: null },
  8215. },
  8216. vertexShader: ShaderChunk.equirect_vert,
  8217. fragmentShader: ShaderChunk.equirect_frag
  8218. },
  8219. distanceRGBA: {
  8220. uniforms: mergeUniforms( [
  8221. UniformsLib.common,
  8222. UniformsLib.displacementmap,
  8223. {
  8224. referencePosition: { value: new Vector3() },
  8225. nearDistance: { value: 1 },
  8226. farDistance: { value: 1000 }
  8227. }
  8228. ] ),
  8229. vertexShader: ShaderChunk.distanceRGBA_vert,
  8230. fragmentShader: ShaderChunk.distanceRGBA_frag
  8231. },
  8232. shadow: {
  8233. uniforms: mergeUniforms( [
  8234. UniformsLib.lights,
  8235. UniformsLib.fog,
  8236. {
  8237. color: { value: new Color( 0x00000 ) },
  8238. opacity: { value: 1.0 }
  8239. },
  8240. ] ),
  8241. vertexShader: ShaderChunk.shadow_vert,
  8242. fragmentShader: ShaderChunk.shadow_frag
  8243. }
  8244. };
  8245. ShaderLib.physical = {
  8246. uniforms: mergeUniforms( [
  8247. ShaderLib.standard.uniforms,
  8248. {
  8249. clearcoat: { value: 0 },
  8250. clearcoatMap: { value: null },
  8251. clearcoatRoughness: { value: 0 },
  8252. clearcoatRoughnessMap: { value: null },
  8253. clearcoatNormalScale: { value: new Vector2( 1, 1 ) },
  8254. clearcoatNormalMap: { value: null },
  8255. sheen: { value: 0 },
  8256. sheenTint: { value: new Color( 0x000000 ) },
  8257. sheenRoughness: { value: 0 },
  8258. transmission: { value: 0 },
  8259. transmissionMap: { value: null },
  8260. transmissionSamplerSize: { value: new Vector2() },
  8261. transmissionSamplerMap: { value: null },
  8262. thickness: { value: 0 },
  8263. thicknessMap: { value: null },
  8264. attenuationDistance: { value: 0 },
  8265. attenuationTint: { value: new Color( 0x000000 ) },
  8266. specularIntensity: { value: 0 },
  8267. specularIntensityMap: { value: null },
  8268. specularTint: { value: new Color( 1, 1, 1 ) },
  8269. specularTintMap: { value: null },
  8270. }
  8271. ] ),
  8272. vertexShader: ShaderChunk.meshphysical_vert,
  8273. fragmentShader: ShaderChunk.meshphysical_frag
  8274. };
  8275. function WebGLBackground( renderer, cubemaps, state, objects, premultipliedAlpha ) {
  8276. const clearColor = new Color( 0x000000 );
  8277. let clearAlpha = 0;
  8278. let planeMesh;
  8279. let boxMesh;
  8280. let currentBackground = null;
  8281. let currentBackgroundVersion = 0;
  8282. let currentTonemapping = null;
  8283. function render( renderList, scene ) {
  8284. let forceClear = false;
  8285. let background = scene.isScene === true ? scene.background : null;
  8286. if ( background && background.isTexture ) {
  8287. background = cubemaps.get( background );
  8288. }
  8289. // Ignore background in AR
  8290. // TODO: Reconsider this.
  8291. const xr = renderer.xr;
  8292. const session = xr.getSession && xr.getSession();
  8293. if ( session && session.environmentBlendMode === 'additive' ) {
  8294. background = null;
  8295. }
  8296. if ( background === null ) {
  8297. setClear( clearColor, clearAlpha );
  8298. } else if ( background && background.isColor ) {
  8299. setClear( background, 1 );
  8300. forceClear = true;
  8301. }
  8302. if ( renderer.autoClear || forceClear ) {
  8303. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  8304. }
  8305. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  8306. if ( boxMesh === undefined ) {
  8307. boxMesh = new Mesh(
  8308. new BoxGeometry( 1, 1, 1 ),
  8309. new ShaderMaterial( {
  8310. name: 'BackgroundCubeMaterial',
  8311. uniforms: cloneUniforms( ShaderLib.cube.uniforms ),
  8312. vertexShader: ShaderLib.cube.vertexShader,
  8313. fragmentShader: ShaderLib.cube.fragmentShader,
  8314. side: BackSide,
  8315. depthTest: false,
  8316. depthWrite: false,
  8317. fog: false
  8318. } )
  8319. );
  8320. boxMesh.geometry.deleteAttribute( 'normal' );
  8321. boxMesh.geometry.deleteAttribute( 'uv' );
  8322. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  8323. this.matrixWorld.copyPosition( camera.matrixWorld );
  8324. };
  8325. // enable code injection for non-built-in material
  8326. Object.defineProperty( boxMesh.material, 'envMap', {
  8327. get: function () {
  8328. return this.uniforms.envMap.value;
  8329. }
  8330. } );
  8331. objects.update( boxMesh );
  8332. }
  8333. boxMesh.material.uniforms.envMap.value = background;
  8334. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1;
  8335. if ( currentBackground !== background ||
  8336. currentBackgroundVersion !== background.version ||
  8337. currentTonemapping !== renderer.toneMapping ) {
  8338. boxMesh.material.needsUpdate = true;
  8339. currentBackground = background;
  8340. currentBackgroundVersion = background.version;
  8341. currentTonemapping = renderer.toneMapping;
  8342. }
  8343. // push to the pre-sorted opaque render list
  8344. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  8345. } else if ( background && background.isTexture ) {
  8346. if ( planeMesh === undefined ) {
  8347. planeMesh = new Mesh(
  8348. new PlaneGeometry( 2, 2 ),
  8349. new ShaderMaterial( {
  8350. name: 'BackgroundMaterial',
  8351. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  8352. vertexShader: ShaderLib.background.vertexShader,
  8353. fragmentShader: ShaderLib.background.fragmentShader,
  8354. side: FrontSide,
  8355. depthTest: false,
  8356. depthWrite: false,
  8357. fog: false
  8358. } )
  8359. );
  8360. planeMesh.geometry.deleteAttribute( 'normal' );
  8361. // enable code injection for non-built-in material
  8362. Object.defineProperty( planeMesh.material, 'map', {
  8363. get: function () {
  8364. return this.uniforms.t2D.value;
  8365. }
  8366. } );
  8367. objects.update( planeMesh );
  8368. }
  8369. planeMesh.material.uniforms.t2D.value = background;
  8370. if ( background.matrixAutoUpdate === true ) {
  8371. background.updateMatrix();
  8372. }
  8373. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  8374. if ( currentBackground !== background ||
  8375. currentBackgroundVersion !== background.version ||
  8376. currentTonemapping !== renderer.toneMapping ) {
  8377. planeMesh.material.needsUpdate = true;
  8378. currentBackground = background;
  8379. currentBackgroundVersion = background.version;
  8380. currentTonemapping = renderer.toneMapping;
  8381. }
  8382. // push to the pre-sorted opaque render list
  8383. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  8384. }
  8385. }
  8386. function setClear( color, alpha ) {
  8387. state.buffers.color.setClear( color.r, color.g, color.b, alpha, premultipliedAlpha );
  8388. }
  8389. return {
  8390. getClearColor: function () {
  8391. return clearColor;
  8392. },
  8393. setClearColor: function ( color, alpha = 1 ) {
  8394. clearColor.set( color );
  8395. clearAlpha = alpha;
  8396. setClear( clearColor, clearAlpha );
  8397. },
  8398. getClearAlpha: function () {
  8399. return clearAlpha;
  8400. },
  8401. setClearAlpha: function ( alpha ) {
  8402. clearAlpha = alpha;
  8403. setClear( clearColor, clearAlpha );
  8404. },
  8405. render: render
  8406. };
  8407. }
  8408. function WebGLBindingStates( gl, extensions, attributes, capabilities ) {
  8409. const maxVertexAttributes = gl.getParameter( 34921 );
  8410. const extension = capabilities.isWebGL2 ? null : extensions.get( 'OES_vertex_array_object' );
  8411. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8412. const bindingStates = {};
  8413. const defaultState = createBindingState( null );
  8414. let currentState = defaultState;
  8415. function setup( object, material, program, geometry, index ) {
  8416. let updateBuffers = false;
  8417. if ( vaoAvailable ) {
  8418. const state = getBindingState( geometry, program, material );
  8419. if ( currentState !== state ) {
  8420. currentState = state;
  8421. bindVertexArrayObject( currentState.object );
  8422. }
  8423. updateBuffers = needsUpdate( geometry, index );
  8424. if ( updateBuffers ) saveCache( geometry, index );
  8425. } else {
  8426. const wireframe = ( material.wireframe === true );
  8427. if ( currentState.geometry !== geometry.id ||
  8428. currentState.program !== program.id ||
  8429. currentState.wireframe !== wireframe ) {
  8430. currentState.geometry = geometry.id;
  8431. currentState.program = program.id;
  8432. currentState.wireframe = wireframe;
  8433. updateBuffers = true;
  8434. }
  8435. }
  8436. if ( object.isInstancedMesh === true ) {
  8437. updateBuffers = true;
  8438. }
  8439. if ( index !== null ) {
  8440. attributes.update( index, 34963 );
  8441. }
  8442. if ( updateBuffers ) {
  8443. setupVertexAttributes( object, material, program, geometry );
  8444. if ( index !== null ) {
  8445. gl.bindBuffer( 34963, attributes.get( index ).buffer );
  8446. }
  8447. }
  8448. }
  8449. function createVertexArrayObject() {
  8450. if ( capabilities.isWebGL2 ) return gl.createVertexArray();
  8451. return extension.createVertexArrayOES();
  8452. }
  8453. function bindVertexArrayObject( vao ) {
  8454. if ( capabilities.isWebGL2 ) return gl.bindVertexArray( vao );
  8455. return extension.bindVertexArrayOES( vao );
  8456. }
  8457. function deleteVertexArrayObject( vao ) {
  8458. if ( capabilities.isWebGL2 ) return gl.deleteVertexArray( vao );
  8459. return extension.deleteVertexArrayOES( vao );
  8460. }
  8461. function getBindingState( geometry, program, material ) {
  8462. const wireframe = ( material.wireframe === true );
  8463. let programMap = bindingStates[ geometry.id ];
  8464. if ( programMap === undefined ) {
  8465. programMap = {};
  8466. bindingStates[ geometry.id ] = programMap;
  8467. }
  8468. let stateMap = programMap[ program.id ];
  8469. if ( stateMap === undefined ) {
  8470. stateMap = {};
  8471. programMap[ program.id ] = stateMap;
  8472. }
  8473. let state = stateMap[ wireframe ];
  8474. if ( state === undefined ) {
  8475. state = createBindingState( createVertexArrayObject() );
  8476. stateMap[ wireframe ] = state;
  8477. }
  8478. return state;
  8479. }
  8480. function createBindingState( vao ) {
  8481. const newAttributes = [];
  8482. const enabledAttributes = [];
  8483. const attributeDivisors = [];
  8484. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  8485. newAttributes[ i ] = 0;
  8486. enabledAttributes[ i ] = 0;
  8487. attributeDivisors[ i ] = 0;
  8488. }
  8489. return {
  8490. // for backward compatibility on non-VAO support browser
  8491. geometry: null,
  8492. program: null,
  8493. wireframe: false,
  8494. newAttributes: newAttributes,
  8495. enabledAttributes: enabledAttributes,
  8496. attributeDivisors: attributeDivisors,
  8497. object: vao,
  8498. attributes: {},
  8499. index: null
  8500. };
  8501. }
  8502. function needsUpdate( geometry, index ) {
  8503. const cachedAttributes = currentState.attributes;
  8504. const geometryAttributes = geometry.attributes;
  8505. let attributesNum = 0;
  8506. for ( const key in geometryAttributes ) {
  8507. const cachedAttribute = cachedAttributes[ key ];
  8508. const geometryAttribute = geometryAttributes[ key ];
  8509. if ( cachedAttribute === undefined ) return true;
  8510. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  8511. if ( cachedAttribute.data !== geometryAttribute.data ) return true;
  8512. attributesNum ++;
  8513. }
  8514. if ( currentState.attributesNum !== attributesNum ) return true;
  8515. if ( currentState.index !== index ) return true;
  8516. return false;
  8517. }
  8518. function saveCache( geometry, index ) {
  8519. const cache = {};
  8520. const attributes = geometry.attributes;
  8521. let attributesNum = 0;
  8522. for ( const key in attributes ) {
  8523. const attribute = attributes[ key ];
  8524. const data = {};
  8525. data.attribute = attribute;
  8526. if ( attribute.data ) {
  8527. data.data = attribute.data;
  8528. }
  8529. cache[ key ] = data;
  8530. attributesNum ++;
  8531. }
  8532. currentState.attributes = cache;
  8533. currentState.attributesNum = attributesNum;
  8534. currentState.index = index;
  8535. }
  8536. function initAttributes() {
  8537. const newAttributes = currentState.newAttributes;
  8538. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  8539. newAttributes[ i ] = 0;
  8540. }
  8541. }
  8542. function enableAttribute( attribute ) {
  8543. enableAttributeAndDivisor( attribute, 0 );
  8544. }
  8545. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  8546. const newAttributes = currentState.newAttributes;
  8547. const enabledAttributes = currentState.enabledAttributes;
  8548. const attributeDivisors = currentState.attributeDivisors;
  8549. newAttributes[ attribute ] = 1;
  8550. if ( enabledAttributes[ attribute ] === 0 ) {
  8551. gl.enableVertexAttribArray( attribute );
  8552. enabledAttributes[ attribute ] = 1;
  8553. }
  8554. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  8555. const extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );
  8556. extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
  8557. attributeDivisors[ attribute ] = meshPerAttribute;
  8558. }
  8559. }
  8560. function disableUnusedAttributes() {
  8561. const newAttributes = currentState.newAttributes;
  8562. const enabledAttributes = currentState.enabledAttributes;
  8563. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  8564. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  8565. gl.disableVertexAttribArray( i );
  8566. enabledAttributes[ i ] = 0;
  8567. }
  8568. }
  8569. }
  8570. function vertexAttribPointer( index, size, type, normalized, stride, offset ) {
  8571. if ( capabilities.isWebGL2 === true && ( type === 5124 || type === 5125 ) ) {
  8572. gl.vertexAttribIPointer( index, size, type, stride, offset );
  8573. } else {
  8574. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  8575. }
  8576. }
  8577. function setupVertexAttributes( object, material, program, geometry ) {
  8578. if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {
  8579. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return;
  8580. }
  8581. initAttributes();
  8582. const geometryAttributes = geometry.attributes;
  8583. const programAttributes = program.getAttributes();
  8584. const materialDefaultAttributeValues = material.defaultAttributeValues;
  8585. for ( const name in programAttributes ) {
  8586. const programAttribute = programAttributes[ name ];
  8587. if ( programAttribute.location >= 0 ) {
  8588. let geometryAttribute = geometryAttributes[ name ];
  8589. if ( geometryAttribute === undefined ) {
  8590. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  8591. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  8592. }
  8593. if ( geometryAttribute !== undefined ) {
  8594. const normalized = geometryAttribute.normalized;
  8595. const size = geometryAttribute.itemSize;
  8596. const attribute = attributes.get( geometryAttribute );
  8597. // TODO Attribute may not be available on context restore
  8598. if ( attribute === undefined ) continue;
  8599. const buffer = attribute.buffer;
  8600. const type = attribute.type;
  8601. const bytesPerElement = attribute.bytesPerElement;
  8602. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  8603. const data = geometryAttribute.data;
  8604. const stride = data.stride;
  8605. const offset = geometryAttribute.offset;
  8606. if ( data && data.isInstancedInterleavedBuffer ) {
  8607. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8608. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  8609. }
  8610. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  8611. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  8612. }
  8613. } else {
  8614. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8615. enableAttribute( programAttribute.location + i );
  8616. }
  8617. }
  8618. gl.bindBuffer( 34962, buffer );
  8619. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8620. vertexAttribPointer(
  8621. programAttribute.location + i,
  8622. size / programAttribute.locationSize,
  8623. type,
  8624. normalized,
  8625. stride * bytesPerElement,
  8626. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement
  8627. );
  8628. }
  8629. } else {
  8630. if ( geometryAttribute.isInstancedBufferAttribute ) {
  8631. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8632. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  8633. }
  8634. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  8635. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  8636. }
  8637. } else {
  8638. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8639. enableAttribute( programAttribute.location + i );
  8640. }
  8641. }
  8642. gl.bindBuffer( 34962, buffer );
  8643. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8644. vertexAttribPointer(
  8645. programAttribute.location + i,
  8646. size / programAttribute.locationSize,
  8647. type,
  8648. normalized,
  8649. size * bytesPerElement,
  8650. ( size / programAttribute.locationSize ) * i * bytesPerElement
  8651. );
  8652. }
  8653. }
  8654. } else if ( materialDefaultAttributeValues !== undefined ) {
  8655. const value = materialDefaultAttributeValues[ name ];
  8656. if ( value !== undefined ) {
  8657. switch ( value.length ) {
  8658. case 2:
  8659. gl.vertexAttrib2fv( programAttribute.location, value );
  8660. break;
  8661. case 3:
  8662. gl.vertexAttrib3fv( programAttribute.location, value );
  8663. break;
  8664. case 4:
  8665. gl.vertexAttrib4fv( programAttribute.location, value );
  8666. break;
  8667. default:
  8668. gl.vertexAttrib1fv( programAttribute.location, value );
  8669. }
  8670. }
  8671. }
  8672. }
  8673. }
  8674. disableUnusedAttributes();
  8675. }
  8676. function dispose() {
  8677. reset();
  8678. for ( const geometryId in bindingStates ) {
  8679. const programMap = bindingStates[ geometryId ];
  8680. for ( const programId in programMap ) {
  8681. const stateMap = programMap[ programId ];
  8682. for ( const wireframe in stateMap ) {
  8683. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8684. delete stateMap[ wireframe ];
  8685. }
  8686. delete programMap[ programId ];
  8687. }
  8688. delete bindingStates[ geometryId ];
  8689. }
  8690. }
  8691. function releaseStatesOfGeometry( geometry ) {
  8692. if ( bindingStates[ geometry.id ] === undefined ) return;
  8693. const programMap = bindingStates[ geometry.id ];
  8694. for ( const programId in programMap ) {
  8695. const stateMap = programMap[ programId ];
  8696. for ( const wireframe in stateMap ) {
  8697. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8698. delete stateMap[ wireframe ];
  8699. }
  8700. delete programMap[ programId ];
  8701. }
  8702. delete bindingStates[ geometry.id ];
  8703. }
  8704. function releaseStatesOfProgram( program ) {
  8705. for ( const geometryId in bindingStates ) {
  8706. const programMap = bindingStates[ geometryId ];
  8707. if ( programMap[ program.id ] === undefined ) continue;
  8708. const stateMap = programMap[ program.id ];
  8709. for ( const wireframe in stateMap ) {
  8710. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8711. delete stateMap[ wireframe ];
  8712. }
  8713. delete programMap[ program.id ];
  8714. }
  8715. }
  8716. function reset() {
  8717. resetDefaultState();
  8718. if ( currentState === defaultState ) return;
  8719. currentState = defaultState;
  8720. bindVertexArrayObject( currentState.object );
  8721. }
  8722. // for backward-compatilibity
  8723. function resetDefaultState() {
  8724. defaultState.geometry = null;
  8725. defaultState.program = null;
  8726. defaultState.wireframe = false;
  8727. }
  8728. return {
  8729. setup: setup,
  8730. reset: reset,
  8731. resetDefaultState: resetDefaultState,
  8732. dispose: dispose,
  8733. releaseStatesOfGeometry: releaseStatesOfGeometry,
  8734. releaseStatesOfProgram: releaseStatesOfProgram,
  8735. initAttributes: initAttributes,
  8736. enableAttribute: enableAttribute,
  8737. disableUnusedAttributes: disableUnusedAttributes
  8738. };
  8739. }
  8740. function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
  8741. const isWebGL2 = capabilities.isWebGL2;
  8742. let mode;
  8743. function setMode( value ) {
  8744. mode = value;
  8745. }
  8746. function render( start, count ) {
  8747. gl.drawArrays( mode, start, count );
  8748. info.update( count, mode, 1 );
  8749. }
  8750. function renderInstances( start, count, primcount ) {
  8751. if ( primcount === 0 ) return;
  8752. let extension, methodName;
  8753. if ( isWebGL2 ) {
  8754. extension = gl;
  8755. methodName = 'drawArraysInstanced';
  8756. } else {
  8757. extension = extensions.get( 'ANGLE_instanced_arrays' );
  8758. methodName = 'drawArraysInstancedANGLE';
  8759. if ( extension === null ) {
  8760. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  8761. return;
  8762. }
  8763. }
  8764. extension[ methodName ]( mode, start, count, primcount );
  8765. info.update( count, mode, primcount );
  8766. }
  8767. //
  8768. this.setMode = setMode;
  8769. this.render = render;
  8770. this.renderInstances = renderInstances;
  8771. }
  8772. function WebGLCapabilities( gl, extensions, parameters ) {
  8773. let maxAnisotropy;
  8774. function getMaxAnisotropy() {
  8775. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  8776. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  8777. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  8778. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  8779. } else {
  8780. maxAnisotropy = 0;
  8781. }
  8782. return maxAnisotropy;
  8783. }
  8784. function getMaxPrecision( precision ) {
  8785. if ( precision === 'highp' ) {
  8786. if ( gl.getShaderPrecisionFormat( 35633, 36338 ).precision > 0 &&
  8787. gl.getShaderPrecisionFormat( 35632, 36338 ).precision > 0 ) {
  8788. return 'highp';
  8789. }
  8790. precision = 'mediump';
  8791. }
  8792. if ( precision === 'mediump' ) {
  8793. if ( gl.getShaderPrecisionFormat( 35633, 36337 ).precision > 0 &&
  8794. gl.getShaderPrecisionFormat( 35632, 36337 ).precision > 0 ) {
  8795. return 'mediump';
  8796. }
  8797. }
  8798. return 'lowp';
  8799. }
  8800. /* eslint-disable no-undef */
  8801. const isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext ) ||
  8802. ( typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext );
  8803. /* eslint-enable no-undef */
  8804. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  8805. const maxPrecision = getMaxPrecision( precision );
  8806. if ( maxPrecision !== precision ) {
  8807. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  8808. precision = maxPrecision;
  8809. }
  8810. const drawBuffers = isWebGL2 || extensions.has( 'WEBGL_draw_buffers' );
  8811. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  8812. const maxTextures = gl.getParameter( 34930 );
  8813. const maxVertexTextures = gl.getParameter( 35660 );
  8814. const maxTextureSize = gl.getParameter( 3379 );
  8815. const maxCubemapSize = gl.getParameter( 34076 );
  8816. const maxAttributes = gl.getParameter( 34921 );
  8817. const maxVertexUniforms = gl.getParameter( 36347 );
  8818. const maxVaryings = gl.getParameter( 36348 );
  8819. const maxFragmentUniforms = gl.getParameter( 36349 );
  8820. const vertexTextures = maxVertexTextures > 0;
  8821. const floatFragmentTextures = isWebGL2 || extensions.has( 'OES_texture_float' );
  8822. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  8823. const maxSamples = isWebGL2 ? gl.getParameter( 36183 ) : 0;
  8824. return {
  8825. isWebGL2: isWebGL2,
  8826. drawBuffers: drawBuffers,
  8827. getMaxAnisotropy: getMaxAnisotropy,
  8828. getMaxPrecision: getMaxPrecision,
  8829. precision: precision,
  8830. logarithmicDepthBuffer: logarithmicDepthBuffer,
  8831. maxTextures: maxTextures,
  8832. maxVertexTextures: maxVertexTextures,
  8833. maxTextureSize: maxTextureSize,
  8834. maxCubemapSize: maxCubemapSize,
  8835. maxAttributes: maxAttributes,
  8836. maxVertexUniforms: maxVertexUniforms,
  8837. maxVaryings: maxVaryings,
  8838. maxFragmentUniforms: maxFragmentUniforms,
  8839. vertexTextures: vertexTextures,
  8840. floatFragmentTextures: floatFragmentTextures,
  8841. floatVertexTextures: floatVertexTextures,
  8842. maxSamples: maxSamples
  8843. };
  8844. }
  8845. function WebGLClipping( properties ) {
  8846. const scope = this;
  8847. let globalState = null,
  8848. numGlobalPlanes = 0,
  8849. localClippingEnabled = false,
  8850. renderingShadows = false;
  8851. const plane = new Plane(),
  8852. viewNormalMatrix = new Matrix3(),
  8853. uniform = { value: null, needsUpdate: false };
  8854. this.uniform = uniform;
  8855. this.numPlanes = 0;
  8856. this.numIntersection = 0;
  8857. this.init = function ( planes, enableLocalClipping, camera ) {
  8858. const enabled =
  8859. planes.length !== 0 ||
  8860. enableLocalClipping ||
  8861. // enable state of previous frame - the clipping code has to
  8862. // run another frame in order to reset the state:
  8863. numGlobalPlanes !== 0 ||
  8864. localClippingEnabled;
  8865. localClippingEnabled = enableLocalClipping;
  8866. globalState = projectPlanes( planes, camera, 0 );
  8867. numGlobalPlanes = planes.length;
  8868. return enabled;
  8869. };
  8870. this.beginShadows = function () {
  8871. renderingShadows = true;
  8872. projectPlanes( null );
  8873. };
  8874. this.endShadows = function () {
  8875. renderingShadows = false;
  8876. resetGlobalState();
  8877. };
  8878. this.setState = function ( material, camera, useCache ) {
  8879. const planes = material.clippingPlanes,
  8880. clipIntersection = material.clipIntersection,
  8881. clipShadows = material.clipShadows;
  8882. const materialProperties = properties.get( material );
  8883. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  8884. // there's no local clipping
  8885. if ( renderingShadows ) {
  8886. // there's no global clipping
  8887. projectPlanes( null );
  8888. } else {
  8889. resetGlobalState();
  8890. }
  8891. } else {
  8892. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  8893. lGlobal = nGlobal * 4;
  8894. let dstArray = materialProperties.clippingState || null;
  8895. uniform.value = dstArray; // ensure unique state
  8896. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  8897. for ( let i = 0; i !== lGlobal; ++ i ) {
  8898. dstArray[ i ] = globalState[ i ];
  8899. }
  8900. materialProperties.clippingState = dstArray;
  8901. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  8902. this.numPlanes += nGlobal;
  8903. }
  8904. };
  8905. function resetGlobalState() {
  8906. if ( uniform.value !== globalState ) {
  8907. uniform.value = globalState;
  8908. uniform.needsUpdate = numGlobalPlanes > 0;
  8909. }
  8910. scope.numPlanes = numGlobalPlanes;
  8911. scope.numIntersection = 0;
  8912. }
  8913. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  8914. const nPlanes = planes !== null ? planes.length : 0;
  8915. let dstArray = null;
  8916. if ( nPlanes !== 0 ) {
  8917. dstArray = uniform.value;
  8918. if ( skipTransform !== true || dstArray === null ) {
  8919. const flatSize = dstOffset + nPlanes * 4,
  8920. viewMatrix = camera.matrixWorldInverse;
  8921. viewNormalMatrix.getNormalMatrix( viewMatrix );
  8922. if ( dstArray === null || dstArray.length < flatSize ) {
  8923. dstArray = new Float32Array( flatSize );
  8924. }
  8925. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  8926. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  8927. plane.normal.toArray( dstArray, i4 );
  8928. dstArray[ i4 + 3 ] = plane.constant;
  8929. }
  8930. }
  8931. uniform.value = dstArray;
  8932. uniform.needsUpdate = true;
  8933. }
  8934. scope.numPlanes = nPlanes;
  8935. scope.numIntersection = 0;
  8936. return dstArray;
  8937. }
  8938. }
  8939. function WebGLCubeMaps( renderer ) {
  8940. let cubemaps = new WeakMap();
  8941. function mapTextureMapping( texture, mapping ) {
  8942. if ( mapping === EquirectangularReflectionMapping ) {
  8943. texture.mapping = CubeReflectionMapping;
  8944. } else if ( mapping === EquirectangularRefractionMapping ) {
  8945. texture.mapping = CubeRefractionMapping;
  8946. }
  8947. return texture;
  8948. }
  8949. function get( texture ) {
  8950. if ( texture && texture.isTexture && texture.isRenderTargetTexture === false ) {
  8951. const mapping = texture.mapping;
  8952. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  8953. if ( cubemaps.has( texture ) ) {
  8954. const cubemap = cubemaps.get( texture ).texture;
  8955. return mapTextureMapping( cubemap, texture.mapping );
  8956. } else {
  8957. const image = texture.image;
  8958. if ( image && image.height > 0 ) {
  8959. const currentRenderTarget = renderer.getRenderTarget();
  8960. const renderTarget = new WebGLCubeRenderTarget( image.height / 2 );
  8961. renderTarget.fromEquirectangularTexture( renderer, texture );
  8962. cubemaps.set( texture, renderTarget );
  8963. renderer.setRenderTarget( currentRenderTarget );
  8964. texture.addEventListener( 'dispose', onTextureDispose );
  8965. return mapTextureMapping( renderTarget.texture, texture.mapping );
  8966. } else {
  8967. // image not yet ready. try the conversion next frame
  8968. return null;
  8969. }
  8970. }
  8971. }
  8972. }
  8973. return texture;
  8974. }
  8975. function onTextureDispose( event ) {
  8976. const texture = event.target;
  8977. texture.removeEventListener( 'dispose', onTextureDispose );
  8978. const cubemap = cubemaps.get( texture );
  8979. if ( cubemap !== undefined ) {
  8980. cubemaps.delete( texture );
  8981. cubemap.dispose();
  8982. }
  8983. }
  8984. function dispose() {
  8985. cubemaps = new WeakMap();
  8986. }
  8987. return {
  8988. get: get,
  8989. dispose: dispose
  8990. };
  8991. }
  8992. class OrthographicCamera extends Camera {
  8993. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  8994. super();
  8995. this.type = 'OrthographicCamera';
  8996. this.zoom = 1;
  8997. this.view = null;
  8998. this.left = left;
  8999. this.right = right;
  9000. this.top = top;
  9001. this.bottom = bottom;
  9002. this.near = near;
  9003. this.far = far;
  9004. this.updateProjectionMatrix();
  9005. }
  9006. copy( source, recursive ) {
  9007. super.copy( source, recursive );
  9008. this.left = source.left;
  9009. this.right = source.right;
  9010. this.top = source.top;
  9011. this.bottom = source.bottom;
  9012. this.near = source.near;
  9013. this.far = source.far;
  9014. this.zoom = source.zoom;
  9015. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9016. return this;
  9017. }
  9018. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  9019. if ( this.view === null ) {
  9020. this.view = {
  9021. enabled: true,
  9022. fullWidth: 1,
  9023. fullHeight: 1,
  9024. offsetX: 0,
  9025. offsetY: 0,
  9026. width: 1,
  9027. height: 1
  9028. };
  9029. }
  9030. this.view.enabled = true;
  9031. this.view.fullWidth = fullWidth;
  9032. this.view.fullHeight = fullHeight;
  9033. this.view.offsetX = x;
  9034. this.view.offsetY = y;
  9035. this.view.width = width;
  9036. this.view.height = height;
  9037. this.updateProjectionMatrix();
  9038. }
  9039. clearViewOffset() {
  9040. if ( this.view !== null ) {
  9041. this.view.enabled = false;
  9042. }
  9043. this.updateProjectionMatrix();
  9044. }
  9045. updateProjectionMatrix() {
  9046. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9047. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9048. const cx = ( this.right + this.left ) / 2;
  9049. const cy = ( this.top + this.bottom ) / 2;
  9050. let left = cx - dx;
  9051. let right = cx + dx;
  9052. let top = cy + dy;
  9053. let bottom = cy - dy;
  9054. if ( this.view !== null && this.view.enabled ) {
  9055. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  9056. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  9057. left += scaleW * this.view.offsetX;
  9058. right = left + scaleW * this.view.width;
  9059. top -= scaleH * this.view.offsetY;
  9060. bottom = top - scaleH * this.view.height;
  9061. }
  9062. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  9063. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  9064. }
  9065. toJSON( meta ) {
  9066. const data = super.toJSON( meta );
  9067. data.object.zoom = this.zoom;
  9068. data.object.left = this.left;
  9069. data.object.right = this.right;
  9070. data.object.top = this.top;
  9071. data.object.bottom = this.bottom;
  9072. data.object.near = this.near;
  9073. data.object.far = this.far;
  9074. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9075. return data;
  9076. }
  9077. }
  9078. OrthographicCamera.prototype.isOrthographicCamera = true;
  9079. class RawShaderMaterial extends ShaderMaterial {
  9080. constructor( parameters ) {
  9081. super( parameters );
  9082. this.type = 'RawShaderMaterial';
  9083. }
  9084. }
  9085. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  9086. const LOD_MIN = 4;
  9087. const LOD_MAX = 8;
  9088. const SIZE_MAX = Math.pow( 2, LOD_MAX );
  9089. // The standard deviations (radians) associated with the extra mips. These are
  9090. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9091. // geometric shadowing function. These sigma values squared must match the
  9092. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9093. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  9094. const TOTAL_LODS = LOD_MAX - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  9095. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  9096. // samples and exit early, but not recompile the shader.
  9097. const MAX_SAMPLES = 20;
  9098. const ENCODINGS = {
  9099. [ LinearEncoding ]: 0,
  9100. [ sRGBEncoding ]: 1,
  9101. [ RGBEEncoding ]: 2,
  9102. [ RGBM7Encoding ]: 3,
  9103. [ RGBM16Encoding ]: 4,
  9104. [ RGBDEncoding ]: 5,
  9105. [ GammaEncoding ]: 6
  9106. };
  9107. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  9108. const { _lodPlanes, _sizeLods, _sigmas } = /*@__PURE__*/ _createPlanes();
  9109. const _clearColor = /*@__PURE__*/ new Color();
  9110. let _oldTarget = null;
  9111. // Golden Ratio
  9112. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  9113. const INV_PHI = 1 / PHI;
  9114. // Vertices of a dodecahedron (except the opposites, which represent the
  9115. // same axis), used as axis directions evenly spread on a sphere.
  9116. const _axisDirections = [
  9117. /*@__PURE__*/ new Vector3( 1, 1, 1 ),
  9118. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  9119. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  9120. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  9121. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  9122. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  9123. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  9124. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  9125. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  9126. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ];
  9127. /**
  9128. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9129. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9130. * blur to be quickly accessed based on material roughness. It is packed into a
  9131. * special CubeUV format that allows us to perform custom interpolation so that
  9132. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9133. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9134. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9135. * higher roughness levels. In this way we maintain resolution to smoothly
  9136. * interpolate diffuse lighting while limiting sampling computation.
  9137. *
  9138. * Paper: Fast, Accurate Image-Based Lighting
  9139. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9140. */
  9141. class PMREMGenerator {
  9142. constructor( renderer ) {
  9143. this._renderer = renderer;
  9144. this._pingPongRenderTarget = null;
  9145. this._blurMaterial = _getBlurShader( MAX_SAMPLES );
  9146. this._equirectShader = null;
  9147. this._cubemapShader = null;
  9148. this._compileMaterial( this._blurMaterial );
  9149. }
  9150. /**
  9151. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9152. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9153. * in radians to be applied to the scene before PMREM generation. Optional near
  9154. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9155. * is placed at the origin).
  9156. */
  9157. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  9158. _oldTarget = this._renderer.getRenderTarget();
  9159. const cubeUVRenderTarget = this._allocateTargets();
  9160. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  9161. if ( sigma > 0 ) {
  9162. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  9163. }
  9164. this._applyPMREM( cubeUVRenderTarget );
  9165. this._cleanup( cubeUVRenderTarget );
  9166. return cubeUVRenderTarget;
  9167. }
  9168. /**
  9169. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9170. * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
  9171. * as this matches best with the 256 x 256 cubemap output.
  9172. */
  9173. fromEquirectangular( equirectangular ) {
  9174. return this._fromTexture( equirectangular );
  9175. }
  9176. /**
  9177. * Generates a PMREM from an cubemap texture, which can be either LDR
  9178. * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
  9179. * as this matches best with the 256 x 256 cubemap output.
  9180. */
  9181. fromCubemap( cubemap ) {
  9182. return this._fromTexture( cubemap );
  9183. }
  9184. /**
  9185. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9186. * your texture's network fetch for increased concurrency.
  9187. */
  9188. compileCubemapShader() {
  9189. if ( this._cubemapShader === null ) {
  9190. this._cubemapShader = _getCubemapShader();
  9191. this._compileMaterial( this._cubemapShader );
  9192. }
  9193. }
  9194. /**
  9195. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9196. * your texture's network fetch for increased concurrency.
  9197. */
  9198. compileEquirectangularShader() {
  9199. if ( this._equirectShader === null ) {
  9200. this._equirectShader = _getEquirectShader();
  9201. this._compileMaterial( this._equirectShader );
  9202. }
  9203. }
  9204. /**
  9205. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9206. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9207. * one of them will cause any others to also become unusable.
  9208. */
  9209. dispose() {
  9210. this._blurMaterial.dispose();
  9211. if ( this._cubemapShader !== null ) this._cubemapShader.dispose();
  9212. if ( this._equirectShader !== null ) this._equirectShader.dispose();
  9213. for ( let i = 0; i < _lodPlanes.length; i ++ ) {
  9214. _lodPlanes[ i ].dispose();
  9215. }
  9216. }
  9217. // private interface
  9218. _cleanup( outputTarget ) {
  9219. this._pingPongRenderTarget.dispose();
  9220. this._renderer.setRenderTarget( _oldTarget );
  9221. outputTarget.scissorTest = false;
  9222. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  9223. }
  9224. _fromTexture( texture ) {
  9225. _oldTarget = this._renderer.getRenderTarget();
  9226. const cubeUVRenderTarget = this._allocateTargets( texture );
  9227. this._textureToCubeUV( texture, cubeUVRenderTarget );
  9228. this._applyPMREM( cubeUVRenderTarget );
  9229. this._cleanup( cubeUVRenderTarget );
  9230. return cubeUVRenderTarget;
  9231. }
  9232. _allocateTargets( texture ) { // warning: null texture is valid
  9233. const params = {
  9234. magFilter: NearestFilter,
  9235. minFilter: NearestFilter,
  9236. generateMipmaps: false,
  9237. type: UnsignedByteType,
  9238. format: RGBEFormat,
  9239. encoding: _isLDR( texture ) ? texture.encoding : RGBEEncoding,
  9240. depthBuffer: false
  9241. };
  9242. const cubeUVRenderTarget = _createRenderTarget( params );
  9243. cubeUVRenderTarget.depthBuffer = texture ? false : true;
  9244. this._pingPongRenderTarget = _createRenderTarget( params );
  9245. return cubeUVRenderTarget;
  9246. }
  9247. _compileMaterial( material ) {
  9248. const tmpMesh = new Mesh( _lodPlanes[ 0 ], material );
  9249. this._renderer.compile( tmpMesh, _flatCamera );
  9250. }
  9251. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  9252. const fov = 90;
  9253. const aspect = 1;
  9254. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  9255. const upSign = [ 1, - 1, 1, 1, 1, 1 ];
  9256. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  9257. const renderer = this._renderer;
  9258. const originalAutoClear = renderer.autoClear;
  9259. const outputEncoding = renderer.outputEncoding;
  9260. const toneMapping = renderer.toneMapping;
  9261. renderer.getClearColor( _clearColor );
  9262. renderer.toneMapping = NoToneMapping;
  9263. renderer.outputEncoding = LinearEncoding;
  9264. renderer.autoClear = false;
  9265. const backgroundMaterial = new MeshBasicMaterial( {
  9266. name: 'PMREM.Background',
  9267. side: BackSide,
  9268. depthWrite: false,
  9269. depthTest: false,
  9270. } );
  9271. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  9272. let useSolidColor = false;
  9273. const background = scene.background;
  9274. if ( background ) {
  9275. if ( background.isColor ) {
  9276. backgroundMaterial.color.copy( background );
  9277. scene.background = null;
  9278. useSolidColor = true;
  9279. }
  9280. } else {
  9281. backgroundMaterial.color.copy( _clearColor );
  9282. useSolidColor = true;
  9283. }
  9284. for ( let i = 0; i < 6; i ++ ) {
  9285. const col = i % 3;
  9286. if ( col == 0 ) {
  9287. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9288. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  9289. } else if ( col == 1 ) {
  9290. cubeCamera.up.set( 0, 0, upSign[ i ] );
  9291. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  9292. } else {
  9293. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9294. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  9295. }
  9296. _setViewport( cubeUVRenderTarget,
  9297. col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX );
  9298. renderer.setRenderTarget( cubeUVRenderTarget );
  9299. if ( useSolidColor ) {
  9300. renderer.render( backgroundBox, cubeCamera );
  9301. }
  9302. renderer.render( scene, cubeCamera );
  9303. }
  9304. backgroundBox.geometry.dispose();
  9305. backgroundBox.material.dispose();
  9306. renderer.toneMapping = toneMapping;
  9307. renderer.outputEncoding = outputEncoding;
  9308. renderer.autoClear = originalAutoClear;
  9309. scene.background = background;
  9310. }
  9311. _setEncoding( uniform, texture ) {
  9312. if ( this._renderer.capabilities.isWebGL2 === true && texture.format === RGBAFormat && texture.type === UnsignedByteType && texture.encoding === sRGBEncoding ) {
  9313. uniform.value = ENCODINGS[ LinearEncoding ];
  9314. } else {
  9315. uniform.value = ENCODINGS[ texture.encoding ];
  9316. }
  9317. }
  9318. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  9319. const renderer = this._renderer;
  9320. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  9321. if ( isCubeTexture ) {
  9322. if ( this._cubemapShader == null ) {
  9323. this._cubemapShader = _getCubemapShader();
  9324. }
  9325. } else {
  9326. if ( this._equirectShader == null ) {
  9327. this._equirectShader = _getEquirectShader();
  9328. }
  9329. }
  9330. const material = isCubeTexture ? this._cubemapShader : this._equirectShader;
  9331. const mesh = new Mesh( _lodPlanes[ 0 ], material );
  9332. const uniforms = material.uniforms;
  9333. uniforms[ 'envMap' ].value = texture;
  9334. if ( ! isCubeTexture ) {
  9335. uniforms[ 'texelSize' ].value.set( 1.0 / texture.image.width, 1.0 / texture.image.height );
  9336. }
  9337. this._setEncoding( uniforms[ 'inputEncoding' ], texture );
  9338. this._setEncoding( uniforms[ 'outputEncoding' ], cubeUVRenderTarget.texture );
  9339. _setViewport( cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX );
  9340. renderer.setRenderTarget( cubeUVRenderTarget );
  9341. renderer.render( mesh, _flatCamera );
  9342. }
  9343. _applyPMREM( cubeUVRenderTarget ) {
  9344. const renderer = this._renderer;
  9345. const autoClear = renderer.autoClear;
  9346. renderer.autoClear = false;
  9347. for ( let i = 1; i < TOTAL_LODS; i ++ ) {
  9348. const sigma = Math.sqrt( _sigmas[ i ] * _sigmas[ i ] - _sigmas[ i - 1 ] * _sigmas[ i - 1 ] );
  9349. const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ];
  9350. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  9351. }
  9352. renderer.autoClear = autoClear;
  9353. }
  9354. /**
  9355. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  9356. * vertically and horizontally, but this breaks down on a cube. Here we apply
  9357. * the blur latitudinally (around the poles), and then longitudinally (towards
  9358. * the poles) to approximate the orthogonally-separable blur. It is least
  9359. * accurate at the poles, but still does a decent job.
  9360. */
  9361. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  9362. const pingPongRenderTarget = this._pingPongRenderTarget;
  9363. this._halfBlur(
  9364. cubeUVRenderTarget,
  9365. pingPongRenderTarget,
  9366. lodIn,
  9367. lodOut,
  9368. sigma,
  9369. 'latitudinal',
  9370. poleAxis );
  9371. this._halfBlur(
  9372. pingPongRenderTarget,
  9373. cubeUVRenderTarget,
  9374. lodOut,
  9375. lodOut,
  9376. sigma,
  9377. 'longitudinal',
  9378. poleAxis );
  9379. }
  9380. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  9381. const renderer = this._renderer;
  9382. const blurMaterial = this._blurMaterial;
  9383. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  9384. console.error(
  9385. 'blur direction must be either latitudinal or longitudinal!' );
  9386. }
  9387. // Number of standard deviations at which to cut off the discrete approximation.
  9388. const STANDARD_DEVIATIONS = 3;
  9389. const blurMesh = new Mesh( _lodPlanes[ lodOut ], blurMaterial );
  9390. const blurUniforms = blurMaterial.uniforms;
  9391. const pixels = _sizeLods[ lodIn ] - 1;
  9392. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  9393. const sigmaPixels = sigmaRadians / radiansPerPixel;
  9394. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  9395. if ( samples > MAX_SAMPLES ) {
  9396. console.warn( `sigmaRadians, ${
  9397. sigmaRadians}, is too large and will clip, as it requested ${
  9398. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  9399. }
  9400. const weights = [];
  9401. let sum = 0;
  9402. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  9403. const x = i / sigmaPixels;
  9404. const weight = Math.exp( - x * x / 2 );
  9405. weights.push( weight );
  9406. if ( i == 0 ) {
  9407. sum += weight;
  9408. } else if ( i < samples ) {
  9409. sum += 2 * weight;
  9410. }
  9411. }
  9412. for ( let i = 0; i < weights.length; i ++ ) {
  9413. weights[ i ] = weights[ i ] / sum;
  9414. }
  9415. blurUniforms[ 'envMap' ].value = targetIn.texture;
  9416. blurUniforms[ 'samples' ].value = samples;
  9417. blurUniforms[ 'weights' ].value = weights;
  9418. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  9419. if ( poleAxis ) {
  9420. blurUniforms[ 'poleAxis' ].value = poleAxis;
  9421. }
  9422. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  9423. blurUniforms[ 'mipInt' ].value = LOD_MAX - lodIn;
  9424. this._setEncoding( blurUniforms[ 'inputEncoding' ], targetIn.texture );
  9425. this._setEncoding( blurUniforms[ 'outputEncoding' ], targetIn.texture );
  9426. const outputSize = _sizeLods[ lodOut ];
  9427. const x = 3 * Math.max( 0, SIZE_MAX - 2 * outputSize );
  9428. const y = ( lodOut === 0 ? 0 : 2 * SIZE_MAX ) + 2 * outputSize * ( lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0 );
  9429. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  9430. renderer.setRenderTarget( targetOut );
  9431. renderer.render( blurMesh, _flatCamera );
  9432. }
  9433. }
  9434. function _isLDR( texture ) {
  9435. if ( texture === undefined || texture.type !== UnsignedByteType ) return false;
  9436. return texture.encoding === LinearEncoding || texture.encoding === sRGBEncoding || texture.encoding === GammaEncoding;
  9437. }
  9438. function _createPlanes() {
  9439. const _lodPlanes = [];
  9440. const _sizeLods = [];
  9441. const _sigmas = [];
  9442. let lod = LOD_MAX;
  9443. for ( let i = 0; i < TOTAL_LODS; i ++ ) {
  9444. const sizeLod = Math.pow( 2, lod );
  9445. _sizeLods.push( sizeLod );
  9446. let sigma = 1.0 / sizeLod;
  9447. if ( i > LOD_MAX - LOD_MIN ) {
  9448. sigma = EXTRA_LOD_SIGMA[ i - LOD_MAX + LOD_MIN - 1 ];
  9449. } else if ( i == 0 ) {
  9450. sigma = 0;
  9451. }
  9452. _sigmas.push( sigma );
  9453. const texelSize = 1.0 / ( sizeLod - 1 );
  9454. const min = - texelSize / 2;
  9455. const max = 1 + texelSize / 2;
  9456. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  9457. const cubeFaces = 6;
  9458. const vertices = 6;
  9459. const positionSize = 3;
  9460. const uvSize = 2;
  9461. const faceIndexSize = 1;
  9462. const position = new Float32Array( positionSize * vertices * cubeFaces );
  9463. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  9464. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  9465. for ( let face = 0; face < cubeFaces; face ++ ) {
  9466. const x = ( face % 3 ) * 2 / 3 - 1;
  9467. const y = face > 2 ? 0 : - 1;
  9468. const coordinates = [
  9469. x, y, 0,
  9470. x + 2 / 3, y, 0,
  9471. x + 2 / 3, y + 1, 0,
  9472. x, y, 0,
  9473. x + 2 / 3, y + 1, 0,
  9474. x, y + 1, 0
  9475. ];
  9476. position.set( coordinates, positionSize * vertices * face );
  9477. uv.set( uv1, uvSize * vertices * face );
  9478. const fill = [ face, face, face, face, face, face ];
  9479. faceIndex.set( fill, faceIndexSize * vertices * face );
  9480. }
  9481. const planes = new BufferGeometry();
  9482. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  9483. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  9484. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  9485. _lodPlanes.push( planes );
  9486. if ( lod > LOD_MIN ) {
  9487. lod --;
  9488. }
  9489. }
  9490. return { _lodPlanes, _sizeLods, _sigmas };
  9491. }
  9492. function _createRenderTarget( params ) {
  9493. const cubeUVRenderTarget = new WebGLRenderTarget( 3 * SIZE_MAX, 3 * SIZE_MAX, params );
  9494. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  9495. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  9496. cubeUVRenderTarget.scissorTest = true;
  9497. return cubeUVRenderTarget;
  9498. }
  9499. function _setViewport( target, x, y, width, height ) {
  9500. target.viewport.set( x, y, width, height );
  9501. target.scissor.set( x, y, width, height );
  9502. }
  9503. function _getBlurShader( maxSamples ) {
  9504. const weights = new Float32Array( maxSamples );
  9505. const poleAxis = new Vector3( 0, 1, 0 );
  9506. const shaderMaterial = new RawShaderMaterial( {
  9507. name: 'SphericalGaussianBlur',
  9508. defines: { 'n': maxSamples },
  9509. uniforms: {
  9510. 'envMap': { value: null },
  9511. 'samples': { value: 1 },
  9512. 'weights': { value: weights },
  9513. 'latitudinal': { value: false },
  9514. 'dTheta': { value: 0 },
  9515. 'mipInt': { value: 0 },
  9516. 'poleAxis': { value: poleAxis },
  9517. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  9518. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  9519. },
  9520. vertexShader: _getCommonVertexShader(),
  9521. fragmentShader: /* glsl */`
  9522. precision mediump float;
  9523. precision mediump int;
  9524. varying vec3 vOutputDirection;
  9525. uniform sampler2D envMap;
  9526. uniform int samples;
  9527. uniform float weights[ n ];
  9528. uniform bool latitudinal;
  9529. uniform float dTheta;
  9530. uniform float mipInt;
  9531. uniform vec3 poleAxis;
  9532. ${ _getEncodings() }
  9533. #define ENVMAP_TYPE_CUBE_UV
  9534. #include <cube_uv_reflection_fragment>
  9535. vec3 getSample( float theta, vec3 axis ) {
  9536. float cosTheta = cos( theta );
  9537. // Rodrigues' axis-angle rotation
  9538. vec3 sampleDirection = vOutputDirection * cosTheta
  9539. + cross( axis, vOutputDirection ) * sin( theta )
  9540. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  9541. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  9542. }
  9543. void main() {
  9544. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  9545. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  9546. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  9547. }
  9548. axis = normalize( axis );
  9549. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9550. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  9551. for ( int i = 1; i < n; i++ ) {
  9552. if ( i >= samples ) {
  9553. break;
  9554. }
  9555. float theta = dTheta * float( i );
  9556. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  9557. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  9558. }
  9559. gl_FragColor = linearToOutputTexel( gl_FragColor );
  9560. }
  9561. `,
  9562. blending: NoBlending,
  9563. depthTest: false,
  9564. depthWrite: false
  9565. } );
  9566. return shaderMaterial;
  9567. }
  9568. function _getEquirectShader() {
  9569. const texelSize = new Vector2( 1, 1 );
  9570. const shaderMaterial = new RawShaderMaterial( {
  9571. name: 'EquirectangularToCubeUV',
  9572. uniforms: {
  9573. 'envMap': { value: null },
  9574. 'texelSize': { value: texelSize },
  9575. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  9576. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  9577. },
  9578. vertexShader: _getCommonVertexShader(),
  9579. fragmentShader: /* glsl */`
  9580. precision mediump float;
  9581. precision mediump int;
  9582. varying vec3 vOutputDirection;
  9583. uniform sampler2D envMap;
  9584. uniform vec2 texelSize;
  9585. ${ _getEncodings() }
  9586. #include <common>
  9587. void main() {
  9588. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9589. vec3 outputDirection = normalize( vOutputDirection );
  9590. vec2 uv = equirectUv( outputDirection );
  9591. vec2 f = fract( uv / texelSize - 0.5 );
  9592. uv -= f * texelSize;
  9593. vec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9594. uv.x += texelSize.x;
  9595. vec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9596. uv.y += texelSize.y;
  9597. vec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9598. uv.x -= texelSize.x;
  9599. vec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9600. vec3 tm = mix( tl, tr, f.x );
  9601. vec3 bm = mix( bl, br, f.x );
  9602. gl_FragColor.rgb = mix( tm, bm, f.y );
  9603. gl_FragColor = linearToOutputTexel( gl_FragColor );
  9604. }
  9605. `,
  9606. blending: NoBlending,
  9607. depthTest: false,
  9608. depthWrite: false
  9609. } );
  9610. return shaderMaterial;
  9611. }
  9612. function _getCubemapShader() {
  9613. const shaderMaterial = new RawShaderMaterial( {
  9614. name: 'CubemapToCubeUV',
  9615. uniforms: {
  9616. 'envMap': { value: null },
  9617. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  9618. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  9619. },
  9620. vertexShader: _getCommonVertexShader(),
  9621. fragmentShader: /* glsl */`
  9622. precision mediump float;
  9623. precision mediump int;
  9624. varying vec3 vOutputDirection;
  9625. uniform samplerCube envMap;
  9626. ${ _getEncodings() }
  9627. void main() {
  9628. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9629. gl_FragColor.rgb = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) ).rgb;
  9630. gl_FragColor = linearToOutputTexel( gl_FragColor );
  9631. }
  9632. `,
  9633. blending: NoBlending,
  9634. depthTest: false,
  9635. depthWrite: false
  9636. } );
  9637. return shaderMaterial;
  9638. }
  9639. function _getCommonVertexShader() {
  9640. return /* glsl */`
  9641. precision mediump float;
  9642. precision mediump int;
  9643. attribute vec3 position;
  9644. attribute vec2 uv;
  9645. attribute float faceIndex;
  9646. varying vec3 vOutputDirection;
  9647. // RH coordinate system; PMREM face-indexing convention
  9648. vec3 getDirection( vec2 uv, float face ) {
  9649. uv = 2.0 * uv - 1.0;
  9650. vec3 direction = vec3( uv, 1.0 );
  9651. if ( face == 0.0 ) {
  9652. direction = direction.zyx; // ( 1, v, u ) pos x
  9653. } else if ( face == 1.0 ) {
  9654. direction = direction.xzy;
  9655. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  9656. } else if ( face == 2.0 ) {
  9657. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  9658. } else if ( face == 3.0 ) {
  9659. direction = direction.zyx;
  9660. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  9661. } else if ( face == 4.0 ) {
  9662. direction = direction.xzy;
  9663. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  9664. } else if ( face == 5.0 ) {
  9665. direction.z *= -1.0; // ( u, v, -1 ) neg z
  9666. }
  9667. return direction;
  9668. }
  9669. void main() {
  9670. vOutputDirection = getDirection( uv, faceIndex );
  9671. gl_Position = vec4( position, 1.0 );
  9672. }
  9673. `;
  9674. }
  9675. function _getEncodings() {
  9676. return /* glsl */`
  9677. uniform int inputEncoding;
  9678. uniform int outputEncoding;
  9679. #include <encodings_pars_fragment>
  9680. vec4 inputTexelToLinear( vec4 value ) {
  9681. if ( inputEncoding == 0 ) {
  9682. return value;
  9683. } else if ( inputEncoding == 1 ) {
  9684. return sRGBToLinear( value );
  9685. } else if ( inputEncoding == 2 ) {
  9686. return RGBEToLinear( value );
  9687. } else if ( inputEncoding == 3 ) {
  9688. return RGBMToLinear( value, 7.0 );
  9689. } else if ( inputEncoding == 4 ) {
  9690. return RGBMToLinear( value, 16.0 );
  9691. } else if ( inputEncoding == 5 ) {
  9692. return RGBDToLinear( value, 256.0 );
  9693. } else {
  9694. return GammaToLinear( value, 2.2 );
  9695. }
  9696. }
  9697. vec4 linearToOutputTexel( vec4 value ) {
  9698. if ( outputEncoding == 0 ) {
  9699. return value;
  9700. } else if ( outputEncoding == 1 ) {
  9701. return LinearTosRGB( value );
  9702. } else if ( outputEncoding == 2 ) {
  9703. return LinearToRGBE( value );
  9704. } else if ( outputEncoding == 3 ) {
  9705. return LinearToRGBM( value, 7.0 );
  9706. } else if ( outputEncoding == 4 ) {
  9707. return LinearToRGBM( value, 16.0 );
  9708. } else if ( outputEncoding == 5 ) {
  9709. return LinearToRGBD( value, 256.0 );
  9710. } else {
  9711. return LinearToGamma( value, 2.2 );
  9712. }
  9713. }
  9714. vec4 envMapTexelToLinear( vec4 color ) {
  9715. return inputTexelToLinear( color );
  9716. }
  9717. `;
  9718. }
  9719. function WebGLCubeUVMaps( renderer ) {
  9720. let cubeUVmaps = new WeakMap();
  9721. let pmremGenerator = null;
  9722. function get( texture ) {
  9723. if ( texture && texture.isTexture && texture.isRenderTargetTexture === false ) {
  9724. const mapping = texture.mapping;
  9725. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  9726. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  9727. if ( isEquirectMap || isCubeMap ) {
  9728. // equirect/cube map to cubeUV conversion
  9729. if ( cubeUVmaps.has( texture ) ) {
  9730. return cubeUVmaps.get( texture ).texture;
  9731. } else {
  9732. const image = texture.image;
  9733. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  9734. const currentRenderTarget = renderer.getRenderTarget();
  9735. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  9736. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  9737. cubeUVmaps.set( texture, renderTarget );
  9738. renderer.setRenderTarget( currentRenderTarget );
  9739. texture.addEventListener( 'dispose', onTextureDispose );
  9740. return renderTarget.texture;
  9741. } else {
  9742. // image not yet ready. try the conversion next frame
  9743. return null;
  9744. }
  9745. }
  9746. }
  9747. }
  9748. return texture;
  9749. }
  9750. function isCubeTextureComplete( image ) {
  9751. let count = 0;
  9752. const length = 6;
  9753. for ( let i = 0; i < length; i ++ ) {
  9754. if ( image[ i ] !== undefined ) count ++;
  9755. }
  9756. return count === length;
  9757. }
  9758. function onTextureDispose( event ) {
  9759. const texture = event.target;
  9760. texture.removeEventListener( 'dispose', onTextureDispose );
  9761. const cubemapUV = cubeUVmaps.get( texture );
  9762. if ( cubemapUV !== undefined ) {
  9763. cubeUVmaps.delete( texture );
  9764. cubemapUV.dispose();
  9765. }
  9766. }
  9767. function dispose() {
  9768. cubeUVmaps = new WeakMap();
  9769. if ( pmremGenerator !== null ) {
  9770. pmremGenerator.dispose();
  9771. pmremGenerator = null;
  9772. }
  9773. }
  9774. return {
  9775. get: get,
  9776. dispose: dispose
  9777. };
  9778. }
  9779. function WebGLExtensions( gl ) {
  9780. const extensions = {};
  9781. function getExtension( name ) {
  9782. if ( extensions[ name ] !== undefined ) {
  9783. return extensions[ name ];
  9784. }
  9785. let extension;
  9786. switch ( name ) {
  9787. case 'WEBGL_depth_texture':
  9788. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  9789. break;
  9790. case 'EXT_texture_filter_anisotropic':
  9791. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  9792. break;
  9793. case 'WEBGL_compressed_texture_s3tc':
  9794. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  9795. break;
  9796. case 'WEBGL_compressed_texture_pvrtc':
  9797. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  9798. break;
  9799. default:
  9800. extension = gl.getExtension( name );
  9801. }
  9802. extensions[ name ] = extension;
  9803. return extension;
  9804. }
  9805. return {
  9806. has: function ( name ) {
  9807. return getExtension( name ) !== null;
  9808. },
  9809. init: function ( capabilities ) {
  9810. if ( capabilities.isWebGL2 ) {
  9811. getExtension( 'EXT_color_buffer_float' );
  9812. } else {
  9813. getExtension( 'WEBGL_depth_texture' );
  9814. getExtension( 'OES_texture_float' );
  9815. getExtension( 'OES_texture_half_float' );
  9816. getExtension( 'OES_texture_half_float_linear' );
  9817. getExtension( 'OES_standard_derivatives' );
  9818. getExtension( 'OES_element_index_uint' );
  9819. getExtension( 'OES_vertex_array_object' );
  9820. getExtension( 'ANGLE_instanced_arrays' );
  9821. }
  9822. getExtension( 'OES_texture_float_linear' );
  9823. getExtension( 'EXT_color_buffer_half_float' );
  9824. },
  9825. get: function ( name ) {
  9826. const extension = getExtension( name );
  9827. if ( extension === null ) {
  9828. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  9829. }
  9830. return extension;
  9831. }
  9832. };
  9833. }
  9834. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  9835. const geometries = {};
  9836. const wireframeAttributes = new WeakMap();
  9837. function onGeometryDispose( event ) {
  9838. const geometry = event.target;
  9839. if ( geometry.index !== null ) {
  9840. attributes.remove( geometry.index );
  9841. }
  9842. for ( const name in geometry.attributes ) {
  9843. attributes.remove( geometry.attributes[ name ] );
  9844. }
  9845. geometry.removeEventListener( 'dispose', onGeometryDispose );
  9846. delete geometries[ geometry.id ];
  9847. const attribute = wireframeAttributes.get( geometry );
  9848. if ( attribute ) {
  9849. attributes.remove( attribute );
  9850. wireframeAttributes.delete( geometry );
  9851. }
  9852. bindingStates.releaseStatesOfGeometry( geometry );
  9853. if ( geometry.isInstancedBufferGeometry === true ) {
  9854. delete geometry._maxInstanceCount;
  9855. }
  9856. //
  9857. info.memory.geometries --;
  9858. }
  9859. function get( object, geometry ) {
  9860. if ( geometries[ geometry.id ] === true ) return geometry;
  9861. geometry.addEventListener( 'dispose', onGeometryDispose );
  9862. geometries[ geometry.id ] = true;
  9863. info.memory.geometries ++;
  9864. return geometry;
  9865. }
  9866. function update( geometry ) {
  9867. const geometryAttributes = geometry.attributes;
  9868. // Updating index buffer in VAO now. See WebGLBindingStates.
  9869. for ( const name in geometryAttributes ) {
  9870. attributes.update( geometryAttributes[ name ], 34962 );
  9871. }
  9872. // morph targets
  9873. const morphAttributes = geometry.morphAttributes;
  9874. for ( const name in morphAttributes ) {
  9875. const array = morphAttributes[ name ];
  9876. for ( let i = 0, l = array.length; i < l; i ++ ) {
  9877. attributes.update( array[ i ], 34962 );
  9878. }
  9879. }
  9880. }
  9881. function updateWireframeAttribute( geometry ) {
  9882. const indices = [];
  9883. const geometryIndex = geometry.index;
  9884. const geometryPosition = geometry.attributes.position;
  9885. let version = 0;
  9886. if ( geometryIndex !== null ) {
  9887. const array = geometryIndex.array;
  9888. version = geometryIndex.version;
  9889. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  9890. const a = array[ i + 0 ];
  9891. const b = array[ i + 1 ];
  9892. const c = array[ i + 2 ];
  9893. indices.push( a, b, b, c, c, a );
  9894. }
  9895. } else {
  9896. const array = geometryPosition.array;
  9897. version = geometryPosition.version;
  9898. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  9899. const a = i + 0;
  9900. const b = i + 1;
  9901. const c = i + 2;
  9902. indices.push( a, b, b, c, c, a );
  9903. }
  9904. }
  9905. const attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  9906. attribute.version = version;
  9907. // Updating index buffer in VAO now. See WebGLBindingStates
  9908. //
  9909. const previousAttribute = wireframeAttributes.get( geometry );
  9910. if ( previousAttribute ) attributes.remove( previousAttribute );
  9911. //
  9912. wireframeAttributes.set( geometry, attribute );
  9913. }
  9914. function getWireframeAttribute( geometry ) {
  9915. const currentAttribute = wireframeAttributes.get( geometry );
  9916. if ( currentAttribute ) {
  9917. const geometryIndex = geometry.index;
  9918. if ( geometryIndex !== null ) {
  9919. // if the attribute is obsolete, create a new one
  9920. if ( currentAttribute.version < geometryIndex.version ) {
  9921. updateWireframeAttribute( geometry );
  9922. }
  9923. }
  9924. } else {
  9925. updateWireframeAttribute( geometry );
  9926. }
  9927. return wireframeAttributes.get( geometry );
  9928. }
  9929. return {
  9930. get: get,
  9931. update: update,
  9932. getWireframeAttribute: getWireframeAttribute
  9933. };
  9934. }
  9935. function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {
  9936. const isWebGL2 = capabilities.isWebGL2;
  9937. let mode;
  9938. function setMode( value ) {
  9939. mode = value;
  9940. }
  9941. let type, bytesPerElement;
  9942. function setIndex( value ) {
  9943. type = value.type;
  9944. bytesPerElement = value.bytesPerElement;
  9945. }
  9946. function render( start, count ) {
  9947. gl.drawElements( mode, count, type, start * bytesPerElement );
  9948. info.update( count, mode, 1 );
  9949. }
  9950. function renderInstances( start, count, primcount ) {
  9951. if ( primcount === 0 ) return;
  9952. let extension, methodName;
  9953. if ( isWebGL2 ) {
  9954. extension = gl;
  9955. methodName = 'drawElementsInstanced';
  9956. } else {
  9957. extension = extensions.get( 'ANGLE_instanced_arrays' );
  9958. methodName = 'drawElementsInstancedANGLE';
  9959. if ( extension === null ) {
  9960. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9961. return;
  9962. }
  9963. }
  9964. extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount );
  9965. info.update( count, mode, primcount );
  9966. }
  9967. //
  9968. this.setMode = setMode;
  9969. this.setIndex = setIndex;
  9970. this.render = render;
  9971. this.renderInstances = renderInstances;
  9972. }
  9973. function WebGLInfo( gl ) {
  9974. const memory = {
  9975. geometries: 0,
  9976. textures: 0
  9977. };
  9978. const render = {
  9979. frame: 0,
  9980. calls: 0,
  9981. triangles: 0,
  9982. points: 0,
  9983. lines: 0
  9984. };
  9985. function update( count, mode, instanceCount ) {
  9986. render.calls ++;
  9987. switch ( mode ) {
  9988. case 4:
  9989. render.triangles += instanceCount * ( count / 3 );
  9990. break;
  9991. case 1:
  9992. render.lines += instanceCount * ( count / 2 );
  9993. break;
  9994. case 3:
  9995. render.lines += instanceCount * ( count - 1 );
  9996. break;
  9997. case 2:
  9998. render.lines += instanceCount * count;
  9999. break;
  10000. case 0:
  10001. render.points += instanceCount * count;
  10002. break;
  10003. default:
  10004. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  10005. break;
  10006. }
  10007. }
  10008. function reset() {
  10009. render.frame ++;
  10010. render.calls = 0;
  10011. render.triangles = 0;
  10012. render.points = 0;
  10013. render.lines = 0;
  10014. }
  10015. return {
  10016. memory: memory,
  10017. render: render,
  10018. programs: null,
  10019. autoReset: true,
  10020. reset: reset,
  10021. update: update
  10022. };
  10023. }
  10024. class DataTexture2DArray extends Texture {
  10025. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  10026. super( null );
  10027. this.image = { data, width, height, depth };
  10028. this.magFilter = NearestFilter;
  10029. this.minFilter = NearestFilter;
  10030. this.wrapR = ClampToEdgeWrapping;
  10031. this.generateMipmaps = false;
  10032. this.flipY = false;
  10033. this.unpackAlignment = 1;
  10034. this.needsUpdate = true;
  10035. }
  10036. }
  10037. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  10038. function numericalSort( a, b ) {
  10039. return a[ 0 ] - b[ 0 ];
  10040. }
  10041. function absNumericalSort( a, b ) {
  10042. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  10043. }
  10044. function denormalize( morph, attribute ) {
  10045. let denominator = 1;
  10046. const array = attribute.isInterleavedBufferAttribute ? attribute.data.array : attribute.array;
  10047. if ( array instanceof Int8Array ) denominator = 127;
  10048. else if ( array instanceof Int16Array ) denominator = 32767;
  10049. else if ( array instanceof Int32Array ) denominator = 2147483647;
  10050. else console.error( 'THREE.WebGLMorphtargets: Unsupported morph attribute data type: ', array );
  10051. morph.divideScalar( denominator );
  10052. }
  10053. function WebGLMorphtargets( gl, capabilities, textures ) {
  10054. const influencesList = {};
  10055. const morphInfluences = new Float32Array( 8 );
  10056. const morphTextures = new WeakMap();
  10057. const morph = new Vector3();
  10058. const workInfluences = [];
  10059. for ( let i = 0; i < 8; i ++ ) {
  10060. workInfluences[ i ] = [ i, 0 ];
  10061. }
  10062. function update( object, geometry, material, program ) {
  10063. const objectInfluences = object.morphTargetInfluences;
  10064. if ( capabilities.isWebGL2 === true ) {
  10065. // instead of using attributes, the WebGL 2 code path encodes morph targets
  10066. // into an array of data textures. Each layer represents a single morph target.
  10067. const numberOfMorphTargets = geometry.morphAttributes.position.length;
  10068. let entry = morphTextures.get( geometry );
  10069. if ( entry === undefined || entry.count !== numberOfMorphTargets ) {
  10070. if ( entry !== undefined ) entry.texture.dispose();
  10071. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10072. const morphTargets = geometry.morphAttributes.position;
  10073. const morphNormals = geometry.morphAttributes.normal || [];
  10074. const numberOfVertices = geometry.attributes.position.count;
  10075. const numberOfVertexData = ( hasMorphNormals === true ) ? 2 : 1; // (v,n) vs. (v)
  10076. let width = numberOfVertices * numberOfVertexData;
  10077. let height = 1;
  10078. if ( width > capabilities.maxTextureSize ) {
  10079. height = Math.ceil( width / capabilities.maxTextureSize );
  10080. width = capabilities.maxTextureSize;
  10081. }
  10082. const buffer = new Float32Array( width * height * 4 * numberOfMorphTargets );
  10083. const texture = new DataTexture2DArray( buffer, width, height, numberOfMorphTargets );
  10084. texture.format = RGBAFormat; // using RGBA since RGB might be emulated (and is thus slower)
  10085. texture.type = FloatType;
  10086. // fill buffer
  10087. const vertexDataStride = numberOfVertexData * 4;
  10088. for ( let i = 0; i < numberOfMorphTargets; i ++ ) {
  10089. const morphTarget = morphTargets[ i ];
  10090. const morphNormal = morphNormals[ i ];
  10091. const offset = width * height * 4 * i;
  10092. for ( let j = 0; j < morphTarget.count; j ++ ) {
  10093. morph.fromBufferAttribute( morphTarget, j );
  10094. if ( morphTarget.normalized === true ) denormalize( morph, morphTarget );
  10095. const stride = j * vertexDataStride;
  10096. buffer[ offset + stride + 0 ] = morph.x;
  10097. buffer[ offset + stride + 1 ] = morph.y;
  10098. buffer[ offset + stride + 2 ] = morph.z;
  10099. buffer[ offset + stride + 3 ] = 0;
  10100. if ( hasMorphNormals === true ) {
  10101. morph.fromBufferAttribute( morphNormal, j );
  10102. if ( morphNormal.normalized === true ) denormalize( morph, morphNormal );
  10103. buffer[ offset + stride + 4 ] = morph.x;
  10104. buffer[ offset + stride + 5 ] = morph.y;
  10105. buffer[ offset + stride + 6 ] = morph.z;
  10106. buffer[ offset + stride + 7 ] = 0;
  10107. }
  10108. }
  10109. }
  10110. entry = {
  10111. count: numberOfMorphTargets,
  10112. texture: texture,
  10113. size: new Vector2( width, height )
  10114. };
  10115. morphTextures.set( geometry, entry );
  10116. }
  10117. //
  10118. let morphInfluencesSum = 0;
  10119. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  10120. morphInfluencesSum += objectInfluences[ i ];
  10121. }
  10122. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10123. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10124. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  10125. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  10126. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  10127. } else {
  10128. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10129. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10130. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10131. let influences = influencesList[ geometry.id ];
  10132. if ( influences === undefined || influences.length !== length ) {
  10133. // initialise list
  10134. influences = [];
  10135. for ( let i = 0; i < length; i ++ ) {
  10136. influences[ i ] = [ i, 0 ];
  10137. }
  10138. influencesList[ geometry.id ] = influences;
  10139. }
  10140. // Collect influences
  10141. for ( let i = 0; i < length; i ++ ) {
  10142. const influence = influences[ i ];
  10143. influence[ 0 ] = i;
  10144. influence[ 1 ] = objectInfluences[ i ];
  10145. }
  10146. influences.sort( absNumericalSort );
  10147. for ( let i = 0; i < 8; i ++ ) {
  10148. if ( i < length && influences[ i ][ 1 ] ) {
  10149. workInfluences[ i ][ 0 ] = influences[ i ][ 0 ];
  10150. workInfluences[ i ][ 1 ] = influences[ i ][ 1 ];
  10151. } else {
  10152. workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER;
  10153. workInfluences[ i ][ 1 ] = 0;
  10154. }
  10155. }
  10156. workInfluences.sort( numericalSort );
  10157. const morphTargets = geometry.morphAttributes.position;
  10158. const morphNormals = geometry.morphAttributes.normal;
  10159. let morphInfluencesSum = 0;
  10160. for ( let i = 0; i < 8; i ++ ) {
  10161. const influence = workInfluences[ i ];
  10162. const index = influence[ 0 ];
  10163. const value = influence[ 1 ];
  10164. if ( index !== Number.MAX_SAFE_INTEGER && value ) {
  10165. if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) {
  10166. geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] );
  10167. }
  10168. if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) {
  10169. geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] );
  10170. }
  10171. morphInfluences[ i ] = value;
  10172. morphInfluencesSum += value;
  10173. } else {
  10174. if ( morphTargets && geometry.hasAttribute( 'morphTarget' + i ) === true ) {
  10175. geometry.deleteAttribute( 'morphTarget' + i );
  10176. }
  10177. if ( morphNormals && geometry.hasAttribute( 'morphNormal' + i ) === true ) {
  10178. geometry.deleteAttribute( 'morphNormal' + i );
  10179. }
  10180. morphInfluences[ i ] = 0;
  10181. }
  10182. }
  10183. // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10184. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10185. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10186. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10187. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10188. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  10189. }
  10190. }
  10191. return {
  10192. update: update
  10193. };
  10194. }
  10195. function WebGLObjects( gl, geometries, attributes, info ) {
  10196. let updateMap = new WeakMap();
  10197. function update( object ) {
  10198. const frame = info.render.frame;
  10199. const geometry = object.geometry;
  10200. const buffergeometry = geometries.get( object, geometry );
  10201. // Update once per frame
  10202. if ( updateMap.get( buffergeometry ) !== frame ) {
  10203. geometries.update( buffergeometry );
  10204. updateMap.set( buffergeometry, frame );
  10205. }
  10206. if ( object.isInstancedMesh ) {
  10207. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  10208. object.addEventListener( 'dispose', onInstancedMeshDispose );
  10209. }
  10210. attributes.update( object.instanceMatrix, 34962 );
  10211. if ( object.instanceColor !== null ) {
  10212. attributes.update( object.instanceColor, 34962 );
  10213. }
  10214. }
  10215. return buffergeometry;
  10216. }
  10217. function dispose() {
  10218. updateMap = new WeakMap();
  10219. }
  10220. function onInstancedMeshDispose( event ) {
  10221. const instancedMesh = event.target;
  10222. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  10223. attributes.remove( instancedMesh.instanceMatrix );
  10224. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  10225. }
  10226. return {
  10227. update: update,
  10228. dispose: dispose
  10229. };
  10230. }
  10231. class DataTexture3D extends Texture {
  10232. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  10233. // We're going to add .setXXX() methods for setting properties later.
  10234. // Users can still set in DataTexture3D directly.
  10235. //
  10236. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  10237. // texture.anisotropy = 16;
  10238. //
  10239. // See #14839
  10240. super( null );
  10241. this.image = { data, width, height, depth };
  10242. this.magFilter = NearestFilter;
  10243. this.minFilter = NearestFilter;
  10244. this.wrapR = ClampToEdgeWrapping;
  10245. this.generateMipmaps = false;
  10246. this.flipY = false;
  10247. this.unpackAlignment = 1;
  10248. this.needsUpdate = true;
  10249. }
  10250. }
  10251. DataTexture3D.prototype.isDataTexture3D = true;
  10252. /**
  10253. * Uniforms of a program.
  10254. * Those form a tree structure with a special top-level container for the root,
  10255. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10256. *
  10257. *
  10258. * Properties of inner nodes including the top-level container:
  10259. *
  10260. * .seq - array of nested uniforms
  10261. * .map - nested uniforms by name
  10262. *
  10263. *
  10264. * Methods of all nodes except the top-level container:
  10265. *
  10266. * .setValue( gl, value, [textures] )
  10267. *
  10268. * uploads a uniform value(s)
  10269. * the 'textures' parameter is needed for sampler uniforms
  10270. *
  10271. *
  10272. * Static methods of the top-level container (textures factorizations):
  10273. *
  10274. * .upload( gl, seq, values, textures )
  10275. *
  10276. * sets uniforms in 'seq' to 'values[id].value'
  10277. *
  10278. * .seqWithValue( seq, values ) : filteredSeq
  10279. *
  10280. * filters 'seq' entries with corresponding entry in values
  10281. *
  10282. *
  10283. * Methods of the top-level container (textures factorizations):
  10284. *
  10285. * .setValue( gl, name, value, textures )
  10286. *
  10287. * sets uniform with name 'name' to 'value'
  10288. *
  10289. * .setOptional( gl, obj, prop )
  10290. *
  10291. * like .set for an optional property of the object
  10292. *
  10293. */
  10294. const emptyTexture = new Texture();
  10295. const emptyTexture2dArray = new DataTexture2DArray();
  10296. const emptyTexture3d = new DataTexture3D();
  10297. const emptyCubeTexture = new CubeTexture();
  10298. // --- Utilities ---
  10299. // Array Caches (provide typed arrays for temporary by size)
  10300. const arrayCacheF32 = [];
  10301. const arrayCacheI32 = [];
  10302. // Float32Array caches used for uploading Matrix uniforms
  10303. const mat4array = new Float32Array( 16 );
  10304. const mat3array = new Float32Array( 9 );
  10305. const mat2array = new Float32Array( 4 );
  10306. // Flattening for arrays of vectors and matrices
  10307. function flatten( array, nBlocks, blockSize ) {
  10308. const firstElem = array[ 0 ];
  10309. if ( firstElem <= 0 || firstElem > 0 ) return array;
  10310. // unoptimized: ! isNaN( firstElem )
  10311. // see http://jacksondunstan.com/articles/983
  10312. const n = nBlocks * blockSize;
  10313. let r = arrayCacheF32[ n ];
  10314. if ( r === undefined ) {
  10315. r = new Float32Array( n );
  10316. arrayCacheF32[ n ] = r;
  10317. }
  10318. if ( nBlocks !== 0 ) {
  10319. firstElem.toArray( r, 0 );
  10320. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  10321. offset += blockSize;
  10322. array[ i ].toArray( r, offset );
  10323. }
  10324. }
  10325. return r;
  10326. }
  10327. function arraysEqual( a, b ) {
  10328. if ( a.length !== b.length ) return false;
  10329. for ( let i = 0, l = a.length; i < l; i ++ ) {
  10330. if ( a[ i ] !== b[ i ] ) return false;
  10331. }
  10332. return true;
  10333. }
  10334. function copyArray( a, b ) {
  10335. for ( let i = 0, l = b.length; i < l; i ++ ) {
  10336. a[ i ] = b[ i ];
  10337. }
  10338. }
  10339. // Texture unit allocation
  10340. function allocTexUnits( textures, n ) {
  10341. let r = arrayCacheI32[ n ];
  10342. if ( r === undefined ) {
  10343. r = new Int32Array( n );
  10344. arrayCacheI32[ n ] = r;
  10345. }
  10346. for ( let i = 0; i !== n; ++ i ) {
  10347. r[ i ] = textures.allocateTextureUnit();
  10348. }
  10349. return r;
  10350. }
  10351. // --- Setters ---
  10352. // Note: Defining these methods externally, because they come in a bunch
  10353. // and this way their names minify.
  10354. // Single scalar
  10355. function setValueV1f( gl, v ) {
  10356. const cache = this.cache;
  10357. if ( cache[ 0 ] === v ) return;
  10358. gl.uniform1f( this.addr, v );
  10359. cache[ 0 ] = v;
  10360. }
  10361. // Single float vector (from flat array or THREE.VectorN)
  10362. function setValueV2f( gl, v ) {
  10363. const cache = this.cache;
  10364. if ( v.x !== undefined ) {
  10365. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10366. gl.uniform2f( this.addr, v.x, v.y );
  10367. cache[ 0 ] = v.x;
  10368. cache[ 1 ] = v.y;
  10369. }
  10370. } else {
  10371. if ( arraysEqual( cache, v ) ) return;
  10372. gl.uniform2fv( this.addr, v );
  10373. copyArray( cache, v );
  10374. }
  10375. }
  10376. function setValueV3f( gl, v ) {
  10377. const cache = this.cache;
  10378. if ( v.x !== undefined ) {
  10379. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10380. gl.uniform3f( this.addr, v.x, v.y, v.z );
  10381. cache[ 0 ] = v.x;
  10382. cache[ 1 ] = v.y;
  10383. cache[ 2 ] = v.z;
  10384. }
  10385. } else if ( v.r !== undefined ) {
  10386. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  10387. gl.uniform3f( this.addr, v.r, v.g, v.b );
  10388. cache[ 0 ] = v.r;
  10389. cache[ 1 ] = v.g;
  10390. cache[ 2 ] = v.b;
  10391. }
  10392. } else {
  10393. if ( arraysEqual( cache, v ) ) return;
  10394. gl.uniform3fv( this.addr, v );
  10395. copyArray( cache, v );
  10396. }
  10397. }
  10398. function setValueV4f( gl, v ) {
  10399. const cache = this.cache;
  10400. if ( v.x !== undefined ) {
  10401. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10402. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  10403. cache[ 0 ] = v.x;
  10404. cache[ 1 ] = v.y;
  10405. cache[ 2 ] = v.z;
  10406. cache[ 3 ] = v.w;
  10407. }
  10408. } else {
  10409. if ( arraysEqual( cache, v ) ) return;
  10410. gl.uniform4fv( this.addr, v );
  10411. copyArray( cache, v );
  10412. }
  10413. }
  10414. // Single matrix (from flat array or THREE.MatrixN)
  10415. function setValueM2( gl, v ) {
  10416. const cache = this.cache;
  10417. const elements = v.elements;
  10418. if ( elements === undefined ) {
  10419. if ( arraysEqual( cache, v ) ) return;
  10420. gl.uniformMatrix2fv( this.addr, false, v );
  10421. copyArray( cache, v );
  10422. } else {
  10423. if ( arraysEqual( cache, elements ) ) return;
  10424. mat2array.set( elements );
  10425. gl.uniformMatrix2fv( this.addr, false, mat2array );
  10426. copyArray( cache, elements );
  10427. }
  10428. }
  10429. function setValueM3( gl, v ) {
  10430. const cache = this.cache;
  10431. const elements = v.elements;
  10432. if ( elements === undefined ) {
  10433. if ( arraysEqual( cache, v ) ) return;
  10434. gl.uniformMatrix3fv( this.addr, false, v );
  10435. copyArray( cache, v );
  10436. } else {
  10437. if ( arraysEqual( cache, elements ) ) return;
  10438. mat3array.set( elements );
  10439. gl.uniformMatrix3fv( this.addr, false, mat3array );
  10440. copyArray( cache, elements );
  10441. }
  10442. }
  10443. function setValueM4( gl, v ) {
  10444. const cache = this.cache;
  10445. const elements = v.elements;
  10446. if ( elements === undefined ) {
  10447. if ( arraysEqual( cache, v ) ) return;
  10448. gl.uniformMatrix4fv( this.addr, false, v );
  10449. copyArray( cache, v );
  10450. } else {
  10451. if ( arraysEqual( cache, elements ) ) return;
  10452. mat4array.set( elements );
  10453. gl.uniformMatrix4fv( this.addr, false, mat4array );
  10454. copyArray( cache, elements );
  10455. }
  10456. }
  10457. // Single integer / boolean
  10458. function setValueV1i( gl, v ) {
  10459. const cache = this.cache;
  10460. if ( cache[ 0 ] === v ) return;
  10461. gl.uniform1i( this.addr, v );
  10462. cache[ 0 ] = v;
  10463. }
  10464. // Single integer / boolean vector (from flat array)
  10465. function setValueV2i( gl, v ) {
  10466. const cache = this.cache;
  10467. if ( arraysEqual( cache, v ) ) return;
  10468. gl.uniform2iv( this.addr, v );
  10469. copyArray( cache, v );
  10470. }
  10471. function setValueV3i( gl, v ) {
  10472. const cache = this.cache;
  10473. if ( arraysEqual( cache, v ) ) return;
  10474. gl.uniform3iv( this.addr, v );
  10475. copyArray( cache, v );
  10476. }
  10477. function setValueV4i( gl, v ) {
  10478. const cache = this.cache;
  10479. if ( arraysEqual( cache, v ) ) return;
  10480. gl.uniform4iv( this.addr, v );
  10481. copyArray( cache, v );
  10482. }
  10483. // Single unsigned integer
  10484. function setValueV1ui( gl, v ) {
  10485. const cache = this.cache;
  10486. if ( cache[ 0 ] === v ) return;
  10487. gl.uniform1ui( this.addr, v );
  10488. cache[ 0 ] = v;
  10489. }
  10490. // Single unsigned integer vector (from flat array)
  10491. function setValueV2ui( gl, v ) {
  10492. const cache = this.cache;
  10493. if ( arraysEqual( cache, v ) ) return;
  10494. gl.uniform2uiv( this.addr, v );
  10495. copyArray( cache, v );
  10496. }
  10497. function setValueV3ui( gl, v ) {
  10498. const cache = this.cache;
  10499. if ( arraysEqual( cache, v ) ) return;
  10500. gl.uniform3uiv( this.addr, v );
  10501. copyArray( cache, v );
  10502. }
  10503. function setValueV4ui( gl, v ) {
  10504. const cache = this.cache;
  10505. if ( arraysEqual( cache, v ) ) return;
  10506. gl.uniform4uiv( this.addr, v );
  10507. copyArray( cache, v );
  10508. }
  10509. // Single texture (2D / Cube)
  10510. function setValueT1( gl, v, textures ) {
  10511. const cache = this.cache;
  10512. const unit = textures.allocateTextureUnit();
  10513. if ( cache[ 0 ] !== unit ) {
  10514. gl.uniform1i( this.addr, unit );
  10515. cache[ 0 ] = unit;
  10516. }
  10517. textures.safeSetTexture2D( v || emptyTexture, unit );
  10518. }
  10519. function setValueT3D1( gl, v, textures ) {
  10520. const cache = this.cache;
  10521. const unit = textures.allocateTextureUnit();
  10522. if ( cache[ 0 ] !== unit ) {
  10523. gl.uniform1i( this.addr, unit );
  10524. cache[ 0 ] = unit;
  10525. }
  10526. textures.setTexture3D( v || emptyTexture3d, unit );
  10527. }
  10528. function setValueT6( gl, v, textures ) {
  10529. const cache = this.cache;
  10530. const unit = textures.allocateTextureUnit();
  10531. if ( cache[ 0 ] !== unit ) {
  10532. gl.uniform1i( this.addr, unit );
  10533. cache[ 0 ] = unit;
  10534. }
  10535. textures.safeSetTextureCube( v || emptyCubeTexture, unit );
  10536. }
  10537. function setValueT2DArray1( gl, v, textures ) {
  10538. const cache = this.cache;
  10539. const unit = textures.allocateTextureUnit();
  10540. if ( cache[ 0 ] !== unit ) {
  10541. gl.uniform1i( this.addr, unit );
  10542. cache[ 0 ] = unit;
  10543. }
  10544. textures.setTexture2DArray( v || emptyTexture2dArray, unit );
  10545. }
  10546. // Helper to pick the right setter for the singular case
  10547. function getSingularSetter( type ) {
  10548. switch ( type ) {
  10549. case 0x1406: return setValueV1f; // FLOAT
  10550. case 0x8b50: return setValueV2f; // _VEC2
  10551. case 0x8b51: return setValueV3f; // _VEC3
  10552. case 0x8b52: return setValueV4f; // _VEC4
  10553. case 0x8b5a: return setValueM2; // _MAT2
  10554. case 0x8b5b: return setValueM3; // _MAT3
  10555. case 0x8b5c: return setValueM4; // _MAT4
  10556. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  10557. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  10558. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  10559. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  10560. case 0x1405: return setValueV1ui; // UINT
  10561. case 0x8dc6: return setValueV2ui; // _VEC2
  10562. case 0x8dc7: return setValueV3ui; // _VEC3
  10563. case 0x8dc8: return setValueV4ui; // _VEC4
  10564. case 0x8b5e: // SAMPLER_2D
  10565. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10566. case 0x8dca: // INT_SAMPLER_2D
  10567. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10568. case 0x8b62: // SAMPLER_2D_SHADOW
  10569. return setValueT1;
  10570. case 0x8b5f: // SAMPLER_3D
  10571. case 0x8dcb: // INT_SAMPLER_3D
  10572. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  10573. return setValueT3D1;
  10574. case 0x8b60: // SAMPLER_CUBE
  10575. case 0x8dcc: // INT_SAMPLER_CUBE
  10576. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10577. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  10578. return setValueT6;
  10579. case 0x8dc1: // SAMPLER_2D_ARRAY
  10580. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10581. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10582. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  10583. return setValueT2DArray1;
  10584. }
  10585. }
  10586. // Array of scalars
  10587. function setValueV1fArray( gl, v ) {
  10588. gl.uniform1fv( this.addr, v );
  10589. }
  10590. // Array of vectors (from flat array or array of THREE.VectorN)
  10591. function setValueV2fArray( gl, v ) {
  10592. const data = flatten( v, this.size, 2 );
  10593. gl.uniform2fv( this.addr, data );
  10594. }
  10595. function setValueV3fArray( gl, v ) {
  10596. const data = flatten( v, this.size, 3 );
  10597. gl.uniform3fv( this.addr, data );
  10598. }
  10599. function setValueV4fArray( gl, v ) {
  10600. const data = flatten( v, this.size, 4 );
  10601. gl.uniform4fv( this.addr, data );
  10602. }
  10603. // Array of matrices (from flat array or array of THREE.MatrixN)
  10604. function setValueM2Array( gl, v ) {
  10605. const data = flatten( v, this.size, 4 );
  10606. gl.uniformMatrix2fv( this.addr, false, data );
  10607. }
  10608. function setValueM3Array( gl, v ) {
  10609. const data = flatten( v, this.size, 9 );
  10610. gl.uniformMatrix3fv( this.addr, false, data );
  10611. }
  10612. function setValueM4Array( gl, v ) {
  10613. const data = flatten( v, this.size, 16 );
  10614. gl.uniformMatrix4fv( this.addr, false, data );
  10615. }
  10616. // Array of integer / boolean
  10617. function setValueV1iArray( gl, v ) {
  10618. gl.uniform1iv( this.addr, v );
  10619. }
  10620. // Array of integer / boolean vectors (from flat array)
  10621. function setValueV2iArray( gl, v ) {
  10622. gl.uniform2iv( this.addr, v );
  10623. }
  10624. function setValueV3iArray( gl, v ) {
  10625. gl.uniform3iv( this.addr, v );
  10626. }
  10627. function setValueV4iArray( gl, v ) {
  10628. gl.uniform4iv( this.addr, v );
  10629. }
  10630. // Array of unsigned integer
  10631. function setValueV1uiArray( gl, v ) {
  10632. gl.uniform1uiv( this.addr, v );
  10633. }
  10634. // Array of unsigned integer vectors (from flat array)
  10635. function setValueV2uiArray( gl, v ) {
  10636. gl.uniform2uiv( this.addr, v );
  10637. }
  10638. function setValueV3uiArray( gl, v ) {
  10639. gl.uniform3uiv( this.addr, v );
  10640. }
  10641. function setValueV4uiArray( gl, v ) {
  10642. gl.uniform4uiv( this.addr, v );
  10643. }
  10644. // Array of textures (2D / Cube)
  10645. function setValueT1Array( gl, v, textures ) {
  10646. const n = v.length;
  10647. const units = allocTexUnits( textures, n );
  10648. gl.uniform1iv( this.addr, units );
  10649. for ( let i = 0; i !== n; ++ i ) {
  10650. textures.safeSetTexture2D( v[ i ] || emptyTexture, units[ i ] );
  10651. }
  10652. }
  10653. function setValueT6Array( gl, v, textures ) {
  10654. const n = v.length;
  10655. const units = allocTexUnits( textures, n );
  10656. gl.uniform1iv( this.addr, units );
  10657. for ( let i = 0; i !== n; ++ i ) {
  10658. textures.safeSetTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  10659. }
  10660. }
  10661. // Helper to pick the right setter for a pure (bottom-level) array
  10662. function getPureArraySetter( type ) {
  10663. switch ( type ) {
  10664. case 0x1406: return setValueV1fArray; // FLOAT
  10665. case 0x8b50: return setValueV2fArray; // _VEC2
  10666. case 0x8b51: return setValueV3fArray; // _VEC3
  10667. case 0x8b52: return setValueV4fArray; // _VEC4
  10668. case 0x8b5a: return setValueM2Array; // _MAT2
  10669. case 0x8b5b: return setValueM3Array; // _MAT3
  10670. case 0x8b5c: return setValueM4Array; // _MAT4
  10671. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  10672. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  10673. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  10674. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  10675. case 0x1405: return setValueV1uiArray; // UINT
  10676. case 0x8dc6: return setValueV2uiArray; // _VEC2
  10677. case 0x8dc7: return setValueV3uiArray; // _VEC3
  10678. case 0x8dc8: return setValueV4uiArray; // _VEC4
  10679. case 0x8b5e: // SAMPLER_2D
  10680. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10681. case 0x8dca: // INT_SAMPLER_2D
  10682. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10683. case 0x8b62: // SAMPLER_2D_SHADOW
  10684. return setValueT1Array;
  10685. case 0x8b60: // SAMPLER_CUBE
  10686. case 0x8dcc: // INT_SAMPLER_CUBE
  10687. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10688. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  10689. return setValueT6Array;
  10690. }
  10691. }
  10692. // --- Uniform Classes ---
  10693. function SingleUniform( id, activeInfo, addr ) {
  10694. this.id = id;
  10695. this.addr = addr;
  10696. this.cache = [];
  10697. this.setValue = getSingularSetter( activeInfo.type );
  10698. // this.path = activeInfo.name; // DEBUG
  10699. }
  10700. function PureArrayUniform( id, activeInfo, addr ) {
  10701. this.id = id;
  10702. this.addr = addr;
  10703. this.cache = [];
  10704. this.size = activeInfo.size;
  10705. this.setValue = getPureArraySetter( activeInfo.type );
  10706. // this.path = activeInfo.name; // DEBUG
  10707. }
  10708. PureArrayUniform.prototype.updateCache = function ( data ) {
  10709. const cache = this.cache;
  10710. if ( data instanceof Float32Array && cache.length !== data.length ) {
  10711. this.cache = new Float32Array( data.length );
  10712. }
  10713. copyArray( cache, data );
  10714. };
  10715. function StructuredUniform( id ) {
  10716. this.id = id;
  10717. this.seq = [];
  10718. this.map = {};
  10719. }
  10720. StructuredUniform.prototype.setValue = function ( gl, value, textures ) {
  10721. const seq = this.seq;
  10722. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10723. const u = seq[ i ];
  10724. u.setValue( gl, value[ u.id ], textures );
  10725. }
  10726. };
  10727. // --- Top-level ---
  10728. // Parser - builds up the property tree from the path strings
  10729. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  10730. // extracts
  10731. // - the identifier (member name or array index)
  10732. // - followed by an optional right bracket (found when array index)
  10733. // - followed by an optional left bracket or dot (type of subscript)
  10734. //
  10735. // Note: These portions can be read in a non-overlapping fashion and
  10736. // allow straightforward parsing of the hierarchy that WebGL encodes
  10737. // in the uniform names.
  10738. function addUniform( container, uniformObject ) {
  10739. container.seq.push( uniformObject );
  10740. container.map[ uniformObject.id ] = uniformObject;
  10741. }
  10742. function parseUniform( activeInfo, addr, container ) {
  10743. const path = activeInfo.name,
  10744. pathLength = path.length;
  10745. // reset RegExp object, because of the early exit of a previous run
  10746. RePathPart.lastIndex = 0;
  10747. while ( true ) {
  10748. const match = RePathPart.exec( path ),
  10749. matchEnd = RePathPart.lastIndex;
  10750. let id = match[ 1 ];
  10751. const idIsIndex = match[ 2 ] === ']',
  10752. subscript = match[ 3 ];
  10753. if ( idIsIndex ) id = id | 0; // convert to integer
  10754. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  10755. // bare name or "pure" bottom-level array "[0]" suffix
  10756. addUniform( container, subscript === undefined ?
  10757. new SingleUniform( id, activeInfo, addr ) :
  10758. new PureArrayUniform( id, activeInfo, addr ) );
  10759. break;
  10760. } else {
  10761. // step into inner node / create it in case it doesn't exist
  10762. const map = container.map;
  10763. let next = map[ id ];
  10764. if ( next === undefined ) {
  10765. next = new StructuredUniform( id );
  10766. addUniform( container, next );
  10767. }
  10768. container = next;
  10769. }
  10770. }
  10771. }
  10772. // Root Container
  10773. function WebGLUniforms( gl, program ) {
  10774. this.seq = [];
  10775. this.map = {};
  10776. const n = gl.getProgramParameter( program, 35718 );
  10777. for ( let i = 0; i < n; ++ i ) {
  10778. const info = gl.getActiveUniform( program, i ),
  10779. addr = gl.getUniformLocation( program, info.name );
  10780. parseUniform( info, addr, this );
  10781. }
  10782. }
  10783. WebGLUniforms.prototype.setValue = function ( gl, name, value, textures ) {
  10784. const u = this.map[ name ];
  10785. if ( u !== undefined ) u.setValue( gl, value, textures );
  10786. };
  10787. WebGLUniforms.prototype.setOptional = function ( gl, object, name ) {
  10788. const v = object[ name ];
  10789. if ( v !== undefined ) this.setValue( gl, name, v );
  10790. };
  10791. // Static interface
  10792. WebGLUniforms.upload = function ( gl, seq, values, textures ) {
  10793. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10794. const u = seq[ i ],
  10795. v = values[ u.id ];
  10796. if ( v.needsUpdate !== false ) {
  10797. // note: always updating when .needsUpdate is undefined
  10798. u.setValue( gl, v.value, textures );
  10799. }
  10800. }
  10801. };
  10802. WebGLUniforms.seqWithValue = function ( seq, values ) {
  10803. const r = [];
  10804. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10805. const u = seq[ i ];
  10806. if ( u.id in values ) r.push( u );
  10807. }
  10808. return r;
  10809. };
  10810. function WebGLShader( gl, type, string ) {
  10811. const shader = gl.createShader( type );
  10812. gl.shaderSource( shader, string );
  10813. gl.compileShader( shader );
  10814. return shader;
  10815. }
  10816. let programIdCount = 0;
  10817. function addLineNumbers( string ) {
  10818. const lines = string.split( '\n' );
  10819. for ( let i = 0; i < lines.length; i ++ ) {
  10820. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  10821. }
  10822. return lines.join( '\n' );
  10823. }
  10824. function getEncodingComponents( encoding ) {
  10825. switch ( encoding ) {
  10826. case LinearEncoding:
  10827. return [ 'Linear', '( value )' ];
  10828. case sRGBEncoding:
  10829. return [ 'sRGB', '( value )' ];
  10830. case RGBEEncoding:
  10831. return [ 'RGBE', '( value )' ];
  10832. case RGBM7Encoding:
  10833. return [ 'RGBM', '( value, 7.0 )' ];
  10834. case RGBM16Encoding:
  10835. return [ 'RGBM', '( value, 16.0 )' ];
  10836. case RGBDEncoding:
  10837. return [ 'RGBD', '( value, 256.0 )' ];
  10838. case GammaEncoding:
  10839. return [ 'Gamma', '( value, float( GAMMA_FACTOR ) )' ];
  10840. case LogLuvEncoding:
  10841. return [ 'LogLuv', '( value )' ];
  10842. default:
  10843. console.warn( 'THREE.WebGLProgram: Unsupported encoding:', encoding );
  10844. return [ 'Linear', '( value )' ];
  10845. }
  10846. }
  10847. function getShaderErrors( gl, shader, type ) {
  10848. const status = gl.getShaderParameter( shader, 35713 );
  10849. const errors = gl.getShaderInfoLog( shader ).trim();
  10850. if ( status && errors === '' ) return '';
  10851. // --enable-privileged-webgl-extension
  10852. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  10853. return type.toUpperCase() + '\n\n' + errors + '\n\n' + addLineNumbers( gl.getShaderSource( shader ) );
  10854. }
  10855. function getTexelDecodingFunction( functionName, encoding ) {
  10856. const components = getEncodingComponents( encoding );
  10857. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[ 0 ] + 'ToLinear' + components[ 1 ] + '; }';
  10858. }
  10859. function getTexelEncodingFunction( functionName, encoding ) {
  10860. const components = getEncodingComponents( encoding );
  10861. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';
  10862. }
  10863. function getToneMappingFunction( functionName, toneMapping ) {
  10864. let toneMappingName;
  10865. switch ( toneMapping ) {
  10866. case LinearToneMapping:
  10867. toneMappingName = 'Linear';
  10868. break;
  10869. case ReinhardToneMapping:
  10870. toneMappingName = 'Reinhard';
  10871. break;
  10872. case CineonToneMapping:
  10873. toneMappingName = 'OptimizedCineon';
  10874. break;
  10875. case ACESFilmicToneMapping:
  10876. toneMappingName = 'ACESFilmic';
  10877. break;
  10878. case CustomToneMapping:
  10879. toneMappingName = 'Custom';
  10880. break;
  10881. default:
  10882. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  10883. toneMappingName = 'Linear';
  10884. }
  10885. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  10886. }
  10887. function generateExtensions( parameters ) {
  10888. const chunks = [
  10889. ( parameters.extensionDerivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  10890. ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '',
  10891. ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '',
  10892. ( parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  10893. ];
  10894. return chunks.filter( filterEmptyLine ).join( '\n' );
  10895. }
  10896. function generateDefines( defines ) {
  10897. const chunks = [];
  10898. for ( const name in defines ) {
  10899. const value = defines[ name ];
  10900. if ( value === false ) continue;
  10901. chunks.push( '#define ' + name + ' ' + value );
  10902. }
  10903. return chunks.join( '\n' );
  10904. }
  10905. function fetchAttributeLocations( gl, program ) {
  10906. const attributes = {};
  10907. const n = gl.getProgramParameter( program, 35721 );
  10908. for ( let i = 0; i < n; i ++ ) {
  10909. const info = gl.getActiveAttrib( program, i );
  10910. const name = info.name;
  10911. let locationSize = 1;
  10912. if ( info.type === 35674 ) locationSize = 2;
  10913. if ( info.type === 35675 ) locationSize = 3;
  10914. if ( info.type === 35676 ) locationSize = 4;
  10915. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  10916. attributes[ name ] = {
  10917. type: info.type,
  10918. location: gl.getAttribLocation( program, name ),
  10919. locationSize: locationSize
  10920. };
  10921. }
  10922. return attributes;
  10923. }
  10924. function filterEmptyLine( string ) {
  10925. return string !== '';
  10926. }
  10927. function replaceLightNums( string, parameters ) {
  10928. return string
  10929. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  10930. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  10931. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  10932. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  10933. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  10934. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  10935. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  10936. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  10937. }
  10938. function replaceClippingPlaneNums( string, parameters ) {
  10939. return string
  10940. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  10941. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  10942. }
  10943. // Resolve Includes
  10944. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  10945. function resolveIncludes( string ) {
  10946. return string.replace( includePattern, includeReplacer );
  10947. }
  10948. function includeReplacer( match, include ) {
  10949. const string = ShaderChunk[ include ];
  10950. if ( string === undefined ) {
  10951. throw new Error( 'Can not resolve #include <' + include + '>' );
  10952. }
  10953. return resolveIncludes( string );
  10954. }
  10955. // Unroll Loops
  10956. const deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  10957. 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;
  10958. function unrollLoops( string ) {
  10959. return string
  10960. .replace( unrollLoopPattern, loopReplacer )
  10961. .replace( deprecatedUnrollLoopPattern, deprecatedLoopReplacer );
  10962. }
  10963. function deprecatedLoopReplacer( match, start, end, snippet ) {
  10964. console.warn( 'WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.' );
  10965. return loopReplacer( match, start, end, snippet );
  10966. }
  10967. function loopReplacer( match, start, end, snippet ) {
  10968. let string = '';
  10969. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  10970. string += snippet
  10971. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  10972. .replace( /UNROLLED_LOOP_INDEX/g, i );
  10973. }
  10974. return string;
  10975. }
  10976. //
  10977. function generatePrecision( parameters ) {
  10978. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  10979. if ( parameters.precision === 'highp' ) {
  10980. precisionstring += '\n#define HIGH_PRECISION';
  10981. } else if ( parameters.precision === 'mediump' ) {
  10982. precisionstring += '\n#define MEDIUM_PRECISION';
  10983. } else if ( parameters.precision === 'lowp' ) {
  10984. precisionstring += '\n#define LOW_PRECISION';
  10985. }
  10986. return precisionstring;
  10987. }
  10988. function generateShadowMapTypeDefine( parameters ) {
  10989. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  10990. if ( parameters.shadowMapType === PCFShadowMap ) {
  10991. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  10992. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  10993. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  10994. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  10995. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  10996. }
  10997. return shadowMapTypeDefine;
  10998. }
  10999. function generateEnvMapTypeDefine( parameters ) {
  11000. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11001. if ( parameters.envMap ) {
  11002. switch ( parameters.envMapMode ) {
  11003. case CubeReflectionMapping:
  11004. case CubeRefractionMapping:
  11005. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11006. break;
  11007. case CubeUVReflectionMapping:
  11008. case CubeUVRefractionMapping:
  11009. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11010. break;
  11011. }
  11012. }
  11013. return envMapTypeDefine;
  11014. }
  11015. function generateEnvMapModeDefine( parameters ) {
  11016. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11017. if ( parameters.envMap ) {
  11018. switch ( parameters.envMapMode ) {
  11019. case CubeRefractionMapping:
  11020. case CubeUVRefractionMapping:
  11021. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11022. break;
  11023. }
  11024. }
  11025. return envMapModeDefine;
  11026. }
  11027. function generateEnvMapBlendingDefine( parameters ) {
  11028. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11029. if ( parameters.envMap ) {
  11030. switch ( parameters.combine ) {
  11031. case MultiplyOperation:
  11032. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11033. break;
  11034. case MixOperation:
  11035. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11036. break;
  11037. case AddOperation:
  11038. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11039. break;
  11040. }
  11041. }
  11042. return envMapBlendingDefine;
  11043. }
  11044. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  11045. // TODO Send this event to Three.js DevTools
  11046. // console.log( 'WebGLProgram', cacheKey );
  11047. const gl = renderer.getContext();
  11048. const defines = parameters.defines;
  11049. let vertexShader = parameters.vertexShader;
  11050. let fragmentShader = parameters.fragmentShader;
  11051. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  11052. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  11053. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  11054. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  11055. const gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  11056. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters );
  11057. const customDefines = generateDefines( defines );
  11058. const program = gl.createProgram();
  11059. let prefixVertex, prefixFragment;
  11060. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  11061. if ( parameters.isRawShaderMaterial ) {
  11062. prefixVertex = [
  11063. customDefines
  11064. ].filter( filterEmptyLine ).join( '\n' );
  11065. if ( prefixVertex.length > 0 ) {
  11066. prefixVertex += '\n';
  11067. }
  11068. prefixFragment = [
  11069. customExtensions,
  11070. customDefines
  11071. ].filter( filterEmptyLine ).join( '\n' );
  11072. if ( prefixFragment.length > 0 ) {
  11073. prefixFragment += '\n';
  11074. }
  11075. } else {
  11076. prefixVertex = [
  11077. generatePrecision( parameters ),
  11078. '#define SHADER_NAME ' + parameters.shaderName,
  11079. customDefines,
  11080. parameters.instancing ? '#define USE_INSTANCING' : '',
  11081. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  11082. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  11083. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  11084. '#define MAX_BONES ' + parameters.maxBones,
  11085. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  11086. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  11087. parameters.map ? '#define USE_MAP' : '',
  11088. parameters.envMap ? '#define USE_ENVMAP' : '',
  11089. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11090. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11091. parameters.aoMap ? '#define USE_AOMAP' : '',
  11092. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11093. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11094. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11095. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  11096. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  11097. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11098. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11099. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11100. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  11101. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11102. parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '',
  11103. parameters.specularTintMap ? '#define USE_SPECULARTINTMAP' : '',
  11104. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11105. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11106. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11107. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11108. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11109. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11110. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11111. parameters.vertexColors ? '#define USE_COLOR' : '',
  11112. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11113. parameters.vertexUvs ? '#define USE_UV' : '',
  11114. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  11115. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11116. parameters.skinning ? '#define USE_SKINNING' : '',
  11117. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  11118. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  11119. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  11120. ( parameters.morphTargets && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE' : '',
  11121. ( parameters.morphTargets && parameters.isWebGL2 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  11122. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11123. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11124. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11125. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11126. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  11127. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11128. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11129. 'uniform mat4 modelMatrix;',
  11130. 'uniform mat4 modelViewMatrix;',
  11131. 'uniform mat4 projectionMatrix;',
  11132. 'uniform mat4 viewMatrix;',
  11133. 'uniform mat3 normalMatrix;',
  11134. 'uniform vec3 cameraPosition;',
  11135. 'uniform bool isOrthographic;',
  11136. '#ifdef USE_INSTANCING',
  11137. ' attribute mat4 instanceMatrix;',
  11138. '#endif',
  11139. '#ifdef USE_INSTANCING_COLOR',
  11140. ' attribute vec3 instanceColor;',
  11141. '#endif',
  11142. 'attribute vec3 position;',
  11143. 'attribute vec3 normal;',
  11144. 'attribute vec2 uv;',
  11145. '#ifdef USE_TANGENT',
  11146. ' attribute vec4 tangent;',
  11147. '#endif',
  11148. '#if defined( USE_COLOR_ALPHA )',
  11149. ' attribute vec4 color;',
  11150. '#elif defined( USE_COLOR )',
  11151. ' attribute vec3 color;',
  11152. '#endif',
  11153. '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )',
  11154. ' attribute vec3 morphTarget0;',
  11155. ' attribute vec3 morphTarget1;',
  11156. ' attribute vec3 morphTarget2;',
  11157. ' attribute vec3 morphTarget3;',
  11158. ' #ifdef USE_MORPHNORMALS',
  11159. ' attribute vec3 morphNormal0;',
  11160. ' attribute vec3 morphNormal1;',
  11161. ' attribute vec3 morphNormal2;',
  11162. ' attribute vec3 morphNormal3;',
  11163. ' #else',
  11164. ' attribute vec3 morphTarget4;',
  11165. ' attribute vec3 morphTarget5;',
  11166. ' attribute vec3 morphTarget6;',
  11167. ' attribute vec3 morphTarget7;',
  11168. ' #endif',
  11169. '#endif',
  11170. '#ifdef USE_SKINNING',
  11171. ' attribute vec4 skinIndex;',
  11172. ' attribute vec4 skinWeight;',
  11173. '#endif',
  11174. '\n'
  11175. ].filter( filterEmptyLine ).join( '\n' );
  11176. prefixFragment = [
  11177. customExtensions,
  11178. generatePrecision( parameters ),
  11179. '#define SHADER_NAME ' + parameters.shaderName,
  11180. customDefines,
  11181. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  11182. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  11183. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  11184. parameters.map ? '#define USE_MAP' : '',
  11185. parameters.matcap ? '#define USE_MATCAP' : '',
  11186. parameters.envMap ? '#define USE_ENVMAP' : '',
  11187. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  11188. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11189. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  11190. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11191. parameters.aoMap ? '#define USE_AOMAP' : '',
  11192. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11193. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11194. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11195. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  11196. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  11197. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  11198. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11199. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11200. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11201. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11202. parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '',
  11203. parameters.specularTintMap ? '#define USE_SPECULARTINTMAP' : '',
  11204. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11205. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11206. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11207. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  11208. parameters.sheen ? '#define USE_SHEEN' : '',
  11209. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11210. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11211. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11212. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11213. parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '',
  11214. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11215. parameters.vertexUvs ? '#define USE_UV' : '',
  11216. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  11217. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  11218. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11219. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11220. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11221. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11222. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11223. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  11224. parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '',
  11225. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11226. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11227. ( ( parameters.extensionShaderTextureLOD || parameters.envMap ) && parameters.rendererExtensionShaderTextureLod ) ? '#define TEXTURE_LOD_EXT' : '',
  11228. 'uniform mat4 viewMatrix;',
  11229. 'uniform vec3 cameraPosition;',
  11230. 'uniform bool isOrthographic;',
  11231. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  11232. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  11233. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  11234. parameters.dithering ? '#define DITHERING' : '',
  11235. parameters.format === RGBFormat ? '#define OPAQUE' : '',
  11236. ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  11237. parameters.map ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  11238. parameters.matcap ? getTexelDecodingFunction( 'matcapTexelToLinear', parameters.matcapEncoding ) : '',
  11239. parameters.envMap ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  11240. parameters.emissiveMap ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  11241. parameters.specularTintMap ? getTexelDecodingFunction( 'specularTintMapTexelToLinear', parameters.specularTintMapEncoding ) : '',
  11242. parameters.lightMap ? getTexelDecodingFunction( 'lightMapTexelToLinear', parameters.lightMapEncoding ) : '',
  11243. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ),
  11244. parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  11245. '\n'
  11246. ].filter( filterEmptyLine ).join( '\n' );
  11247. }
  11248. vertexShader = resolveIncludes( vertexShader );
  11249. vertexShader = replaceLightNums( vertexShader, parameters );
  11250. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  11251. fragmentShader = resolveIncludes( fragmentShader );
  11252. fragmentShader = replaceLightNums( fragmentShader, parameters );
  11253. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  11254. vertexShader = unrollLoops( vertexShader );
  11255. fragmentShader = unrollLoops( fragmentShader );
  11256. if ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) {
  11257. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11258. versionString = '#version 300 es\n';
  11259. prefixVertex = [
  11260. 'precision mediump sampler2DArray;',
  11261. '#define attribute in',
  11262. '#define varying out',
  11263. '#define texture2D texture'
  11264. ].join( '\n' ) + '\n' + prefixVertex;
  11265. prefixFragment = [
  11266. '#define varying in',
  11267. ( parameters.glslVersion === GLSL3 ) ? '' : 'out highp vec4 pc_fragColor;',
  11268. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  11269. '#define gl_FragDepthEXT gl_FragDepth',
  11270. '#define texture2D texture',
  11271. '#define textureCube texture',
  11272. '#define texture2DProj textureProj',
  11273. '#define texture2DLodEXT textureLod',
  11274. '#define texture2DProjLodEXT textureProjLod',
  11275. '#define textureCubeLodEXT textureLod',
  11276. '#define texture2DGradEXT textureGrad',
  11277. '#define texture2DProjGradEXT textureProjGrad',
  11278. '#define textureCubeGradEXT textureGrad'
  11279. ].join( '\n' ) + '\n' + prefixFragment;
  11280. }
  11281. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11282. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  11283. // console.log( '*VERTEX*', vertexGlsl );
  11284. // console.log( '*FRAGMENT*', fragmentGlsl );
  11285. const glVertexShader = WebGLShader( gl, 35633, vertexGlsl );
  11286. const glFragmentShader = WebGLShader( gl, 35632, fragmentGlsl );
  11287. gl.attachShader( program, glVertexShader );
  11288. gl.attachShader( program, glFragmentShader );
  11289. // Force a particular attribute to index 0.
  11290. if ( parameters.index0AttributeName !== undefined ) {
  11291. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  11292. } else if ( parameters.morphTargets === true ) {
  11293. // programs with morphTargets displace position out of attribute 0
  11294. gl.bindAttribLocation( program, 0, 'position' );
  11295. }
  11296. gl.linkProgram( program );
  11297. // check for link errors
  11298. if ( renderer.debug.checkShaderErrors ) {
  11299. const programLog = gl.getProgramInfoLog( program ).trim();
  11300. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  11301. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  11302. let runnable = true;
  11303. let haveDiagnostics = true;
  11304. if ( gl.getProgramParameter( program, 35714 ) === false ) {
  11305. runnable = false;
  11306. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  11307. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  11308. console.error(
  11309. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  11310. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, 35715 ) + '\n\n' +
  11311. 'Program Info Log: ' + programLog + '\n' +
  11312. vertexErrors + '\n' +
  11313. fragmentErrors
  11314. );
  11315. } else if ( programLog !== '' ) {
  11316. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  11317. } else if ( vertexLog === '' || fragmentLog === '' ) {
  11318. haveDiagnostics = false;
  11319. }
  11320. if ( haveDiagnostics ) {
  11321. this.diagnostics = {
  11322. runnable: runnable,
  11323. programLog: programLog,
  11324. vertexShader: {
  11325. log: vertexLog,
  11326. prefix: prefixVertex
  11327. },
  11328. fragmentShader: {
  11329. log: fragmentLog,
  11330. prefix: prefixFragment
  11331. }
  11332. };
  11333. }
  11334. }
  11335. // Clean up
  11336. // Crashes in iOS9 and iOS10. #18402
  11337. // gl.detachShader( program, glVertexShader );
  11338. // gl.detachShader( program, glFragmentShader );
  11339. gl.deleteShader( glVertexShader );
  11340. gl.deleteShader( glFragmentShader );
  11341. // set up caching for uniform locations
  11342. let cachedUniforms;
  11343. this.getUniforms = function () {
  11344. if ( cachedUniforms === undefined ) {
  11345. cachedUniforms = new WebGLUniforms( gl, program );
  11346. }
  11347. return cachedUniforms;
  11348. };
  11349. // set up caching for attribute locations
  11350. let cachedAttributes;
  11351. this.getAttributes = function () {
  11352. if ( cachedAttributes === undefined ) {
  11353. cachedAttributes = fetchAttributeLocations( gl, program );
  11354. }
  11355. return cachedAttributes;
  11356. };
  11357. // free resource
  11358. this.destroy = function () {
  11359. bindingStates.releaseStatesOfProgram( this );
  11360. gl.deleteProgram( program );
  11361. this.program = undefined;
  11362. };
  11363. //
  11364. this.name = parameters.shaderName;
  11365. this.id = programIdCount ++;
  11366. this.cacheKey = cacheKey;
  11367. this.usedTimes = 1;
  11368. this.program = program;
  11369. this.vertexShader = glVertexShader;
  11370. this.fragmentShader = glFragmentShader;
  11371. return this;
  11372. }
  11373. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  11374. const programs = [];
  11375. const isWebGL2 = capabilities.isWebGL2;
  11376. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11377. const floatVertexTextures = capabilities.floatVertexTextures;
  11378. const maxVertexUniforms = capabilities.maxVertexUniforms;
  11379. const vertexTextures = capabilities.vertexTextures;
  11380. let precision = capabilities.precision;
  11381. const shaderIDs = {
  11382. MeshDepthMaterial: 'depth',
  11383. MeshDistanceMaterial: 'distanceRGBA',
  11384. MeshNormalMaterial: 'normal',
  11385. MeshBasicMaterial: 'basic',
  11386. MeshLambertMaterial: 'lambert',
  11387. MeshPhongMaterial: 'phong',
  11388. MeshToonMaterial: 'toon',
  11389. MeshStandardMaterial: 'physical',
  11390. MeshPhysicalMaterial: 'physical',
  11391. MeshMatcapMaterial: 'matcap',
  11392. LineBasicMaterial: 'basic',
  11393. LineDashedMaterial: 'dashed',
  11394. PointsMaterial: 'points',
  11395. ShadowMaterial: 'shadow',
  11396. SpriteMaterial: 'sprite'
  11397. };
  11398. const parameterNames = [
  11399. 'precision', 'isWebGL2', 'supportsVertexTextures', 'outputEncoding', 'instancing', 'instancingColor',
  11400. 'map', 'mapEncoding', 'matcap', 'matcapEncoding', 'envMap', 'envMapMode', 'envMapEncoding', 'envMapCubeUV',
  11401. 'lightMap', 'lightMapEncoding', 'aoMap', 'emissiveMap', 'emissiveMapEncoding', 'bumpMap', 'normalMap',
  11402. 'objectSpaceNormalMap', 'tangentSpaceNormalMap',
  11403. 'clearcoat', 'clearcoatMap', 'clearcoatRoughnessMap', 'clearcoatNormalMap',
  11404. 'displacementMap',
  11405. 'specularMap', 'specularIntensityMap', 'specularTintMap', 'specularTintMapEncoding', 'roughnessMap', 'metalnessMap', 'gradientMap',
  11406. 'alphaMap', 'alphaTest', 'combine', 'vertexColors', 'vertexAlphas', 'vertexTangents', 'vertexUvs', 'uvsVertexOnly', 'fog', 'useFog', 'fogExp2',
  11407. 'flatShading', 'sizeAttenuation', 'logarithmicDepthBuffer', 'skinning',
  11408. 'maxBones', 'useVertexTexture', 'morphTargets', 'morphNormals', 'morphTargetsCount', 'premultipliedAlpha',
  11409. 'numDirLights', 'numPointLights', 'numSpotLights', 'numHemiLights', 'numRectAreaLights',
  11410. 'numDirLightShadows', 'numPointLightShadows', 'numSpotLightShadows',
  11411. 'shadowMapEnabled', 'shadowMapType', 'toneMapping', 'physicallyCorrectLights',
  11412. 'doubleSided', 'flipSided', 'numClippingPlanes', 'numClipIntersection', 'depthPacking', 'dithering', 'format',
  11413. 'sheen', 'transmission', 'transmissionMap', 'thicknessMap'
  11414. ];
  11415. function getMaxBones( object ) {
  11416. const skeleton = object.skeleton;
  11417. const bones = skeleton.bones;
  11418. if ( floatVertexTextures ) {
  11419. return 1024;
  11420. } else {
  11421. // default for when object is not specified
  11422. // ( for example when prebuilding shader to be used with multiple objects )
  11423. //
  11424. // - leave some extra space for other uniforms
  11425. // - limit here is ANGLE's 254 max uniform vectors
  11426. // (up to 54 should be safe)
  11427. const nVertexUniforms = maxVertexUniforms;
  11428. const nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  11429. const maxBones = Math.min( nVertexMatrices, bones.length );
  11430. if ( maxBones < bones.length ) {
  11431. console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' );
  11432. return 0;
  11433. }
  11434. return maxBones;
  11435. }
  11436. }
  11437. function getTextureEncodingFromMap( map ) {
  11438. let encoding;
  11439. if ( map && map.isTexture ) {
  11440. encoding = map.encoding;
  11441. } else if ( map && map.isWebGLRenderTarget ) {
  11442. console.warn( 'THREE.WebGLPrograms.getTextureEncodingFromMap: don\'t use render targets as textures. Use their .texture property instead.' );
  11443. encoding = map.texture.encoding;
  11444. } else {
  11445. encoding = LinearEncoding;
  11446. }
  11447. if ( isWebGL2 && map && map.isTexture && map.format === RGBAFormat && map.type === UnsignedByteType && map.encoding === sRGBEncoding ) {
  11448. encoding = LinearEncoding; // disable inline decode for sRGB textures in WebGL 2
  11449. }
  11450. return encoding;
  11451. }
  11452. function getParameters( material, lights, shadows, scene, object ) {
  11453. const fog = scene.fog;
  11454. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  11455. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  11456. const shaderID = shaderIDs[ material.type ];
  11457. // heuristics to create shader parameters according to lights in the scene
  11458. // (not to blow over maxLights budget)
  11459. const maxBones = object.isSkinnedMesh ? getMaxBones( object ) : 0;
  11460. if ( material.precision !== null ) {
  11461. precision = capabilities.getMaxPrecision( material.precision );
  11462. if ( precision !== material.precision ) {
  11463. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  11464. }
  11465. }
  11466. let vertexShader, fragmentShader;
  11467. if ( shaderID ) {
  11468. const shader = ShaderLib[ shaderID ];
  11469. vertexShader = shader.vertexShader;
  11470. fragmentShader = shader.fragmentShader;
  11471. } else {
  11472. vertexShader = material.vertexShader;
  11473. fragmentShader = material.fragmentShader;
  11474. }
  11475. const currentRenderTarget = renderer.getRenderTarget();
  11476. const useAlphaTest = material.alphaTest > 0;
  11477. const useClearcoat = material.clearcoat > 0;
  11478. const parameters = {
  11479. isWebGL2: isWebGL2,
  11480. shaderID: shaderID,
  11481. shaderName: material.type,
  11482. vertexShader: vertexShader,
  11483. fragmentShader: fragmentShader,
  11484. defines: material.defines,
  11485. isRawShaderMaterial: material.isRawShaderMaterial === true,
  11486. glslVersion: material.glslVersion,
  11487. precision: precision,
  11488. instancing: object.isInstancedMesh === true,
  11489. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  11490. supportsVertexTextures: vertexTextures,
  11491. outputEncoding: ( currentRenderTarget !== null ) ? getTextureEncodingFromMap( currentRenderTarget.texture ) : renderer.outputEncoding,
  11492. map: !! material.map,
  11493. mapEncoding: getTextureEncodingFromMap( material.map ),
  11494. matcap: !! material.matcap,
  11495. matcapEncoding: getTextureEncodingFromMap( material.matcap ),
  11496. envMap: !! envMap,
  11497. envMapMode: envMap && envMap.mapping,
  11498. envMapEncoding: getTextureEncodingFromMap( envMap ),
  11499. envMapCubeUV: ( !! envMap ) && ( ( envMap.mapping === CubeUVReflectionMapping ) || ( envMap.mapping === CubeUVRefractionMapping ) ),
  11500. lightMap: !! material.lightMap,
  11501. lightMapEncoding: getTextureEncodingFromMap( material.lightMap ),
  11502. aoMap: !! material.aoMap,
  11503. emissiveMap: !! material.emissiveMap,
  11504. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap ),
  11505. bumpMap: !! material.bumpMap,
  11506. normalMap: !! material.normalMap,
  11507. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  11508. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  11509. clearcoat: useClearcoat,
  11510. clearcoatMap: useClearcoat && !! material.clearcoatMap,
  11511. clearcoatRoughnessMap: useClearcoat && !! material.clearcoatRoughnessMap,
  11512. clearcoatNormalMap: useClearcoat && !! material.clearcoatNormalMap,
  11513. displacementMap: !! material.displacementMap,
  11514. roughnessMap: !! material.roughnessMap,
  11515. metalnessMap: !! material.metalnessMap,
  11516. specularMap: !! material.specularMap,
  11517. specularIntensityMap: !! material.specularIntensityMap,
  11518. specularTintMap: !! material.specularTintMap,
  11519. specularTintMapEncoding: getTextureEncodingFromMap( material.specularTintMap ),
  11520. alphaMap: !! material.alphaMap,
  11521. alphaTest: useAlphaTest,
  11522. gradientMap: !! material.gradientMap,
  11523. sheen: material.sheen > 0,
  11524. transmission: material.transmission > 0,
  11525. transmissionMap: !! material.transmissionMap,
  11526. thicknessMap: !! material.thicknessMap,
  11527. combine: material.combine,
  11528. vertexTangents: ( !! material.normalMap && !! object.geometry && !! object.geometry.attributes.tangent ),
  11529. vertexColors: material.vertexColors,
  11530. vertexAlphas: material.vertexColors === true && !! object.geometry && !! object.geometry.attributes.color && object.geometry.attributes.color.itemSize === 4,
  11531. vertexUvs: !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatMap || !! material.clearcoatRoughnessMap || !! material.clearcoatNormalMap || !! material.displacementMap || !! material.transmissionMap || !! material.thicknessMap || !! material.specularIntensityMap || !! material.specularTintMap,
  11532. uvsVertexOnly: ! ( !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap || material.transmission > 0 || !! material.transmissionMap || !! material.thicknessMap || !! material.specularIntensityMap || !! material.specularTintMap ) && !! material.displacementMap,
  11533. fog: !! fog,
  11534. useFog: material.fog,
  11535. fogExp2: ( fog && fog.isFogExp2 ),
  11536. flatShading: !! material.flatShading,
  11537. sizeAttenuation: material.sizeAttenuation,
  11538. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11539. skinning: object.isSkinnedMesh === true && maxBones > 0,
  11540. maxBones: maxBones,
  11541. useVertexTexture: floatVertexTextures,
  11542. morphTargets: !! object.geometry && !! object.geometry.morphAttributes.position,
  11543. morphNormals: !! object.geometry && !! object.geometry.morphAttributes.normal,
  11544. morphTargetsCount: ( !! object.geometry && !! object.geometry.morphAttributes.position ) ? object.geometry.morphAttributes.position.length : 0,
  11545. numDirLights: lights.directional.length,
  11546. numPointLights: lights.point.length,
  11547. numSpotLights: lights.spot.length,
  11548. numRectAreaLights: lights.rectArea.length,
  11549. numHemiLights: lights.hemi.length,
  11550. numDirLightShadows: lights.directionalShadowMap.length,
  11551. numPointLightShadows: lights.pointShadowMap.length,
  11552. numSpotLightShadows: lights.spotShadowMap.length,
  11553. numClippingPlanes: clipping.numPlanes,
  11554. numClipIntersection: clipping.numIntersection,
  11555. format: material.format,
  11556. dithering: material.dithering,
  11557. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  11558. shadowMapType: renderer.shadowMap.type,
  11559. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  11560. physicallyCorrectLights: renderer.physicallyCorrectLights,
  11561. premultipliedAlpha: material.premultipliedAlpha,
  11562. doubleSided: material.side === DoubleSide,
  11563. flipSided: material.side === BackSide,
  11564. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false,
  11565. index0AttributeName: material.index0AttributeName,
  11566. extensionDerivatives: material.extensions && material.extensions.derivatives,
  11567. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  11568. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  11569. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  11570. rendererExtensionFragDepth: isWebGL2 || extensions.has( 'EXT_frag_depth' ),
  11571. rendererExtensionDrawBuffers: isWebGL2 || extensions.has( 'WEBGL_draw_buffers' ),
  11572. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has( 'EXT_shader_texture_lod' ),
  11573. customProgramCacheKey: material.customProgramCacheKey()
  11574. };
  11575. return parameters;
  11576. }
  11577. function getProgramCacheKey( parameters ) {
  11578. const array = [];
  11579. if ( parameters.shaderID ) {
  11580. array.push( parameters.shaderID );
  11581. } else {
  11582. array.push( hashString( parameters.fragmentShader ) );
  11583. array.push( hashString( parameters.vertexShader ) );
  11584. }
  11585. if ( parameters.defines !== undefined ) {
  11586. for ( const name in parameters.defines ) {
  11587. array.push( name );
  11588. array.push( parameters.defines[ name ] );
  11589. }
  11590. }
  11591. if ( parameters.isRawShaderMaterial === false ) {
  11592. for ( let i = 0; i < parameterNames.length; i ++ ) {
  11593. array.push( parameters[ parameterNames[ i ] ] );
  11594. }
  11595. array.push( renderer.outputEncoding );
  11596. array.push( renderer.gammaFactor );
  11597. }
  11598. array.push( parameters.customProgramCacheKey );
  11599. return array.join();
  11600. }
  11601. function getUniforms( material ) {
  11602. const shaderID = shaderIDs[ material.type ];
  11603. let uniforms;
  11604. if ( shaderID ) {
  11605. const shader = ShaderLib[ shaderID ];
  11606. uniforms = UniformsUtils.clone( shader.uniforms );
  11607. } else {
  11608. uniforms = material.uniforms;
  11609. }
  11610. return uniforms;
  11611. }
  11612. function acquireProgram( parameters, cacheKey ) {
  11613. let program;
  11614. // Check if code has been already compiled
  11615. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  11616. const preexistingProgram = programs[ p ];
  11617. if ( preexistingProgram.cacheKey === cacheKey ) {
  11618. program = preexistingProgram;
  11619. ++ program.usedTimes;
  11620. break;
  11621. }
  11622. }
  11623. if ( program === undefined ) {
  11624. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  11625. programs.push( program );
  11626. }
  11627. return program;
  11628. }
  11629. function releaseProgram( program ) {
  11630. if ( -- program.usedTimes === 0 ) {
  11631. // Remove from unordered set
  11632. const i = programs.indexOf( program );
  11633. programs[ i ] = programs[ programs.length - 1 ];
  11634. programs.pop();
  11635. // Free WebGL resources
  11636. program.destroy();
  11637. }
  11638. }
  11639. return {
  11640. getParameters: getParameters,
  11641. getProgramCacheKey: getProgramCacheKey,
  11642. getUniforms: getUniforms,
  11643. acquireProgram: acquireProgram,
  11644. releaseProgram: releaseProgram,
  11645. // Exposed for resource monitoring & error feedback via renderer.info:
  11646. programs: programs
  11647. };
  11648. }
  11649. function WebGLProperties() {
  11650. let properties = new WeakMap();
  11651. function get( object ) {
  11652. let map = properties.get( object );
  11653. if ( map === undefined ) {
  11654. map = {};
  11655. properties.set( object, map );
  11656. }
  11657. return map;
  11658. }
  11659. function remove( object ) {
  11660. properties.delete( object );
  11661. }
  11662. function update( object, key, value ) {
  11663. properties.get( object )[ key ] = value;
  11664. }
  11665. function dispose() {
  11666. properties = new WeakMap();
  11667. }
  11668. return {
  11669. get: get,
  11670. remove: remove,
  11671. update: update,
  11672. dispose: dispose
  11673. };
  11674. }
  11675. function painterSortStable( a, b ) {
  11676. if ( a.groupOrder !== b.groupOrder ) {
  11677. return a.groupOrder - b.groupOrder;
  11678. } else if ( a.renderOrder !== b.renderOrder ) {
  11679. return a.renderOrder - b.renderOrder;
  11680. } else if ( a.program !== b.program ) {
  11681. return a.program.id - b.program.id;
  11682. } else if ( a.material.id !== b.material.id ) {
  11683. return a.material.id - b.material.id;
  11684. } else if ( a.z !== b.z ) {
  11685. return a.z - b.z;
  11686. } else {
  11687. return a.id - b.id;
  11688. }
  11689. }
  11690. function reversePainterSortStable( a, b ) {
  11691. if ( a.groupOrder !== b.groupOrder ) {
  11692. return a.groupOrder - b.groupOrder;
  11693. } else if ( a.renderOrder !== b.renderOrder ) {
  11694. return a.renderOrder - b.renderOrder;
  11695. } else if ( a.z !== b.z ) {
  11696. return b.z - a.z;
  11697. } else {
  11698. return a.id - b.id;
  11699. }
  11700. }
  11701. function WebGLRenderList( properties ) {
  11702. const renderItems = [];
  11703. let renderItemsIndex = 0;
  11704. const opaque = [];
  11705. const transmissive = [];
  11706. const transparent = [];
  11707. const defaultProgram = { id: - 1 };
  11708. function init() {
  11709. renderItemsIndex = 0;
  11710. opaque.length = 0;
  11711. transmissive.length = 0;
  11712. transparent.length = 0;
  11713. }
  11714. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  11715. let renderItem = renderItems[ renderItemsIndex ];
  11716. const materialProperties = properties.get( material );
  11717. if ( renderItem === undefined ) {
  11718. renderItem = {
  11719. id: object.id,
  11720. object: object,
  11721. geometry: geometry,
  11722. material: material,
  11723. program: materialProperties.program || defaultProgram,
  11724. groupOrder: groupOrder,
  11725. renderOrder: object.renderOrder,
  11726. z: z,
  11727. group: group
  11728. };
  11729. renderItems[ renderItemsIndex ] = renderItem;
  11730. } else {
  11731. renderItem.id = object.id;
  11732. renderItem.object = object;
  11733. renderItem.geometry = geometry;
  11734. renderItem.material = material;
  11735. renderItem.program = materialProperties.program || defaultProgram;
  11736. renderItem.groupOrder = groupOrder;
  11737. renderItem.renderOrder = object.renderOrder;
  11738. renderItem.z = z;
  11739. renderItem.group = group;
  11740. }
  11741. renderItemsIndex ++;
  11742. return renderItem;
  11743. }
  11744. function push( object, geometry, material, groupOrder, z, group ) {
  11745. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  11746. if ( material.transmission > 0.0 ) {
  11747. transmissive.push( renderItem );
  11748. } else if ( material.transparent === true ) {
  11749. transparent.push( renderItem );
  11750. } else {
  11751. opaque.push( renderItem );
  11752. }
  11753. }
  11754. function unshift( object, geometry, material, groupOrder, z, group ) {
  11755. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  11756. if ( material.transmission > 0.0 ) {
  11757. transmissive.unshift( renderItem );
  11758. } else if ( material.transparent === true ) {
  11759. transparent.unshift( renderItem );
  11760. } else {
  11761. opaque.unshift( renderItem );
  11762. }
  11763. }
  11764. function sort( customOpaqueSort, customTransparentSort ) {
  11765. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  11766. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  11767. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  11768. }
  11769. function finish() {
  11770. // Clear references from inactive renderItems in the list
  11771. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  11772. const renderItem = renderItems[ i ];
  11773. if ( renderItem.id === null ) break;
  11774. renderItem.id = null;
  11775. renderItem.object = null;
  11776. renderItem.geometry = null;
  11777. renderItem.material = null;
  11778. renderItem.program = null;
  11779. renderItem.group = null;
  11780. }
  11781. }
  11782. return {
  11783. opaque: opaque,
  11784. transmissive: transmissive,
  11785. transparent: transparent,
  11786. init: init,
  11787. push: push,
  11788. unshift: unshift,
  11789. finish: finish,
  11790. sort: sort
  11791. };
  11792. }
  11793. function WebGLRenderLists( properties ) {
  11794. let lists = new WeakMap();
  11795. function get( scene, renderCallDepth ) {
  11796. let list;
  11797. if ( lists.has( scene ) === false ) {
  11798. list = new WebGLRenderList( properties );
  11799. lists.set( scene, [ list ] );
  11800. } else {
  11801. if ( renderCallDepth >= lists.get( scene ).length ) {
  11802. list = new WebGLRenderList( properties );
  11803. lists.get( scene ).push( list );
  11804. } else {
  11805. list = lists.get( scene )[ renderCallDepth ];
  11806. }
  11807. }
  11808. return list;
  11809. }
  11810. function dispose() {
  11811. lists = new WeakMap();
  11812. }
  11813. return {
  11814. get: get,
  11815. dispose: dispose
  11816. };
  11817. }
  11818. function UniformsCache() {
  11819. const lights = {};
  11820. return {
  11821. get: function ( light ) {
  11822. if ( lights[ light.id ] !== undefined ) {
  11823. return lights[ light.id ];
  11824. }
  11825. let uniforms;
  11826. switch ( light.type ) {
  11827. case 'DirectionalLight':
  11828. uniforms = {
  11829. direction: new Vector3(),
  11830. color: new Color()
  11831. };
  11832. break;
  11833. case 'SpotLight':
  11834. uniforms = {
  11835. position: new Vector3(),
  11836. direction: new Vector3(),
  11837. color: new Color(),
  11838. distance: 0,
  11839. coneCos: 0,
  11840. penumbraCos: 0,
  11841. decay: 0
  11842. };
  11843. break;
  11844. case 'PointLight':
  11845. uniforms = {
  11846. position: new Vector3(),
  11847. color: new Color(),
  11848. distance: 0,
  11849. decay: 0
  11850. };
  11851. break;
  11852. case 'HemisphereLight':
  11853. uniforms = {
  11854. direction: new Vector3(),
  11855. skyColor: new Color(),
  11856. groundColor: new Color()
  11857. };
  11858. break;
  11859. case 'RectAreaLight':
  11860. uniforms = {
  11861. color: new Color(),
  11862. position: new Vector3(),
  11863. halfWidth: new Vector3(),
  11864. halfHeight: new Vector3()
  11865. };
  11866. break;
  11867. }
  11868. lights[ light.id ] = uniforms;
  11869. return uniforms;
  11870. }
  11871. };
  11872. }
  11873. function ShadowUniformsCache() {
  11874. const lights = {};
  11875. return {
  11876. get: function ( light ) {
  11877. if ( lights[ light.id ] !== undefined ) {
  11878. return lights[ light.id ];
  11879. }
  11880. let uniforms;
  11881. switch ( light.type ) {
  11882. case 'DirectionalLight':
  11883. uniforms = {
  11884. shadowBias: 0,
  11885. shadowNormalBias: 0,
  11886. shadowRadius: 1,
  11887. shadowMapSize: new Vector2()
  11888. };
  11889. break;
  11890. case 'SpotLight':
  11891. uniforms = {
  11892. shadowBias: 0,
  11893. shadowNormalBias: 0,
  11894. shadowRadius: 1,
  11895. shadowMapSize: new Vector2()
  11896. };
  11897. break;
  11898. case 'PointLight':
  11899. uniforms = {
  11900. shadowBias: 0,
  11901. shadowNormalBias: 0,
  11902. shadowRadius: 1,
  11903. shadowMapSize: new Vector2(),
  11904. shadowCameraNear: 1,
  11905. shadowCameraFar: 1000
  11906. };
  11907. break;
  11908. // TODO (abelnation): set RectAreaLight shadow uniforms
  11909. }
  11910. lights[ light.id ] = uniforms;
  11911. return uniforms;
  11912. }
  11913. };
  11914. }
  11915. let nextVersion = 0;
  11916. function shadowCastingLightsFirst( lightA, lightB ) {
  11917. return ( lightB.castShadow ? 1 : 0 ) - ( lightA.castShadow ? 1 : 0 );
  11918. }
  11919. function WebGLLights( extensions, capabilities ) {
  11920. const cache = new UniformsCache();
  11921. const shadowCache = ShadowUniformsCache();
  11922. const state = {
  11923. version: 0,
  11924. hash: {
  11925. directionalLength: - 1,
  11926. pointLength: - 1,
  11927. spotLength: - 1,
  11928. rectAreaLength: - 1,
  11929. hemiLength: - 1,
  11930. numDirectionalShadows: - 1,
  11931. numPointShadows: - 1,
  11932. numSpotShadows: - 1
  11933. },
  11934. ambient: [ 0, 0, 0 ],
  11935. probe: [],
  11936. directional: [],
  11937. directionalShadow: [],
  11938. directionalShadowMap: [],
  11939. directionalShadowMatrix: [],
  11940. spot: [],
  11941. spotShadow: [],
  11942. spotShadowMap: [],
  11943. spotShadowMatrix: [],
  11944. rectArea: [],
  11945. rectAreaLTC1: null,
  11946. rectAreaLTC2: null,
  11947. point: [],
  11948. pointShadow: [],
  11949. pointShadowMap: [],
  11950. pointShadowMatrix: [],
  11951. hemi: []
  11952. };
  11953. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  11954. const vector3 = new Vector3();
  11955. const matrix4 = new Matrix4();
  11956. const matrix42 = new Matrix4();
  11957. function setup( lights, physicallyCorrectLights ) {
  11958. let r = 0, g = 0, b = 0;
  11959. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  11960. let directionalLength = 0;
  11961. let pointLength = 0;
  11962. let spotLength = 0;
  11963. let rectAreaLength = 0;
  11964. let hemiLength = 0;
  11965. let numDirectionalShadows = 0;
  11966. let numPointShadows = 0;
  11967. let numSpotShadows = 0;
  11968. lights.sort( shadowCastingLightsFirst );
  11969. // artist-friendly light intensity scaling factor
  11970. const scaleFactor = ( physicallyCorrectLights !== true ) ? Math.PI : 1;
  11971. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  11972. const light = lights[ i ];
  11973. const color = light.color;
  11974. const intensity = light.intensity;
  11975. const distance = light.distance;
  11976. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  11977. if ( light.isAmbientLight ) {
  11978. r += color.r * intensity * scaleFactor;
  11979. g += color.g * intensity * scaleFactor;
  11980. b += color.b * intensity * scaleFactor;
  11981. } else if ( light.isLightProbe ) {
  11982. for ( let j = 0; j < 9; j ++ ) {
  11983. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  11984. }
  11985. } else if ( light.isDirectionalLight ) {
  11986. const uniforms = cache.get( light );
  11987. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  11988. if ( light.castShadow ) {
  11989. const shadow = light.shadow;
  11990. const shadowUniforms = shadowCache.get( light );
  11991. shadowUniforms.shadowBias = shadow.bias;
  11992. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11993. shadowUniforms.shadowRadius = shadow.radius;
  11994. shadowUniforms.shadowMapSize = shadow.mapSize;
  11995. state.directionalShadow[ directionalLength ] = shadowUniforms;
  11996. state.directionalShadowMap[ directionalLength ] = shadowMap;
  11997. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  11998. numDirectionalShadows ++;
  11999. }
  12000. state.directional[ directionalLength ] = uniforms;
  12001. directionalLength ++;
  12002. } else if ( light.isSpotLight ) {
  12003. const uniforms = cache.get( light );
  12004. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12005. uniforms.color.copy( color ).multiplyScalar( intensity * scaleFactor );
  12006. uniforms.distance = distance;
  12007. uniforms.coneCos = Math.cos( light.angle );
  12008. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  12009. uniforms.decay = light.decay;
  12010. if ( light.castShadow ) {
  12011. const shadow = light.shadow;
  12012. const shadowUniforms = shadowCache.get( light );
  12013. shadowUniforms.shadowBias = shadow.bias;
  12014. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12015. shadowUniforms.shadowRadius = shadow.radius;
  12016. shadowUniforms.shadowMapSize = shadow.mapSize;
  12017. state.spotShadow[ spotLength ] = shadowUniforms;
  12018. state.spotShadowMap[ spotLength ] = shadowMap;
  12019. state.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  12020. numSpotShadows ++;
  12021. }
  12022. state.spot[ spotLength ] = uniforms;
  12023. spotLength ++;
  12024. } else if ( light.isRectAreaLight ) {
  12025. const uniforms = cache.get( light );
  12026. // (a) intensity is the total visible light emitted
  12027. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  12028. // (b) intensity is the brightness of the light
  12029. uniforms.color.copy( color ).multiplyScalar( intensity );
  12030. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  12031. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  12032. state.rectArea[ rectAreaLength ] = uniforms;
  12033. rectAreaLength ++;
  12034. } else if ( light.isPointLight ) {
  12035. const uniforms = cache.get( light );
  12036. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12037. uniforms.distance = light.distance;
  12038. uniforms.decay = light.decay;
  12039. if ( light.castShadow ) {
  12040. const shadow = light.shadow;
  12041. const shadowUniforms = shadowCache.get( light );
  12042. shadowUniforms.shadowBias = shadow.bias;
  12043. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12044. shadowUniforms.shadowRadius = shadow.radius;
  12045. shadowUniforms.shadowMapSize = shadow.mapSize;
  12046. shadowUniforms.shadowCameraNear = shadow.camera.near;
  12047. shadowUniforms.shadowCameraFar = shadow.camera.far;
  12048. state.pointShadow[ pointLength ] = shadowUniforms;
  12049. state.pointShadowMap[ pointLength ] = shadowMap;
  12050. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  12051. numPointShadows ++;
  12052. }
  12053. state.point[ pointLength ] = uniforms;
  12054. pointLength ++;
  12055. } else if ( light.isHemisphereLight ) {
  12056. const uniforms = cache.get( light );
  12057. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity * scaleFactor );
  12058. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity * scaleFactor );
  12059. state.hemi[ hemiLength ] = uniforms;
  12060. hemiLength ++;
  12061. }
  12062. }
  12063. if ( rectAreaLength > 0 ) {
  12064. if ( capabilities.isWebGL2 ) {
  12065. // WebGL 2
  12066. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12067. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12068. } else {
  12069. // WebGL 1
  12070. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  12071. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12072. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12073. } else if ( extensions.has( 'OES_texture_half_float_linear' ) === true ) {
  12074. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  12075. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  12076. } else {
  12077. console.error( 'THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.' );
  12078. }
  12079. }
  12080. }
  12081. state.ambient[ 0 ] = r;
  12082. state.ambient[ 1 ] = g;
  12083. state.ambient[ 2 ] = b;
  12084. const hash = state.hash;
  12085. if ( hash.directionalLength !== directionalLength ||
  12086. hash.pointLength !== pointLength ||
  12087. hash.spotLength !== spotLength ||
  12088. hash.rectAreaLength !== rectAreaLength ||
  12089. hash.hemiLength !== hemiLength ||
  12090. hash.numDirectionalShadows !== numDirectionalShadows ||
  12091. hash.numPointShadows !== numPointShadows ||
  12092. hash.numSpotShadows !== numSpotShadows ) {
  12093. state.directional.length = directionalLength;
  12094. state.spot.length = spotLength;
  12095. state.rectArea.length = rectAreaLength;
  12096. state.point.length = pointLength;
  12097. state.hemi.length = hemiLength;
  12098. state.directionalShadow.length = numDirectionalShadows;
  12099. state.directionalShadowMap.length = numDirectionalShadows;
  12100. state.pointShadow.length = numPointShadows;
  12101. state.pointShadowMap.length = numPointShadows;
  12102. state.spotShadow.length = numSpotShadows;
  12103. state.spotShadowMap.length = numSpotShadows;
  12104. state.directionalShadowMatrix.length = numDirectionalShadows;
  12105. state.pointShadowMatrix.length = numPointShadows;
  12106. state.spotShadowMatrix.length = numSpotShadows;
  12107. hash.directionalLength = directionalLength;
  12108. hash.pointLength = pointLength;
  12109. hash.spotLength = spotLength;
  12110. hash.rectAreaLength = rectAreaLength;
  12111. hash.hemiLength = hemiLength;
  12112. hash.numDirectionalShadows = numDirectionalShadows;
  12113. hash.numPointShadows = numPointShadows;
  12114. hash.numSpotShadows = numSpotShadows;
  12115. state.version = nextVersion ++;
  12116. }
  12117. }
  12118. function setupView( lights, camera ) {
  12119. let directionalLength = 0;
  12120. let pointLength = 0;
  12121. let spotLength = 0;
  12122. let rectAreaLength = 0;
  12123. let hemiLength = 0;
  12124. const viewMatrix = camera.matrixWorldInverse;
  12125. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  12126. const light = lights[ i ];
  12127. if ( light.isDirectionalLight ) {
  12128. const uniforms = state.directional[ directionalLength ];
  12129. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12130. vector3.setFromMatrixPosition( light.target.matrixWorld );
  12131. uniforms.direction.sub( vector3 );
  12132. uniforms.direction.transformDirection( viewMatrix );
  12133. directionalLength ++;
  12134. } else if ( light.isSpotLight ) {
  12135. const uniforms = state.spot[ spotLength ];
  12136. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12137. uniforms.position.applyMatrix4( viewMatrix );
  12138. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12139. vector3.setFromMatrixPosition( light.target.matrixWorld );
  12140. uniforms.direction.sub( vector3 );
  12141. uniforms.direction.transformDirection( viewMatrix );
  12142. spotLength ++;
  12143. } else if ( light.isRectAreaLight ) {
  12144. const uniforms = state.rectArea[ rectAreaLength ];
  12145. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12146. uniforms.position.applyMatrix4( viewMatrix );
  12147. // extract local rotation of light to derive width/height half vectors
  12148. matrix42.identity();
  12149. matrix4.copy( light.matrixWorld );
  12150. matrix4.premultiply( viewMatrix );
  12151. matrix42.extractRotation( matrix4 );
  12152. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  12153. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  12154. uniforms.halfWidth.applyMatrix4( matrix42 );
  12155. uniforms.halfHeight.applyMatrix4( matrix42 );
  12156. rectAreaLength ++;
  12157. } else if ( light.isPointLight ) {
  12158. const uniforms = state.point[ pointLength ];
  12159. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12160. uniforms.position.applyMatrix4( viewMatrix );
  12161. pointLength ++;
  12162. } else if ( light.isHemisphereLight ) {
  12163. const uniforms = state.hemi[ hemiLength ];
  12164. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12165. uniforms.direction.transformDirection( viewMatrix );
  12166. uniforms.direction.normalize();
  12167. hemiLength ++;
  12168. }
  12169. }
  12170. }
  12171. return {
  12172. setup: setup,
  12173. setupView: setupView,
  12174. state: state
  12175. };
  12176. }
  12177. function WebGLRenderState( extensions, capabilities ) {
  12178. const lights = new WebGLLights( extensions, capabilities );
  12179. const lightsArray = [];
  12180. const shadowsArray = [];
  12181. function init() {
  12182. lightsArray.length = 0;
  12183. shadowsArray.length = 0;
  12184. }
  12185. function pushLight( light ) {
  12186. lightsArray.push( light );
  12187. }
  12188. function pushShadow( shadowLight ) {
  12189. shadowsArray.push( shadowLight );
  12190. }
  12191. function setupLights( physicallyCorrectLights ) {
  12192. lights.setup( lightsArray, physicallyCorrectLights );
  12193. }
  12194. function setupLightsView( camera ) {
  12195. lights.setupView( lightsArray, camera );
  12196. }
  12197. const state = {
  12198. lightsArray: lightsArray,
  12199. shadowsArray: shadowsArray,
  12200. lights: lights
  12201. };
  12202. return {
  12203. init: init,
  12204. state: state,
  12205. setupLights: setupLights,
  12206. setupLightsView: setupLightsView,
  12207. pushLight: pushLight,
  12208. pushShadow: pushShadow
  12209. };
  12210. }
  12211. function WebGLRenderStates( extensions, capabilities ) {
  12212. let renderStates = new WeakMap();
  12213. function get( scene, renderCallDepth = 0 ) {
  12214. let renderState;
  12215. if ( renderStates.has( scene ) === false ) {
  12216. renderState = new WebGLRenderState( extensions, capabilities );
  12217. renderStates.set( scene, [ renderState ] );
  12218. } else {
  12219. if ( renderCallDepth >= renderStates.get( scene ).length ) {
  12220. renderState = new WebGLRenderState( extensions, capabilities );
  12221. renderStates.get( scene ).push( renderState );
  12222. } else {
  12223. renderState = renderStates.get( scene )[ renderCallDepth ];
  12224. }
  12225. }
  12226. return renderState;
  12227. }
  12228. function dispose() {
  12229. renderStates = new WeakMap();
  12230. }
  12231. return {
  12232. get: get,
  12233. dispose: dispose
  12234. };
  12235. }
  12236. /**
  12237. * parameters = {
  12238. *
  12239. * opacity: <float>,
  12240. *
  12241. * map: new THREE.Texture( <Image> ),
  12242. *
  12243. * alphaMap: new THREE.Texture( <Image> ),
  12244. *
  12245. * displacementMap: new THREE.Texture( <Image> ),
  12246. * displacementScale: <float>,
  12247. * displacementBias: <float>,
  12248. *
  12249. * wireframe: <boolean>,
  12250. * wireframeLinewidth: <float>
  12251. * }
  12252. */
  12253. class MeshDepthMaterial extends Material {
  12254. constructor( parameters ) {
  12255. super();
  12256. this.type = 'MeshDepthMaterial';
  12257. this.depthPacking = BasicDepthPacking;
  12258. this.map = null;
  12259. this.alphaMap = null;
  12260. this.displacementMap = null;
  12261. this.displacementScale = 1;
  12262. this.displacementBias = 0;
  12263. this.wireframe = false;
  12264. this.wireframeLinewidth = 1;
  12265. this.fog = false;
  12266. this.setValues( parameters );
  12267. }
  12268. copy( source ) {
  12269. super.copy( source );
  12270. this.depthPacking = source.depthPacking;
  12271. this.map = source.map;
  12272. this.alphaMap = source.alphaMap;
  12273. this.displacementMap = source.displacementMap;
  12274. this.displacementScale = source.displacementScale;
  12275. this.displacementBias = source.displacementBias;
  12276. this.wireframe = source.wireframe;
  12277. this.wireframeLinewidth = source.wireframeLinewidth;
  12278. return this;
  12279. }
  12280. }
  12281. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  12282. /**
  12283. * parameters = {
  12284. *
  12285. * referencePosition: <float>,
  12286. * nearDistance: <float>,
  12287. * farDistance: <float>,
  12288. *
  12289. * map: new THREE.Texture( <Image> ),
  12290. *
  12291. * alphaMap: new THREE.Texture( <Image> ),
  12292. *
  12293. * displacementMap: new THREE.Texture( <Image> ),
  12294. * displacementScale: <float>,
  12295. * displacementBias: <float>
  12296. *
  12297. * }
  12298. */
  12299. class MeshDistanceMaterial extends Material {
  12300. constructor( parameters ) {
  12301. super();
  12302. this.type = 'MeshDistanceMaterial';
  12303. this.referencePosition = new Vector3();
  12304. this.nearDistance = 1;
  12305. this.farDistance = 1000;
  12306. this.map = null;
  12307. this.alphaMap = null;
  12308. this.displacementMap = null;
  12309. this.displacementScale = 1;
  12310. this.displacementBias = 0;
  12311. this.fog = false;
  12312. this.setValues( parameters );
  12313. }
  12314. copy( source ) {
  12315. super.copy( source );
  12316. this.referencePosition.copy( source.referencePosition );
  12317. this.nearDistance = source.nearDistance;
  12318. this.farDistance = source.farDistance;
  12319. this.map = source.map;
  12320. this.alphaMap = source.alphaMap;
  12321. this.displacementMap = source.displacementMap;
  12322. this.displacementScale = source.displacementScale;
  12323. this.displacementBias = source.displacementBias;
  12324. return this;
  12325. }
  12326. }
  12327. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  12328. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12329. const fragment = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\nuniform float samples;\n#include <packing>\nvoid main() {\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";
  12330. function WebGLShadowMap( _renderer, _objects, _capabilities ) {
  12331. let _frustum = new Frustum();
  12332. const _shadowMapSize = new Vector2(),
  12333. _viewportSize = new Vector2(),
  12334. _viewport = new Vector4(),
  12335. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  12336. _distanceMaterial = new MeshDistanceMaterial(),
  12337. _materialCache = {},
  12338. _maxTextureSize = _capabilities.maxTextureSize;
  12339. const shadowSide = { 0: BackSide, 1: FrontSide, 2: DoubleSide };
  12340. const shadowMaterialVertical = new ShaderMaterial( {
  12341. uniforms: {
  12342. shadow_pass: { value: null },
  12343. resolution: { value: new Vector2() },
  12344. radius: { value: 4.0 },
  12345. samples: { value: 8.0 }
  12346. },
  12347. vertexShader: vertex,
  12348. fragmentShader: fragment
  12349. } );
  12350. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  12351. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  12352. const fullScreenTri = new BufferGeometry();
  12353. fullScreenTri.setAttribute(
  12354. 'position',
  12355. new BufferAttribute(
  12356. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  12357. 3
  12358. )
  12359. );
  12360. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  12361. const scope = this;
  12362. this.enabled = false;
  12363. this.autoUpdate = true;
  12364. this.needsUpdate = false;
  12365. this.type = PCFShadowMap;
  12366. this.render = function ( lights, scene, camera ) {
  12367. if ( scope.enabled === false ) return;
  12368. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  12369. if ( lights.length === 0 ) return;
  12370. const currentRenderTarget = _renderer.getRenderTarget();
  12371. const activeCubeFace = _renderer.getActiveCubeFace();
  12372. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12373. const _state = _renderer.state;
  12374. // Set GL state for depth map.
  12375. _state.setBlending( NoBlending );
  12376. _state.buffers.color.setClear( 1, 1, 1, 1 );
  12377. _state.buffers.depth.setTest( true );
  12378. _state.setScissorTest( false );
  12379. // render depth map
  12380. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  12381. const light = lights[ i ];
  12382. const shadow = light.shadow;
  12383. if ( shadow === undefined ) {
  12384. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  12385. continue;
  12386. }
  12387. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  12388. _shadowMapSize.copy( shadow.mapSize );
  12389. const shadowFrameExtents = shadow.getFrameExtents();
  12390. _shadowMapSize.multiply( shadowFrameExtents );
  12391. _viewportSize.copy( shadow.mapSize );
  12392. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  12393. if ( _shadowMapSize.x > _maxTextureSize ) {
  12394. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  12395. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12396. shadow.mapSize.x = _viewportSize.x;
  12397. }
  12398. if ( _shadowMapSize.y > _maxTextureSize ) {
  12399. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  12400. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  12401. shadow.mapSize.y = _viewportSize.y;
  12402. }
  12403. }
  12404. if ( shadow.map === null && ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {
  12405. const pars = { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat };
  12406. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  12407. shadow.map.texture.name = light.name + '.shadowMap';
  12408. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  12409. shadow.camera.updateProjectionMatrix();
  12410. }
  12411. if ( shadow.map === null ) {
  12412. const pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  12413. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  12414. shadow.map.texture.name = light.name + '.shadowMap';
  12415. shadow.camera.updateProjectionMatrix();
  12416. }
  12417. _renderer.setRenderTarget( shadow.map );
  12418. _renderer.clear();
  12419. const viewportCount = shadow.getViewportCount();
  12420. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  12421. const viewport = shadow.getViewport( vp );
  12422. _viewport.set(
  12423. _viewportSize.x * viewport.x,
  12424. _viewportSize.y * viewport.y,
  12425. _viewportSize.x * viewport.z,
  12426. _viewportSize.y * viewport.w
  12427. );
  12428. _state.viewport( _viewport );
  12429. shadow.updateMatrices( light, vp );
  12430. _frustum = shadow.getFrustum();
  12431. renderObject( scene, camera, shadow.camera, light, this.type );
  12432. }
  12433. // do blur pass for VSM
  12434. if ( ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {
  12435. VSMPass( shadow, camera );
  12436. }
  12437. shadow.needsUpdate = false;
  12438. }
  12439. scope.needsUpdate = false;
  12440. _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  12441. };
  12442. function VSMPass( shadow, camera ) {
  12443. const geometry = _objects.update( fullScreenMesh );
  12444. // vertical pass
  12445. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  12446. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  12447. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  12448. shadowMaterialVertical.uniforms.samples.value = shadow.blurSamples;
  12449. _renderer.setRenderTarget( shadow.mapPass );
  12450. _renderer.clear();
  12451. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  12452. // horizontal pass
  12453. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  12454. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  12455. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  12456. shadowMaterialHorizontal.uniforms.samples.value = shadow.blurSamples;
  12457. _renderer.setRenderTarget( shadow.map );
  12458. _renderer.clear();
  12459. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  12460. }
  12461. function getDepthMaterial( object, geometry, material, light, shadowCameraNear, shadowCameraFar, type ) {
  12462. let result = null;
  12463. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  12464. if ( customMaterial !== undefined ) {
  12465. result = customMaterial;
  12466. } else {
  12467. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  12468. }
  12469. if ( ( _renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0 ) ||
  12470. ( material.displacementMap && material.displacementScale !== 0 ) ||
  12471. ( material.alphaMap && material.alphaTest > 0 ) ) {
  12472. // in this case we need a unique material instance reflecting the
  12473. // appropriate state
  12474. const keyA = result.uuid, keyB = material.uuid;
  12475. let materialsForVariant = _materialCache[ keyA ];
  12476. if ( materialsForVariant === undefined ) {
  12477. materialsForVariant = {};
  12478. _materialCache[ keyA ] = materialsForVariant;
  12479. }
  12480. let cachedMaterial = materialsForVariant[ keyB ];
  12481. if ( cachedMaterial === undefined ) {
  12482. cachedMaterial = result.clone();
  12483. materialsForVariant[ keyB ] = cachedMaterial;
  12484. }
  12485. result = cachedMaterial;
  12486. }
  12487. result.visible = material.visible;
  12488. result.wireframe = material.wireframe;
  12489. if ( type === VSMShadowMap ) {
  12490. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  12491. } else {
  12492. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  12493. }
  12494. result.alphaMap = material.alphaMap;
  12495. result.alphaTest = material.alphaTest;
  12496. result.clipShadows = material.clipShadows;
  12497. result.clippingPlanes = material.clippingPlanes;
  12498. result.clipIntersection = material.clipIntersection;
  12499. result.displacementMap = material.displacementMap;
  12500. result.displacementScale = material.displacementScale;
  12501. result.displacementBias = material.displacementBias;
  12502. result.wireframeLinewidth = material.wireframeLinewidth;
  12503. result.linewidth = material.linewidth;
  12504. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  12505. result.referencePosition.setFromMatrixPosition( light.matrixWorld );
  12506. result.nearDistance = shadowCameraNear;
  12507. result.farDistance = shadowCameraFar;
  12508. }
  12509. return result;
  12510. }
  12511. function renderObject( object, camera, shadowCamera, light, type ) {
  12512. if ( object.visible === false ) return;
  12513. const visible = object.layers.test( camera.layers );
  12514. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  12515. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  12516. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  12517. const geometry = _objects.update( object );
  12518. const material = object.material;
  12519. if ( Array.isArray( material ) ) {
  12520. const groups = geometry.groups;
  12521. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  12522. const group = groups[ k ];
  12523. const groupMaterial = material[ group.materialIndex ];
  12524. if ( groupMaterial && groupMaterial.visible ) {
  12525. const depthMaterial = getDepthMaterial( object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type );
  12526. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  12527. }
  12528. }
  12529. } else if ( material.visible ) {
  12530. const depthMaterial = getDepthMaterial( object, geometry, material, light, shadowCamera.near, shadowCamera.far, type );
  12531. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  12532. }
  12533. }
  12534. }
  12535. const children = object.children;
  12536. for ( let i = 0, l = children.length; i < l; i ++ ) {
  12537. renderObject( children[ i ], camera, shadowCamera, light, type );
  12538. }
  12539. }
  12540. }
  12541. function WebGLState( gl, extensions, capabilities ) {
  12542. const isWebGL2 = capabilities.isWebGL2;
  12543. function ColorBuffer() {
  12544. let locked = false;
  12545. const color = new Vector4();
  12546. let currentColorMask = null;
  12547. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  12548. return {
  12549. setMask: function ( colorMask ) {
  12550. if ( currentColorMask !== colorMask && ! locked ) {
  12551. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  12552. currentColorMask = colorMask;
  12553. }
  12554. },
  12555. setLocked: function ( lock ) {
  12556. locked = lock;
  12557. },
  12558. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  12559. if ( premultipliedAlpha === true ) {
  12560. r *= a; g *= a; b *= a;
  12561. }
  12562. color.set( r, g, b, a );
  12563. if ( currentColorClear.equals( color ) === false ) {
  12564. gl.clearColor( r, g, b, a );
  12565. currentColorClear.copy( color );
  12566. }
  12567. },
  12568. reset: function () {
  12569. locked = false;
  12570. currentColorMask = null;
  12571. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  12572. }
  12573. };
  12574. }
  12575. function DepthBuffer() {
  12576. let locked = false;
  12577. let currentDepthMask = null;
  12578. let currentDepthFunc = null;
  12579. let currentDepthClear = null;
  12580. return {
  12581. setTest: function ( depthTest ) {
  12582. if ( depthTest ) {
  12583. enable( 2929 );
  12584. } else {
  12585. disable( 2929 );
  12586. }
  12587. },
  12588. setMask: function ( depthMask ) {
  12589. if ( currentDepthMask !== depthMask && ! locked ) {
  12590. gl.depthMask( depthMask );
  12591. currentDepthMask = depthMask;
  12592. }
  12593. },
  12594. setFunc: function ( depthFunc ) {
  12595. if ( currentDepthFunc !== depthFunc ) {
  12596. if ( depthFunc ) {
  12597. switch ( depthFunc ) {
  12598. case NeverDepth:
  12599. gl.depthFunc( 512 );
  12600. break;
  12601. case AlwaysDepth:
  12602. gl.depthFunc( 519 );
  12603. break;
  12604. case LessDepth:
  12605. gl.depthFunc( 513 );
  12606. break;
  12607. case LessEqualDepth:
  12608. gl.depthFunc( 515 );
  12609. break;
  12610. case EqualDepth:
  12611. gl.depthFunc( 514 );
  12612. break;
  12613. case GreaterEqualDepth:
  12614. gl.depthFunc( 518 );
  12615. break;
  12616. case GreaterDepth:
  12617. gl.depthFunc( 516 );
  12618. break;
  12619. case NotEqualDepth:
  12620. gl.depthFunc( 517 );
  12621. break;
  12622. default:
  12623. gl.depthFunc( 515 );
  12624. }
  12625. } else {
  12626. gl.depthFunc( 515 );
  12627. }
  12628. currentDepthFunc = depthFunc;
  12629. }
  12630. },
  12631. setLocked: function ( lock ) {
  12632. locked = lock;
  12633. },
  12634. setClear: function ( depth ) {
  12635. if ( currentDepthClear !== depth ) {
  12636. gl.clearDepth( depth );
  12637. currentDepthClear = depth;
  12638. }
  12639. },
  12640. reset: function () {
  12641. locked = false;
  12642. currentDepthMask = null;
  12643. currentDepthFunc = null;
  12644. currentDepthClear = null;
  12645. }
  12646. };
  12647. }
  12648. function StencilBuffer() {
  12649. let locked = false;
  12650. let currentStencilMask = null;
  12651. let currentStencilFunc = null;
  12652. let currentStencilRef = null;
  12653. let currentStencilFuncMask = null;
  12654. let currentStencilFail = null;
  12655. let currentStencilZFail = null;
  12656. let currentStencilZPass = null;
  12657. let currentStencilClear = null;
  12658. return {
  12659. setTest: function ( stencilTest ) {
  12660. if ( ! locked ) {
  12661. if ( stencilTest ) {
  12662. enable( 2960 );
  12663. } else {
  12664. disable( 2960 );
  12665. }
  12666. }
  12667. },
  12668. setMask: function ( stencilMask ) {
  12669. if ( currentStencilMask !== stencilMask && ! locked ) {
  12670. gl.stencilMask( stencilMask );
  12671. currentStencilMask = stencilMask;
  12672. }
  12673. },
  12674. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  12675. if ( currentStencilFunc !== stencilFunc ||
  12676. currentStencilRef !== stencilRef ||
  12677. currentStencilFuncMask !== stencilMask ) {
  12678. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  12679. currentStencilFunc = stencilFunc;
  12680. currentStencilRef = stencilRef;
  12681. currentStencilFuncMask = stencilMask;
  12682. }
  12683. },
  12684. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  12685. if ( currentStencilFail !== stencilFail ||
  12686. currentStencilZFail !== stencilZFail ||
  12687. currentStencilZPass !== stencilZPass ) {
  12688. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  12689. currentStencilFail = stencilFail;
  12690. currentStencilZFail = stencilZFail;
  12691. currentStencilZPass = stencilZPass;
  12692. }
  12693. },
  12694. setLocked: function ( lock ) {
  12695. locked = lock;
  12696. },
  12697. setClear: function ( stencil ) {
  12698. if ( currentStencilClear !== stencil ) {
  12699. gl.clearStencil( stencil );
  12700. currentStencilClear = stencil;
  12701. }
  12702. },
  12703. reset: function () {
  12704. locked = false;
  12705. currentStencilMask = null;
  12706. currentStencilFunc = null;
  12707. currentStencilRef = null;
  12708. currentStencilFuncMask = null;
  12709. currentStencilFail = null;
  12710. currentStencilZFail = null;
  12711. currentStencilZPass = null;
  12712. currentStencilClear = null;
  12713. }
  12714. };
  12715. }
  12716. //
  12717. const colorBuffer = new ColorBuffer();
  12718. const depthBuffer = new DepthBuffer();
  12719. const stencilBuffer = new StencilBuffer();
  12720. let enabledCapabilities = {};
  12721. let xrFramebuffer = null;
  12722. let currentBoundFramebuffers = {};
  12723. let currentProgram = null;
  12724. let currentBlendingEnabled = false;
  12725. let currentBlending = null;
  12726. let currentBlendEquation = null;
  12727. let currentBlendSrc = null;
  12728. let currentBlendDst = null;
  12729. let currentBlendEquationAlpha = null;
  12730. let currentBlendSrcAlpha = null;
  12731. let currentBlendDstAlpha = null;
  12732. let currentPremultipledAlpha = false;
  12733. let currentFlipSided = null;
  12734. let currentCullFace = null;
  12735. let currentLineWidth = null;
  12736. let currentPolygonOffsetFactor = null;
  12737. let currentPolygonOffsetUnits = null;
  12738. const maxTextures = gl.getParameter( 35661 );
  12739. let lineWidthAvailable = false;
  12740. let version = 0;
  12741. const glVersion = gl.getParameter( 7938 );
  12742. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  12743. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  12744. lineWidthAvailable = ( version >= 1.0 );
  12745. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  12746. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  12747. lineWidthAvailable = ( version >= 2.0 );
  12748. }
  12749. let currentTextureSlot = null;
  12750. let currentBoundTextures = {};
  12751. const scissorParam = gl.getParameter( 3088 );
  12752. const viewportParam = gl.getParameter( 2978 );
  12753. const currentScissor = new Vector4().fromArray( scissorParam );
  12754. const currentViewport = new Vector4().fromArray( viewportParam );
  12755. function createTexture( type, target, count ) {
  12756. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  12757. const texture = gl.createTexture();
  12758. gl.bindTexture( type, texture );
  12759. gl.texParameteri( type, 10241, 9728 );
  12760. gl.texParameteri( type, 10240, 9728 );
  12761. for ( let i = 0; i < count; i ++ ) {
  12762. gl.texImage2D( target + i, 0, 6408, 1, 1, 0, 6408, 5121, data );
  12763. }
  12764. return texture;
  12765. }
  12766. const emptyTextures = {};
  12767. emptyTextures[ 3553 ] = createTexture( 3553, 3553, 1 );
  12768. emptyTextures[ 34067 ] = createTexture( 34067, 34069, 6 );
  12769. // init
  12770. colorBuffer.setClear( 0, 0, 0, 1 );
  12771. depthBuffer.setClear( 1 );
  12772. stencilBuffer.setClear( 0 );
  12773. enable( 2929 );
  12774. depthBuffer.setFunc( LessEqualDepth );
  12775. setFlipSided( false );
  12776. setCullFace( CullFaceBack );
  12777. enable( 2884 );
  12778. setBlending( NoBlending );
  12779. //
  12780. function enable( id ) {
  12781. if ( enabledCapabilities[ id ] !== true ) {
  12782. gl.enable( id );
  12783. enabledCapabilities[ id ] = true;
  12784. }
  12785. }
  12786. function disable( id ) {
  12787. if ( enabledCapabilities[ id ] !== false ) {
  12788. gl.disable( id );
  12789. enabledCapabilities[ id ] = false;
  12790. }
  12791. }
  12792. function bindXRFramebuffer( framebuffer ) {
  12793. if ( framebuffer !== xrFramebuffer ) {
  12794. gl.bindFramebuffer( 36160, framebuffer );
  12795. xrFramebuffer = framebuffer;
  12796. }
  12797. }
  12798. function bindFramebuffer( target, framebuffer ) {
  12799. if ( framebuffer === null && xrFramebuffer !== null ) framebuffer = xrFramebuffer; // use active XR framebuffer if available
  12800. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  12801. gl.bindFramebuffer( target, framebuffer );
  12802. currentBoundFramebuffers[ target ] = framebuffer;
  12803. if ( isWebGL2 ) {
  12804. // 36009 is equivalent to 36160
  12805. if ( target === 36009 ) {
  12806. currentBoundFramebuffers[ 36160 ] = framebuffer;
  12807. }
  12808. if ( target === 36160 ) {
  12809. currentBoundFramebuffers[ 36009 ] = framebuffer;
  12810. }
  12811. }
  12812. return true;
  12813. }
  12814. return false;
  12815. }
  12816. function useProgram( program ) {
  12817. if ( currentProgram !== program ) {
  12818. gl.useProgram( program );
  12819. currentProgram = program;
  12820. return true;
  12821. }
  12822. return false;
  12823. }
  12824. const equationToGL = {
  12825. [ AddEquation ]: 32774,
  12826. [ SubtractEquation ]: 32778,
  12827. [ ReverseSubtractEquation ]: 32779
  12828. };
  12829. if ( isWebGL2 ) {
  12830. equationToGL[ MinEquation ] = 32775;
  12831. equationToGL[ MaxEquation ] = 32776;
  12832. } else {
  12833. const extension = extensions.get( 'EXT_blend_minmax' );
  12834. if ( extension !== null ) {
  12835. equationToGL[ MinEquation ] = extension.MIN_EXT;
  12836. equationToGL[ MaxEquation ] = extension.MAX_EXT;
  12837. }
  12838. }
  12839. const factorToGL = {
  12840. [ ZeroFactor ]: 0,
  12841. [ OneFactor ]: 1,
  12842. [ SrcColorFactor ]: 768,
  12843. [ SrcAlphaFactor ]: 770,
  12844. [ SrcAlphaSaturateFactor ]: 776,
  12845. [ DstColorFactor ]: 774,
  12846. [ DstAlphaFactor ]: 772,
  12847. [ OneMinusSrcColorFactor ]: 769,
  12848. [ OneMinusSrcAlphaFactor ]: 771,
  12849. [ OneMinusDstColorFactor ]: 775,
  12850. [ OneMinusDstAlphaFactor ]: 773
  12851. };
  12852. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  12853. if ( blending === NoBlending ) {
  12854. if ( currentBlendingEnabled === true ) {
  12855. disable( 3042 );
  12856. currentBlendingEnabled = false;
  12857. }
  12858. return;
  12859. }
  12860. if ( currentBlendingEnabled === false ) {
  12861. enable( 3042 );
  12862. currentBlendingEnabled = true;
  12863. }
  12864. if ( blending !== CustomBlending ) {
  12865. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  12866. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  12867. gl.blendEquation( 32774 );
  12868. currentBlendEquation = AddEquation;
  12869. currentBlendEquationAlpha = AddEquation;
  12870. }
  12871. if ( premultipliedAlpha ) {
  12872. switch ( blending ) {
  12873. case NormalBlending:
  12874. gl.blendFuncSeparate( 1, 771, 1, 771 );
  12875. break;
  12876. case AdditiveBlending:
  12877. gl.blendFunc( 1, 1 );
  12878. break;
  12879. case SubtractiveBlending:
  12880. gl.blendFuncSeparate( 0, 0, 769, 771 );
  12881. break;
  12882. case MultiplyBlending:
  12883. gl.blendFuncSeparate( 0, 768, 0, 770 );
  12884. break;
  12885. default:
  12886. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  12887. break;
  12888. }
  12889. } else {
  12890. switch ( blending ) {
  12891. case NormalBlending:
  12892. gl.blendFuncSeparate( 770, 771, 1, 771 );
  12893. break;
  12894. case AdditiveBlending:
  12895. gl.blendFunc( 770, 1 );
  12896. break;
  12897. case SubtractiveBlending:
  12898. gl.blendFunc( 0, 769 );
  12899. break;
  12900. case MultiplyBlending:
  12901. gl.blendFunc( 0, 768 );
  12902. break;
  12903. default:
  12904. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  12905. break;
  12906. }
  12907. }
  12908. currentBlendSrc = null;
  12909. currentBlendDst = null;
  12910. currentBlendSrcAlpha = null;
  12911. currentBlendDstAlpha = null;
  12912. currentBlending = blending;
  12913. currentPremultipledAlpha = premultipliedAlpha;
  12914. }
  12915. return;
  12916. }
  12917. // custom blending
  12918. blendEquationAlpha = blendEquationAlpha || blendEquation;
  12919. blendSrcAlpha = blendSrcAlpha || blendSrc;
  12920. blendDstAlpha = blendDstAlpha || blendDst;
  12921. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  12922. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  12923. currentBlendEquation = blendEquation;
  12924. currentBlendEquationAlpha = blendEquationAlpha;
  12925. }
  12926. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  12927. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  12928. currentBlendSrc = blendSrc;
  12929. currentBlendDst = blendDst;
  12930. currentBlendSrcAlpha = blendSrcAlpha;
  12931. currentBlendDstAlpha = blendDstAlpha;
  12932. }
  12933. currentBlending = blending;
  12934. currentPremultipledAlpha = null;
  12935. }
  12936. function setMaterial( material, frontFaceCW ) {
  12937. material.side === DoubleSide
  12938. ? disable( 2884 )
  12939. : enable( 2884 );
  12940. let flipSided = ( material.side === BackSide );
  12941. if ( frontFaceCW ) flipSided = ! flipSided;
  12942. setFlipSided( flipSided );
  12943. ( material.blending === NormalBlending && material.transparent === false )
  12944. ? setBlending( NoBlending )
  12945. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  12946. depthBuffer.setFunc( material.depthFunc );
  12947. depthBuffer.setTest( material.depthTest );
  12948. depthBuffer.setMask( material.depthWrite );
  12949. colorBuffer.setMask( material.colorWrite );
  12950. const stencilWrite = material.stencilWrite;
  12951. stencilBuffer.setTest( stencilWrite );
  12952. if ( stencilWrite ) {
  12953. stencilBuffer.setMask( material.stencilWriteMask );
  12954. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  12955. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  12956. }
  12957. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12958. material.alphaToCoverage === true
  12959. ? enable( 32926 )
  12960. : disable( 32926 );
  12961. }
  12962. //
  12963. function setFlipSided( flipSided ) {
  12964. if ( currentFlipSided !== flipSided ) {
  12965. if ( flipSided ) {
  12966. gl.frontFace( 2304 );
  12967. } else {
  12968. gl.frontFace( 2305 );
  12969. }
  12970. currentFlipSided = flipSided;
  12971. }
  12972. }
  12973. function setCullFace( cullFace ) {
  12974. if ( cullFace !== CullFaceNone ) {
  12975. enable( 2884 );
  12976. if ( cullFace !== currentCullFace ) {
  12977. if ( cullFace === CullFaceBack ) {
  12978. gl.cullFace( 1029 );
  12979. } else if ( cullFace === CullFaceFront ) {
  12980. gl.cullFace( 1028 );
  12981. } else {
  12982. gl.cullFace( 1032 );
  12983. }
  12984. }
  12985. } else {
  12986. disable( 2884 );
  12987. }
  12988. currentCullFace = cullFace;
  12989. }
  12990. function setLineWidth( width ) {
  12991. if ( width !== currentLineWidth ) {
  12992. if ( lineWidthAvailable ) gl.lineWidth( width );
  12993. currentLineWidth = width;
  12994. }
  12995. }
  12996. function setPolygonOffset( polygonOffset, factor, units ) {
  12997. if ( polygonOffset ) {
  12998. enable( 32823 );
  12999. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  13000. gl.polygonOffset( factor, units );
  13001. currentPolygonOffsetFactor = factor;
  13002. currentPolygonOffsetUnits = units;
  13003. }
  13004. } else {
  13005. disable( 32823 );
  13006. }
  13007. }
  13008. function setScissorTest( scissorTest ) {
  13009. if ( scissorTest ) {
  13010. enable( 3089 );
  13011. } else {
  13012. disable( 3089 );
  13013. }
  13014. }
  13015. // texture
  13016. function activeTexture( webglSlot ) {
  13017. if ( webglSlot === undefined ) webglSlot = 33984 + maxTextures - 1;
  13018. if ( currentTextureSlot !== webglSlot ) {
  13019. gl.activeTexture( webglSlot );
  13020. currentTextureSlot = webglSlot;
  13021. }
  13022. }
  13023. function bindTexture( webglType, webglTexture ) {
  13024. if ( currentTextureSlot === null ) {
  13025. activeTexture();
  13026. }
  13027. let boundTexture = currentBoundTextures[ currentTextureSlot ];
  13028. if ( boundTexture === undefined ) {
  13029. boundTexture = { type: undefined, texture: undefined };
  13030. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  13031. }
  13032. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  13033. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  13034. boundTexture.type = webglType;
  13035. boundTexture.texture = webglTexture;
  13036. }
  13037. }
  13038. function unbindTexture() {
  13039. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  13040. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  13041. gl.bindTexture( boundTexture.type, null );
  13042. boundTexture.type = undefined;
  13043. boundTexture.texture = undefined;
  13044. }
  13045. }
  13046. function compressedTexImage2D() {
  13047. try {
  13048. gl.compressedTexImage2D.apply( gl, arguments );
  13049. } catch ( error ) {
  13050. console.error( 'THREE.WebGLState:', error );
  13051. }
  13052. }
  13053. function texImage2D() {
  13054. try {
  13055. gl.texImage2D.apply( gl, arguments );
  13056. } catch ( error ) {
  13057. console.error( 'THREE.WebGLState:', error );
  13058. }
  13059. }
  13060. function texImage3D() {
  13061. try {
  13062. gl.texImage3D.apply( gl, arguments );
  13063. } catch ( error ) {
  13064. console.error( 'THREE.WebGLState:', error );
  13065. }
  13066. }
  13067. //
  13068. function scissor( scissor ) {
  13069. if ( currentScissor.equals( scissor ) === false ) {
  13070. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  13071. currentScissor.copy( scissor );
  13072. }
  13073. }
  13074. function viewport( viewport ) {
  13075. if ( currentViewport.equals( viewport ) === false ) {
  13076. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  13077. currentViewport.copy( viewport );
  13078. }
  13079. }
  13080. //
  13081. function reset() {
  13082. // reset state
  13083. gl.disable( 3042 );
  13084. gl.disable( 2884 );
  13085. gl.disable( 2929 );
  13086. gl.disable( 32823 );
  13087. gl.disable( 3089 );
  13088. gl.disable( 2960 );
  13089. gl.disable( 32926 );
  13090. gl.blendEquation( 32774 );
  13091. gl.blendFunc( 1, 0 );
  13092. gl.blendFuncSeparate( 1, 0, 1, 0 );
  13093. gl.colorMask( true, true, true, true );
  13094. gl.clearColor( 0, 0, 0, 0 );
  13095. gl.depthMask( true );
  13096. gl.depthFunc( 513 );
  13097. gl.clearDepth( 1 );
  13098. gl.stencilMask( 0xffffffff );
  13099. gl.stencilFunc( 519, 0, 0xffffffff );
  13100. gl.stencilOp( 7680, 7680, 7680 );
  13101. gl.clearStencil( 0 );
  13102. gl.cullFace( 1029 );
  13103. gl.frontFace( 2305 );
  13104. gl.polygonOffset( 0, 0 );
  13105. gl.activeTexture( 33984 );
  13106. gl.bindFramebuffer( 36160, null );
  13107. if ( isWebGL2 === true ) {
  13108. gl.bindFramebuffer( 36009, null );
  13109. gl.bindFramebuffer( 36008, null );
  13110. }
  13111. gl.useProgram( null );
  13112. gl.lineWidth( 1 );
  13113. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  13114. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  13115. // reset internals
  13116. enabledCapabilities = {};
  13117. currentTextureSlot = null;
  13118. currentBoundTextures = {};
  13119. xrFramebuffer = null;
  13120. currentBoundFramebuffers = {};
  13121. currentProgram = null;
  13122. currentBlendingEnabled = false;
  13123. currentBlending = null;
  13124. currentBlendEquation = null;
  13125. currentBlendSrc = null;
  13126. currentBlendDst = null;
  13127. currentBlendEquationAlpha = null;
  13128. currentBlendSrcAlpha = null;
  13129. currentBlendDstAlpha = null;
  13130. currentPremultipledAlpha = false;
  13131. currentFlipSided = null;
  13132. currentCullFace = null;
  13133. currentLineWidth = null;
  13134. currentPolygonOffsetFactor = null;
  13135. currentPolygonOffsetUnits = null;
  13136. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  13137. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  13138. colorBuffer.reset();
  13139. depthBuffer.reset();
  13140. stencilBuffer.reset();
  13141. }
  13142. return {
  13143. buffers: {
  13144. color: colorBuffer,
  13145. depth: depthBuffer,
  13146. stencil: stencilBuffer
  13147. },
  13148. enable: enable,
  13149. disable: disable,
  13150. bindFramebuffer: bindFramebuffer,
  13151. bindXRFramebuffer: bindXRFramebuffer,
  13152. useProgram: useProgram,
  13153. setBlending: setBlending,
  13154. setMaterial: setMaterial,
  13155. setFlipSided: setFlipSided,
  13156. setCullFace: setCullFace,
  13157. setLineWidth: setLineWidth,
  13158. setPolygonOffset: setPolygonOffset,
  13159. setScissorTest: setScissorTest,
  13160. activeTexture: activeTexture,
  13161. bindTexture: bindTexture,
  13162. unbindTexture: unbindTexture,
  13163. compressedTexImage2D: compressedTexImage2D,
  13164. texImage2D: texImage2D,
  13165. texImage3D: texImage3D,
  13166. scissor: scissor,
  13167. viewport: viewport,
  13168. reset: reset
  13169. };
  13170. }
  13171. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  13172. const isWebGL2 = capabilities.isWebGL2;
  13173. const maxTextures = capabilities.maxTextures;
  13174. const maxCubemapSize = capabilities.maxCubemapSize;
  13175. const maxTextureSize = capabilities.maxTextureSize;
  13176. const maxSamples = capabilities.maxSamples;
  13177. const _videoTextures = new WeakMap();
  13178. let _canvas;
  13179. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  13180. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  13181. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  13182. let useOffscreenCanvas = false;
  13183. try {
  13184. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  13185. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  13186. } catch ( err ) {
  13187. // Ignore any errors
  13188. }
  13189. function createCanvas( width, height ) {
  13190. // Use OffscreenCanvas when available. Specially needed in web workers
  13191. return useOffscreenCanvas ?
  13192. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  13193. }
  13194. function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {
  13195. let scale = 1;
  13196. // handle case if texture exceeds max size
  13197. if ( image.width > maxSize || image.height > maxSize ) {
  13198. scale = maxSize / Math.max( image.width, image.height );
  13199. }
  13200. // only perform resize if necessary
  13201. if ( scale < 1 || needsPowerOfTwo === true ) {
  13202. // only perform resize for certain image types
  13203. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  13204. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  13205. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  13206. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  13207. const width = floor( scale * image.width );
  13208. const height = floor( scale * image.height );
  13209. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  13210. // cube textures can't reuse the same canvas
  13211. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  13212. canvas.width = width;
  13213. canvas.height = height;
  13214. const context = canvas.getContext( '2d' );
  13215. context.drawImage( image, 0, 0, width, height );
  13216. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );
  13217. return canvas;
  13218. } else {
  13219. if ( 'data' in image ) {
  13220. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  13221. }
  13222. return image;
  13223. }
  13224. }
  13225. return image;
  13226. }
  13227. function isPowerOfTwo$1( image ) {
  13228. return isPowerOfTwo( image.width ) && isPowerOfTwo( image.height );
  13229. }
  13230. function textureNeedsPowerOfTwo( texture ) {
  13231. if ( isWebGL2 ) return false;
  13232. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  13233. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  13234. }
  13235. function textureNeedsGenerateMipmaps( texture, supportsMips ) {
  13236. return texture.generateMipmaps && supportsMips &&
  13237. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13238. }
  13239. function generateMipmap( target, texture, width, height, depth = 1 ) {
  13240. _gl.generateMipmap( target );
  13241. const textureProperties = properties.get( texture );
  13242. textureProperties.__maxMipLevel = Math.log2( Math.max( width, height, depth ) );
  13243. }
  13244. function getInternalFormat( internalFormatName, glFormat, glType, encoding ) {
  13245. if ( isWebGL2 === false ) return glFormat;
  13246. if ( internalFormatName !== null ) {
  13247. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  13248. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  13249. }
  13250. let internalFormat = glFormat;
  13251. if ( glFormat === 6403 ) {
  13252. if ( glType === 5126 ) internalFormat = 33326;
  13253. if ( glType === 5131 ) internalFormat = 33325;
  13254. if ( glType === 5121 ) internalFormat = 33321;
  13255. }
  13256. if ( glFormat === 6407 ) {
  13257. if ( glType === 5126 ) internalFormat = 34837;
  13258. if ( glType === 5131 ) internalFormat = 34843;
  13259. if ( glType === 5121 ) internalFormat = 32849;
  13260. }
  13261. if ( glFormat === 6408 ) {
  13262. if ( glType === 5126 ) internalFormat = 34836;
  13263. if ( glType === 5131 ) internalFormat = 34842;
  13264. if ( glType === 5121 ) internalFormat = ( encoding === sRGBEncoding ) ? 35907 : 32856;
  13265. }
  13266. if ( internalFormat === 33325 || internalFormat === 33326 ||
  13267. internalFormat === 34842 || internalFormat === 34836 ) {
  13268. extensions.get( 'EXT_color_buffer_float' );
  13269. }
  13270. return internalFormat;
  13271. }
  13272. // Fallback filters for non-power-of-2 textures
  13273. function filterFallback( f ) {
  13274. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  13275. return 9728;
  13276. }
  13277. return 9729;
  13278. }
  13279. //
  13280. function onTextureDispose( event ) {
  13281. const texture = event.target;
  13282. texture.removeEventListener( 'dispose', onTextureDispose );
  13283. deallocateTexture( texture );
  13284. if ( texture.isVideoTexture ) {
  13285. _videoTextures.delete( texture );
  13286. }
  13287. info.memory.textures --;
  13288. }
  13289. function onRenderTargetDispose( event ) {
  13290. const renderTarget = event.target;
  13291. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  13292. deallocateRenderTarget( renderTarget );
  13293. }
  13294. //
  13295. function deallocateTexture( texture ) {
  13296. const textureProperties = properties.get( texture );
  13297. if ( textureProperties.__webglInit === undefined ) return;
  13298. _gl.deleteTexture( textureProperties.__webglTexture );
  13299. properties.remove( texture );
  13300. }
  13301. function deallocateRenderTarget( renderTarget ) {
  13302. const texture = renderTarget.texture;
  13303. const renderTargetProperties = properties.get( renderTarget );
  13304. const textureProperties = properties.get( texture );
  13305. if ( ! renderTarget ) return;
  13306. if ( textureProperties.__webglTexture !== undefined ) {
  13307. _gl.deleteTexture( textureProperties.__webglTexture );
  13308. info.memory.textures --;
  13309. }
  13310. if ( renderTarget.depthTexture ) {
  13311. renderTarget.depthTexture.dispose();
  13312. }
  13313. if ( renderTarget.isWebGLCubeRenderTarget ) {
  13314. for ( let i = 0; i < 6; i ++ ) {
  13315. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  13316. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  13317. }
  13318. } else {
  13319. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  13320. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  13321. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  13322. if ( renderTargetProperties.__webglColorRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer );
  13323. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  13324. }
  13325. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  13326. for ( let i = 0, il = texture.length; i < il; i ++ ) {
  13327. const attachmentProperties = properties.get( texture[ i ] );
  13328. if ( attachmentProperties.__webglTexture ) {
  13329. _gl.deleteTexture( attachmentProperties.__webglTexture );
  13330. info.memory.textures --;
  13331. }
  13332. properties.remove( texture[ i ] );
  13333. }
  13334. }
  13335. properties.remove( texture );
  13336. properties.remove( renderTarget );
  13337. }
  13338. //
  13339. let textureUnits = 0;
  13340. function resetTextureUnits() {
  13341. textureUnits = 0;
  13342. }
  13343. function allocateTextureUnit() {
  13344. const textureUnit = textureUnits;
  13345. if ( textureUnit >= maxTextures ) {
  13346. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures );
  13347. }
  13348. textureUnits += 1;
  13349. return textureUnit;
  13350. }
  13351. //
  13352. function setTexture2D( texture, slot ) {
  13353. const textureProperties = properties.get( texture );
  13354. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  13355. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13356. const image = texture.image;
  13357. if ( image === undefined ) {
  13358. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined' );
  13359. } else if ( image.complete === false ) {
  13360. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  13361. } else {
  13362. uploadTexture( textureProperties, texture, slot );
  13363. return;
  13364. }
  13365. }
  13366. state.activeTexture( 33984 + slot );
  13367. state.bindTexture( 3553, textureProperties.__webglTexture );
  13368. }
  13369. function setTexture2DArray( texture, slot ) {
  13370. const textureProperties = properties.get( texture );
  13371. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13372. uploadTexture( textureProperties, texture, slot );
  13373. return;
  13374. }
  13375. state.activeTexture( 33984 + slot );
  13376. state.bindTexture( 35866, textureProperties.__webglTexture );
  13377. }
  13378. function setTexture3D( texture, slot ) {
  13379. const textureProperties = properties.get( texture );
  13380. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13381. uploadTexture( textureProperties, texture, slot );
  13382. return;
  13383. }
  13384. state.activeTexture( 33984 + slot );
  13385. state.bindTexture( 32879, textureProperties.__webglTexture );
  13386. }
  13387. function setTextureCube( texture, slot ) {
  13388. const textureProperties = properties.get( texture );
  13389. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13390. uploadCubeTexture( textureProperties, texture, slot );
  13391. return;
  13392. }
  13393. state.activeTexture( 33984 + slot );
  13394. state.bindTexture( 34067, textureProperties.__webglTexture );
  13395. }
  13396. const wrappingToGL = {
  13397. [ RepeatWrapping ]: 10497,
  13398. [ ClampToEdgeWrapping ]: 33071,
  13399. [ MirroredRepeatWrapping ]: 33648
  13400. };
  13401. const filterToGL = {
  13402. [ NearestFilter ]: 9728,
  13403. [ NearestMipmapNearestFilter ]: 9984,
  13404. [ NearestMipmapLinearFilter ]: 9986,
  13405. [ LinearFilter ]: 9729,
  13406. [ LinearMipmapNearestFilter ]: 9985,
  13407. [ LinearMipmapLinearFilter ]: 9987
  13408. };
  13409. function setTextureParameters( textureType, texture, supportsMips ) {
  13410. if ( supportsMips ) {
  13411. _gl.texParameteri( textureType, 10242, wrappingToGL[ texture.wrapS ] );
  13412. _gl.texParameteri( textureType, 10243, wrappingToGL[ texture.wrapT ] );
  13413. if ( textureType === 32879 || textureType === 35866 ) {
  13414. _gl.texParameteri( textureType, 32882, wrappingToGL[ texture.wrapR ] );
  13415. }
  13416. _gl.texParameteri( textureType, 10240, filterToGL[ texture.magFilter ] );
  13417. _gl.texParameteri( textureType, 10241, filterToGL[ texture.minFilter ] );
  13418. } else {
  13419. _gl.texParameteri( textureType, 10242, 33071 );
  13420. _gl.texParameteri( textureType, 10243, 33071 );
  13421. if ( textureType === 32879 || textureType === 35866 ) {
  13422. _gl.texParameteri( textureType, 32882, 33071 );
  13423. }
  13424. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  13425. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
  13426. }
  13427. _gl.texParameteri( textureType, 10240, filterFallback( texture.magFilter ) );
  13428. _gl.texParameteri( textureType, 10241, filterFallback( texture.minFilter ) );
  13429. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  13430. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
  13431. }
  13432. }
  13433. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  13434. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  13435. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  13436. if ( isWebGL2 === false && ( texture.type === HalfFloatType && extensions.has( 'OES_texture_half_float_linear' ) === false ) ) return; // verify extension for WebGL 1 only
  13437. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  13438. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  13439. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  13440. }
  13441. }
  13442. }
  13443. function initTexture( textureProperties, texture ) {
  13444. if ( textureProperties.__webglInit === undefined ) {
  13445. textureProperties.__webglInit = true;
  13446. texture.addEventListener( 'dispose', onTextureDispose );
  13447. textureProperties.__webglTexture = _gl.createTexture();
  13448. info.memory.textures ++;
  13449. }
  13450. }
  13451. function uploadTexture( textureProperties, texture, slot ) {
  13452. let textureType = 3553;
  13453. if ( texture.isDataTexture2DArray ) textureType = 35866;
  13454. if ( texture.isDataTexture3D ) textureType = 32879;
  13455. initTexture( textureProperties, texture );
  13456. state.activeTexture( 33984 + slot );
  13457. state.bindTexture( textureType, textureProperties.__webglTexture );
  13458. _gl.pixelStorei( 37440, texture.flipY );
  13459. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  13460. _gl.pixelStorei( 3317, texture.unpackAlignment );
  13461. _gl.pixelStorei( 37443, 0 );
  13462. const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo$1( texture.image ) === false;
  13463. const image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );
  13464. const supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  13465. glFormat = utils.convert( texture.format );
  13466. let glType = utils.convert( texture.type ),
  13467. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  13468. setTextureParameters( textureType, texture, supportsMips );
  13469. let mipmap;
  13470. const mipmaps = texture.mipmaps;
  13471. if ( texture.isDepthTexture ) {
  13472. // populate depth texture with dummy data
  13473. glInternalFormat = 6402;
  13474. if ( isWebGL2 ) {
  13475. if ( texture.type === FloatType ) {
  13476. glInternalFormat = 36012;
  13477. } else if ( texture.type === UnsignedIntType ) {
  13478. glInternalFormat = 33190;
  13479. } else if ( texture.type === UnsignedInt248Type ) {
  13480. glInternalFormat = 35056;
  13481. } else {
  13482. glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D
  13483. }
  13484. } else {
  13485. if ( texture.type === FloatType ) {
  13486. console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' );
  13487. }
  13488. }
  13489. // validation checks for WebGL 1
  13490. if ( texture.format === DepthFormat && glInternalFormat === 6402 ) {
  13491. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13492. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  13493. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13494. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  13495. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  13496. texture.type = UnsignedShortType;
  13497. glType = utils.convert( texture.type );
  13498. }
  13499. }
  13500. if ( texture.format === DepthStencilFormat && glInternalFormat === 6402 ) {
  13501. // Depth stencil textures need the DEPTH_STENCIL internal format
  13502. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13503. glInternalFormat = 34041;
  13504. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13505. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  13506. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13507. if ( texture.type !== UnsignedInt248Type ) {
  13508. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  13509. texture.type = UnsignedInt248Type;
  13510. glType = utils.convert( texture.type );
  13511. }
  13512. }
  13513. //
  13514. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  13515. } else if ( texture.isDataTexture ) {
  13516. // use manually created mipmaps if available
  13517. // if there are no manual mipmaps
  13518. // set 0 level mipmap and then use GL to generate other mipmap levels
  13519. if ( mipmaps.length > 0 && supportsMips ) {
  13520. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  13521. mipmap = mipmaps[ i ];
  13522. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13523. }
  13524. texture.generateMipmaps = false;
  13525. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13526. } else {
  13527. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  13528. textureProperties.__maxMipLevel = 0;
  13529. }
  13530. } else if ( texture.isCompressedTexture ) {
  13531. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  13532. mipmap = mipmaps[ i ];
  13533. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  13534. if ( glFormat !== null ) {
  13535. state.compressedTexImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13536. } else {
  13537. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  13538. }
  13539. } else {
  13540. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13541. }
  13542. }
  13543. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13544. } else if ( texture.isDataTexture2DArray ) {
  13545. state.texImage3D( 35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  13546. textureProperties.__maxMipLevel = 0;
  13547. } else if ( texture.isDataTexture3D ) {
  13548. state.texImage3D( 32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  13549. textureProperties.__maxMipLevel = 0;
  13550. } else {
  13551. // regular Texture (image, video, canvas)
  13552. // use manually created mipmaps if available
  13553. // if there are no manual mipmaps
  13554. // set 0 level mipmap and then use GL to generate other mipmap levels
  13555. if ( mipmaps.length > 0 && supportsMips ) {
  13556. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  13557. mipmap = mipmaps[ i ];
  13558. state.texImage2D( 3553, i, glInternalFormat, glFormat, glType, mipmap );
  13559. }
  13560. texture.generateMipmaps = false;
  13561. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13562. } else {
  13563. state.texImage2D( 3553, 0, glInternalFormat, glFormat, glType, image );
  13564. textureProperties.__maxMipLevel = 0;
  13565. }
  13566. }
  13567. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  13568. generateMipmap( textureType, texture, image.width, image.height );
  13569. }
  13570. textureProperties.__version = texture.version;
  13571. if ( texture.onUpdate ) texture.onUpdate( texture );
  13572. }
  13573. function uploadCubeTexture( textureProperties, texture, slot ) {
  13574. if ( texture.image.length !== 6 ) return;
  13575. initTexture( textureProperties, texture );
  13576. state.activeTexture( 33984 + slot );
  13577. state.bindTexture( 34067, textureProperties.__webglTexture );
  13578. _gl.pixelStorei( 37440, texture.flipY );
  13579. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  13580. _gl.pixelStorei( 3317, texture.unpackAlignment );
  13581. _gl.pixelStorei( 37443, 0 );
  13582. const isCompressed = ( texture && ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture ) );
  13583. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  13584. const cubeImage = [];
  13585. for ( let i = 0; i < 6; i ++ ) {
  13586. if ( ! isCompressed && ! isDataTexture ) {
  13587. cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize );
  13588. } else {
  13589. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  13590. }
  13591. }
  13592. const image = cubeImage[ 0 ],
  13593. supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  13594. glFormat = utils.convert( texture.format ),
  13595. glType = utils.convert( texture.type ),
  13596. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  13597. setTextureParameters( 34067, texture, supportsMips );
  13598. let mipmaps;
  13599. if ( isCompressed ) {
  13600. for ( let i = 0; i < 6; i ++ ) {
  13601. mipmaps = cubeImage[ i ].mipmaps;
  13602. for ( let j = 0; j < mipmaps.length; j ++ ) {
  13603. const mipmap = mipmaps[ j ];
  13604. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  13605. if ( glFormat !== null ) {
  13606. state.compressedTexImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13607. } else {
  13608. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  13609. }
  13610. } else {
  13611. state.texImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13612. }
  13613. }
  13614. }
  13615. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13616. } else {
  13617. mipmaps = texture.mipmaps;
  13618. for ( let i = 0; i < 6; i ++ ) {
  13619. if ( isDataTexture ) {
  13620. state.texImage2D( 34069 + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  13621. for ( let j = 0; j < mipmaps.length; j ++ ) {
  13622. const mipmap = mipmaps[ j ];
  13623. const mipmapImage = mipmap.image[ i ].image;
  13624. state.texImage2D( 34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  13625. }
  13626. } else {
  13627. state.texImage2D( 34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  13628. for ( let j = 0; j < mipmaps.length; j ++ ) {
  13629. const mipmap = mipmaps[ j ];
  13630. state.texImage2D( 34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  13631. }
  13632. }
  13633. }
  13634. textureProperties.__maxMipLevel = mipmaps.length;
  13635. }
  13636. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  13637. // We assume images for cube map have the same size.
  13638. generateMipmap( 34067, texture, image.width, image.height );
  13639. }
  13640. textureProperties.__version = texture.version;
  13641. if ( texture.onUpdate ) texture.onUpdate( texture );
  13642. }
  13643. // Render targets
  13644. // Setup storage for target texture and bind it to correct framebuffer
  13645. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget ) {
  13646. const glFormat = utils.convert( texture.format );
  13647. const glType = utils.convert( texture.type );
  13648. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  13649. if ( textureTarget === 32879 || textureTarget === 35866 ) {
  13650. state.texImage3D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null );
  13651. } else {
  13652. state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  13653. }
  13654. state.bindFramebuffer( 36160, framebuffer );
  13655. _gl.framebufferTexture2D( 36160, attachment, textureTarget, properties.get( texture ).__webglTexture, 0 );
  13656. state.bindFramebuffer( 36160, null );
  13657. }
  13658. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  13659. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  13660. _gl.bindRenderbuffer( 36161, renderbuffer );
  13661. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  13662. let glInternalFormat = 33189;
  13663. if ( isMultisample ) {
  13664. const depthTexture = renderTarget.depthTexture;
  13665. if ( depthTexture && depthTexture.isDepthTexture ) {
  13666. if ( depthTexture.type === FloatType ) {
  13667. glInternalFormat = 36012;
  13668. } else if ( depthTexture.type === UnsignedIntType ) {
  13669. glInternalFormat = 33190;
  13670. }
  13671. }
  13672. const samples = getRenderTargetSamples( renderTarget );
  13673. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  13674. } else {
  13675. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  13676. }
  13677. _gl.framebufferRenderbuffer( 36160, 36096, 36161, renderbuffer );
  13678. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13679. if ( isMultisample ) {
  13680. const samples = getRenderTargetSamples( renderTarget );
  13681. _gl.renderbufferStorageMultisample( 36161, samples, 35056, renderTarget.width, renderTarget.height );
  13682. } else {
  13683. _gl.renderbufferStorage( 36161, 34041, renderTarget.width, renderTarget.height );
  13684. }
  13685. _gl.framebufferRenderbuffer( 36160, 33306, 36161, renderbuffer );
  13686. } else {
  13687. // Use the first texture for MRT so far
  13688. const texture = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture[ 0 ] : renderTarget.texture;
  13689. const glFormat = utils.convert( texture.format );
  13690. const glType = utils.convert( texture.type );
  13691. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  13692. if ( isMultisample ) {
  13693. const samples = getRenderTargetSamples( renderTarget );
  13694. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  13695. } else {
  13696. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  13697. }
  13698. }
  13699. _gl.bindRenderbuffer( 36161, null );
  13700. }
  13701. // Setup resources for a Depth Texture for a FBO (needs an extension)
  13702. function setupDepthTexture( framebuffer, renderTarget ) {
  13703. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  13704. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  13705. state.bindFramebuffer( 36160, framebuffer );
  13706. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  13707. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  13708. }
  13709. // upload an empty depth texture with framebuffer size
  13710. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  13711. renderTarget.depthTexture.image.width !== renderTarget.width ||
  13712. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  13713. renderTarget.depthTexture.image.width = renderTarget.width;
  13714. renderTarget.depthTexture.image.height = renderTarget.height;
  13715. renderTarget.depthTexture.needsUpdate = true;
  13716. }
  13717. setTexture2D( renderTarget.depthTexture, 0 );
  13718. const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  13719. if ( renderTarget.depthTexture.format === DepthFormat ) {
  13720. _gl.framebufferTexture2D( 36160, 36096, 3553, webglDepthTexture, 0 );
  13721. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  13722. _gl.framebufferTexture2D( 36160, 33306, 3553, webglDepthTexture, 0 );
  13723. } else {
  13724. throw new Error( 'Unknown depthTexture format' );
  13725. }
  13726. }
  13727. // Setup GL resources for a non-texture depth buffer
  13728. function setupDepthRenderbuffer( renderTarget ) {
  13729. const renderTargetProperties = properties.get( renderTarget );
  13730. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  13731. if ( renderTarget.depthTexture ) {
  13732. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  13733. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  13734. } else {
  13735. if ( isCube ) {
  13736. renderTargetProperties.__webglDepthbuffer = [];
  13737. for ( let i = 0; i < 6; i ++ ) {
  13738. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer[ i ] );
  13739. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  13740. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  13741. }
  13742. } else {
  13743. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  13744. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  13745. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  13746. }
  13747. }
  13748. state.bindFramebuffer( 36160, null );
  13749. }
  13750. // Set up GL resources for the render target
  13751. function setupRenderTarget( renderTarget ) {
  13752. const texture = renderTarget.texture;
  13753. const renderTargetProperties = properties.get( renderTarget );
  13754. const textureProperties = properties.get( texture );
  13755. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  13756. if ( renderTarget.isWebGLMultipleRenderTargets !== true ) {
  13757. textureProperties.__webglTexture = _gl.createTexture();
  13758. textureProperties.__version = texture.version;
  13759. info.memory.textures ++;
  13760. }
  13761. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  13762. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  13763. const isMultisample = ( renderTarget.isWebGLMultisampleRenderTarget === true );
  13764. const isRenderTarget3D = texture.isDataTexture3D || texture.isDataTexture2DArray;
  13765. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  13766. // Handles WebGL2 RGBFormat fallback - #18858
  13767. if ( isWebGL2 && texture.format === RGBFormat && ( texture.type === FloatType || texture.type === HalfFloatType ) ) {
  13768. texture.format = RGBAFormat;
  13769. console.warn( 'THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.' );
  13770. }
  13771. // Setup framebuffer
  13772. if ( isCube ) {
  13773. renderTargetProperties.__webglFramebuffer = [];
  13774. for ( let i = 0; i < 6; i ++ ) {
  13775. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  13776. }
  13777. } else {
  13778. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  13779. if ( isMultipleRenderTargets ) {
  13780. if ( capabilities.drawBuffers ) {
  13781. const textures = renderTarget.texture;
  13782. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  13783. const attachmentProperties = properties.get( textures[ i ] );
  13784. if ( attachmentProperties.__webglTexture === undefined ) {
  13785. attachmentProperties.__webglTexture = _gl.createTexture();
  13786. info.memory.textures ++;
  13787. }
  13788. }
  13789. } else {
  13790. console.warn( 'THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.' );
  13791. }
  13792. } else if ( isMultisample ) {
  13793. if ( isWebGL2 ) {
  13794. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  13795. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  13796. _gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer );
  13797. const glFormat = utils.convert( texture.format );
  13798. const glType = utils.convert( texture.type );
  13799. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  13800. const samples = getRenderTargetSamples( renderTarget );
  13801. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  13802. state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  13803. _gl.framebufferRenderbuffer( 36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer );
  13804. _gl.bindRenderbuffer( 36161, null );
  13805. if ( renderTarget.depthBuffer ) {
  13806. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  13807. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  13808. }
  13809. state.bindFramebuffer( 36160, null );
  13810. } else {
  13811. console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
  13812. }
  13813. }
  13814. }
  13815. // Setup color buffer
  13816. if ( isCube ) {
  13817. state.bindTexture( 34067, textureProperties.__webglTexture );
  13818. setTextureParameters( 34067, texture, supportsMips );
  13819. for ( let i = 0; i < 6; i ++ ) {
  13820. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, 36064, 34069 + i );
  13821. }
  13822. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  13823. generateMipmap( 34067, texture, renderTarget.width, renderTarget.height );
  13824. }
  13825. state.unbindTexture();
  13826. } else if ( isMultipleRenderTargets ) {
  13827. const textures = renderTarget.texture;
  13828. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  13829. const attachment = textures[ i ];
  13830. const attachmentProperties = properties.get( attachment );
  13831. state.bindTexture( 3553, attachmentProperties.__webglTexture );
  13832. setTextureParameters( 3553, attachment, supportsMips );
  13833. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, 36064 + i, 3553 );
  13834. if ( textureNeedsGenerateMipmaps( attachment, supportsMips ) ) {
  13835. generateMipmap( 3553, attachment, renderTarget.width, renderTarget.height );
  13836. }
  13837. }
  13838. state.unbindTexture();
  13839. } else {
  13840. let glTextureType = 3553;
  13841. if ( isRenderTarget3D ) {
  13842. // Render targets containing layers, i.e: Texture 3D and 2d arrays
  13843. if ( isWebGL2 ) {
  13844. const isTexture3D = texture.isDataTexture3D;
  13845. glTextureType = isTexture3D ? 32879 : 35866;
  13846. } else {
  13847. console.warn( 'THREE.DataTexture3D and THREE.DataTexture2DArray only supported with WebGL2.' );
  13848. }
  13849. }
  13850. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  13851. setTextureParameters( glTextureType, texture, supportsMips );
  13852. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, 36064, glTextureType );
  13853. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  13854. generateMipmap( glTextureType, texture, renderTarget.width, renderTarget.height, renderTarget.depth );
  13855. }
  13856. state.unbindTexture();
  13857. }
  13858. // Setup depth and stencil buffers
  13859. if ( renderTarget.depthBuffer ) {
  13860. setupDepthRenderbuffer( renderTarget );
  13861. }
  13862. }
  13863. function updateRenderTargetMipmap( renderTarget ) {
  13864. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  13865. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  13866. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  13867. const texture = textures[ i ];
  13868. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  13869. const target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553;
  13870. const webglTexture = properties.get( texture ).__webglTexture;
  13871. state.bindTexture( target, webglTexture );
  13872. generateMipmap( target, texture, renderTarget.width, renderTarget.height );
  13873. state.unbindTexture();
  13874. }
  13875. }
  13876. }
  13877. function updateMultisampleRenderTarget( renderTarget ) {
  13878. if ( renderTarget.isWebGLMultisampleRenderTarget ) {
  13879. if ( isWebGL2 ) {
  13880. const width = renderTarget.width;
  13881. const height = renderTarget.height;
  13882. let mask = 16384;
  13883. if ( renderTarget.depthBuffer ) mask |= 256;
  13884. if ( renderTarget.stencilBuffer ) mask |= 1024;
  13885. const renderTargetProperties = properties.get( renderTarget );
  13886. state.bindFramebuffer( 36008, renderTargetProperties.__webglMultisampledFramebuffer );
  13887. state.bindFramebuffer( 36009, renderTargetProperties.__webglFramebuffer );
  13888. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 );
  13889. state.bindFramebuffer( 36008, null );
  13890. state.bindFramebuffer( 36009, renderTargetProperties.__webglMultisampledFramebuffer );
  13891. } else {
  13892. console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
  13893. }
  13894. }
  13895. }
  13896. function getRenderTargetSamples( renderTarget ) {
  13897. return ( isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ) ?
  13898. Math.min( maxSamples, renderTarget.samples ) : 0;
  13899. }
  13900. function updateVideoTexture( texture ) {
  13901. const frame = info.render.frame;
  13902. // Check the last frame we updated the VideoTexture
  13903. if ( _videoTextures.get( texture ) !== frame ) {
  13904. _videoTextures.set( texture, frame );
  13905. texture.update();
  13906. }
  13907. }
  13908. // backwards compatibility
  13909. let warnedTexture2D = false;
  13910. let warnedTextureCube = false;
  13911. function safeSetTexture2D( texture, slot ) {
  13912. if ( texture && texture.isWebGLRenderTarget ) {
  13913. if ( warnedTexture2D === false ) {
  13914. console.warn( 'THREE.WebGLTextures.safeSetTexture2D: don\'t use render targets as textures. Use their .texture property instead.' );
  13915. warnedTexture2D = true;
  13916. }
  13917. texture = texture.texture;
  13918. }
  13919. setTexture2D( texture, slot );
  13920. }
  13921. function safeSetTextureCube( texture, slot ) {
  13922. if ( texture && texture.isWebGLCubeRenderTarget ) {
  13923. if ( warnedTextureCube === false ) {
  13924. console.warn( 'THREE.WebGLTextures.safeSetTextureCube: don\'t use cube render targets as textures. Use their .texture property instead.' );
  13925. warnedTextureCube = true;
  13926. }
  13927. texture = texture.texture;
  13928. }
  13929. setTextureCube( texture, slot );
  13930. }
  13931. //
  13932. this.allocateTextureUnit = allocateTextureUnit;
  13933. this.resetTextureUnits = resetTextureUnits;
  13934. this.setTexture2D = setTexture2D;
  13935. this.setTexture2DArray = setTexture2DArray;
  13936. this.setTexture3D = setTexture3D;
  13937. this.setTextureCube = setTextureCube;
  13938. this.setupRenderTarget = setupRenderTarget;
  13939. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  13940. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  13941. this.safeSetTexture2D = safeSetTexture2D;
  13942. this.safeSetTextureCube = safeSetTextureCube;
  13943. }
  13944. function WebGLUtils( gl, extensions, capabilities ) {
  13945. const isWebGL2 = capabilities.isWebGL2;
  13946. function convert( p ) {
  13947. let extension;
  13948. if ( p === UnsignedByteType ) return 5121;
  13949. if ( p === UnsignedShort4444Type ) return 32819;
  13950. if ( p === UnsignedShort5551Type ) return 32820;
  13951. if ( p === UnsignedShort565Type ) return 33635;
  13952. if ( p === ByteType ) return 5120;
  13953. if ( p === ShortType ) return 5122;
  13954. if ( p === UnsignedShortType ) return 5123;
  13955. if ( p === IntType ) return 5124;
  13956. if ( p === UnsignedIntType ) return 5125;
  13957. if ( p === FloatType ) return 5126;
  13958. if ( p === HalfFloatType ) {
  13959. if ( isWebGL2 ) return 5131;
  13960. extension = extensions.get( 'OES_texture_half_float' );
  13961. if ( extension !== null ) {
  13962. return extension.HALF_FLOAT_OES;
  13963. } else {
  13964. return null;
  13965. }
  13966. }
  13967. if ( p === AlphaFormat ) return 6406;
  13968. if ( p === RGBFormat ) return 6407;
  13969. if ( p === RGBAFormat ) return 6408;
  13970. if ( p === LuminanceFormat ) return 6409;
  13971. if ( p === LuminanceAlphaFormat ) return 6410;
  13972. if ( p === DepthFormat ) return 6402;
  13973. if ( p === DepthStencilFormat ) return 34041;
  13974. if ( p === RedFormat ) return 6403;
  13975. // WebGL2 formats.
  13976. if ( p === RedIntegerFormat ) return 36244;
  13977. if ( p === RGFormat ) return 33319;
  13978. if ( p === RGIntegerFormat ) return 33320;
  13979. if ( p === RGBIntegerFormat ) return 36248;
  13980. if ( p === RGBAIntegerFormat ) return 36249;
  13981. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  13982. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  13983. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  13984. if ( extension !== null ) {
  13985. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13986. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13987. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13988. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13989. } else {
  13990. return null;
  13991. }
  13992. }
  13993. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  13994. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  13995. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  13996. if ( extension !== null ) {
  13997. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  13998. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  13999. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  14000. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  14001. } else {
  14002. return null;
  14003. }
  14004. }
  14005. if ( p === RGB_ETC1_Format ) {
  14006. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  14007. if ( extension !== null ) {
  14008. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  14009. } else {
  14010. return null;
  14011. }
  14012. }
  14013. if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  14014. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  14015. if ( extension !== null ) {
  14016. if ( p === RGB_ETC2_Format ) return extension.COMPRESSED_RGB8_ETC2;
  14017. if ( p === RGBA_ETC2_EAC_Format ) return extension.COMPRESSED_RGBA8_ETC2_EAC;
  14018. }
  14019. }
  14020. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  14021. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  14022. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  14023. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  14024. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ||
  14025. p === SRGB8_ALPHA8_ASTC_4x4_Format || p === SRGB8_ALPHA8_ASTC_5x4_Format || p === SRGB8_ALPHA8_ASTC_5x5_Format ||
  14026. p === SRGB8_ALPHA8_ASTC_6x5_Format || p === SRGB8_ALPHA8_ASTC_6x6_Format || p === SRGB8_ALPHA8_ASTC_8x5_Format ||
  14027. p === SRGB8_ALPHA8_ASTC_8x6_Format || p === SRGB8_ALPHA8_ASTC_8x8_Format || p === SRGB8_ALPHA8_ASTC_10x5_Format ||
  14028. p === SRGB8_ALPHA8_ASTC_10x6_Format || p === SRGB8_ALPHA8_ASTC_10x8_Format || p === SRGB8_ALPHA8_ASTC_10x10_Format ||
  14029. p === SRGB8_ALPHA8_ASTC_12x10_Format || p === SRGB8_ALPHA8_ASTC_12x12_Format ) {
  14030. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  14031. if ( extension !== null ) {
  14032. // TODO Complete?
  14033. return p;
  14034. } else {
  14035. return null;
  14036. }
  14037. }
  14038. if ( p === RGBA_BPTC_Format ) {
  14039. extension = extensions.get( 'EXT_texture_compression_bptc' );
  14040. if ( extension !== null ) {
  14041. // TODO Complete?
  14042. return p;
  14043. } else {
  14044. return null;
  14045. }
  14046. }
  14047. if ( p === UnsignedInt248Type ) {
  14048. if ( isWebGL2 ) return 34042;
  14049. extension = extensions.get( 'WEBGL_depth_texture' );
  14050. if ( extension !== null ) {
  14051. return extension.UNSIGNED_INT_24_8_WEBGL;
  14052. } else {
  14053. return null;
  14054. }
  14055. }
  14056. }
  14057. return { convert: convert };
  14058. }
  14059. class ArrayCamera extends PerspectiveCamera {
  14060. constructor( array = [] ) {
  14061. super();
  14062. this.cameras = array;
  14063. }
  14064. }
  14065. ArrayCamera.prototype.isArrayCamera = true;
  14066. class Group extends Object3D {
  14067. constructor() {
  14068. super();
  14069. this.type = 'Group';
  14070. }
  14071. }
  14072. Group.prototype.isGroup = true;
  14073. const _moveEvent = { type: 'move' };
  14074. class WebXRController {
  14075. constructor() {
  14076. this._targetRay = null;
  14077. this._grip = null;
  14078. this._hand = null;
  14079. }
  14080. getHandSpace() {
  14081. if ( this._hand === null ) {
  14082. this._hand = new Group();
  14083. this._hand.matrixAutoUpdate = false;
  14084. this._hand.visible = false;
  14085. this._hand.joints = {};
  14086. this._hand.inputState = { pinching: false };
  14087. }
  14088. return this._hand;
  14089. }
  14090. getTargetRaySpace() {
  14091. if ( this._targetRay === null ) {
  14092. this._targetRay = new Group();
  14093. this._targetRay.matrixAutoUpdate = false;
  14094. this._targetRay.visible = false;
  14095. this._targetRay.hasLinearVelocity = false;
  14096. this._targetRay.linearVelocity = new Vector3();
  14097. this._targetRay.hasAngularVelocity = false;
  14098. this._targetRay.angularVelocity = new Vector3();
  14099. }
  14100. return this._targetRay;
  14101. }
  14102. getGripSpace() {
  14103. if ( this._grip === null ) {
  14104. this._grip = new Group();
  14105. this._grip.matrixAutoUpdate = false;
  14106. this._grip.visible = false;
  14107. this._grip.hasLinearVelocity = false;
  14108. this._grip.linearVelocity = new Vector3();
  14109. this._grip.hasAngularVelocity = false;
  14110. this._grip.angularVelocity = new Vector3();
  14111. }
  14112. return this._grip;
  14113. }
  14114. dispatchEvent( event ) {
  14115. if ( this._targetRay !== null ) {
  14116. this._targetRay.dispatchEvent( event );
  14117. }
  14118. if ( this._grip !== null ) {
  14119. this._grip.dispatchEvent( event );
  14120. }
  14121. if ( this._hand !== null ) {
  14122. this._hand.dispatchEvent( event );
  14123. }
  14124. return this;
  14125. }
  14126. disconnect( inputSource ) {
  14127. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  14128. if ( this._targetRay !== null ) {
  14129. this._targetRay.visible = false;
  14130. }
  14131. if ( this._grip !== null ) {
  14132. this._grip.visible = false;
  14133. }
  14134. if ( this._hand !== null ) {
  14135. this._hand.visible = false;
  14136. }
  14137. return this;
  14138. }
  14139. update( inputSource, frame, referenceSpace ) {
  14140. let inputPose = null;
  14141. let gripPose = null;
  14142. let handPose = null;
  14143. const targetRay = this._targetRay;
  14144. const grip = this._grip;
  14145. const hand = this._hand;
  14146. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  14147. if ( targetRay !== null ) {
  14148. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  14149. if ( inputPose !== null ) {
  14150. targetRay.matrix.fromArray( inputPose.transform.matrix );
  14151. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  14152. if ( inputPose.linearVelocity ) {
  14153. targetRay.hasLinearVelocity = true;
  14154. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  14155. } else {
  14156. targetRay.hasLinearVelocity = false;
  14157. }
  14158. if ( inputPose.angularVelocity ) {
  14159. targetRay.hasAngularVelocity = true;
  14160. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  14161. } else {
  14162. targetRay.hasAngularVelocity = false;
  14163. }
  14164. this.dispatchEvent( _moveEvent );
  14165. }
  14166. }
  14167. if ( hand && inputSource.hand ) {
  14168. handPose = true;
  14169. for ( const inputjoint of inputSource.hand.values() ) {
  14170. // Update the joints groups with the XRJoint poses
  14171. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  14172. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  14173. // The transform of this joint will be updated with the joint pose on each frame
  14174. const joint = new Group();
  14175. joint.matrixAutoUpdate = false;
  14176. joint.visible = false;
  14177. hand.joints[ inputjoint.jointName ] = joint;
  14178. // ??
  14179. hand.add( joint );
  14180. }
  14181. const joint = hand.joints[ inputjoint.jointName ];
  14182. if ( jointPose !== null ) {
  14183. joint.matrix.fromArray( jointPose.transform.matrix );
  14184. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  14185. joint.jointRadius = jointPose.radius;
  14186. }
  14187. joint.visible = jointPose !== null;
  14188. }
  14189. // Custom events
  14190. // Check pinchz
  14191. const indexTip = hand.joints[ 'index-finger-tip' ];
  14192. const thumbTip = hand.joints[ 'thumb-tip' ];
  14193. const distance = indexTip.position.distanceTo( thumbTip.position );
  14194. const distanceToPinch = 0.02;
  14195. const threshold = 0.005;
  14196. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  14197. hand.inputState.pinching = false;
  14198. this.dispatchEvent( {
  14199. type: 'pinchend',
  14200. handedness: inputSource.handedness,
  14201. target: this
  14202. } );
  14203. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  14204. hand.inputState.pinching = true;
  14205. this.dispatchEvent( {
  14206. type: 'pinchstart',
  14207. handedness: inputSource.handedness,
  14208. target: this
  14209. } );
  14210. }
  14211. } else {
  14212. if ( grip !== null && inputSource.gripSpace ) {
  14213. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  14214. if ( gripPose !== null ) {
  14215. grip.matrix.fromArray( gripPose.transform.matrix );
  14216. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  14217. if ( gripPose.linearVelocity ) {
  14218. grip.hasLinearVelocity = true;
  14219. grip.linearVelocity.copy( gripPose.linearVelocity );
  14220. } else {
  14221. grip.hasLinearVelocity = false;
  14222. }
  14223. if ( gripPose.angularVelocity ) {
  14224. grip.hasAngularVelocity = true;
  14225. grip.angularVelocity.copy( gripPose.angularVelocity );
  14226. } else {
  14227. grip.hasAngularVelocity = false;
  14228. }
  14229. }
  14230. }
  14231. }
  14232. }
  14233. if ( targetRay !== null ) {
  14234. targetRay.visible = ( inputPose !== null );
  14235. }
  14236. if ( grip !== null ) {
  14237. grip.visible = ( gripPose !== null );
  14238. }
  14239. if ( hand !== null ) {
  14240. hand.visible = ( handPose !== null );
  14241. }
  14242. return this;
  14243. }
  14244. }
  14245. class WebXRManager extends EventDispatcher {
  14246. constructor( renderer, gl ) {
  14247. super();
  14248. const scope = this;
  14249. const state = renderer.state;
  14250. let session = null;
  14251. let framebufferScaleFactor = 1.0;
  14252. let referenceSpace = null;
  14253. let referenceSpaceType = 'local-floor';
  14254. let pose = null;
  14255. let glBinding = null;
  14256. let glFramebuffer = null;
  14257. let glProjLayer = null;
  14258. let glBaseLayer = null;
  14259. let isMultisample = false;
  14260. let glMultisampledFramebuffer = null;
  14261. let glColorRenderbuffer = null;
  14262. let glDepthRenderbuffer = null;
  14263. let xrFrame = null;
  14264. let depthStyle = null;
  14265. let clearStyle = null;
  14266. const controllers = [];
  14267. const inputSourcesMap = new Map();
  14268. //
  14269. const cameraL = new PerspectiveCamera();
  14270. cameraL.layers.enable( 1 );
  14271. cameraL.viewport = new Vector4();
  14272. const cameraR = new PerspectiveCamera();
  14273. cameraR.layers.enable( 2 );
  14274. cameraR.viewport = new Vector4();
  14275. const cameras = [ cameraL, cameraR ];
  14276. const cameraVR = new ArrayCamera();
  14277. cameraVR.layers.enable( 1 );
  14278. cameraVR.layers.enable( 2 );
  14279. let _currentDepthNear = null;
  14280. let _currentDepthFar = null;
  14281. //
  14282. this.cameraAutoUpdate = true;
  14283. this.enabled = false;
  14284. this.isPresenting = false;
  14285. this.getController = function ( index ) {
  14286. let controller = controllers[ index ];
  14287. if ( controller === undefined ) {
  14288. controller = new WebXRController();
  14289. controllers[ index ] = controller;
  14290. }
  14291. return controller.getTargetRaySpace();
  14292. };
  14293. this.getControllerGrip = function ( index ) {
  14294. let controller = controllers[ index ];
  14295. if ( controller === undefined ) {
  14296. controller = new WebXRController();
  14297. controllers[ index ] = controller;
  14298. }
  14299. return controller.getGripSpace();
  14300. };
  14301. this.getHand = function ( index ) {
  14302. let controller = controllers[ index ];
  14303. if ( controller === undefined ) {
  14304. controller = new WebXRController();
  14305. controllers[ index ] = controller;
  14306. }
  14307. return controller.getHandSpace();
  14308. };
  14309. //
  14310. function onSessionEvent( event ) {
  14311. const controller = inputSourcesMap.get( event.inputSource );
  14312. if ( controller ) {
  14313. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  14314. }
  14315. }
  14316. function onSessionEnd() {
  14317. inputSourcesMap.forEach( function ( controller, inputSource ) {
  14318. controller.disconnect( inputSource );
  14319. } );
  14320. inputSourcesMap.clear();
  14321. _currentDepthNear = null;
  14322. _currentDepthFar = null;
  14323. // restore framebuffer/rendering state
  14324. state.bindXRFramebuffer( null );
  14325. renderer.setRenderTarget( renderer.getRenderTarget() );
  14326. if ( glFramebuffer ) gl.deleteFramebuffer( glFramebuffer );
  14327. if ( glMultisampledFramebuffer ) gl.deleteFramebuffer( glMultisampledFramebuffer );
  14328. if ( glColorRenderbuffer ) gl.deleteRenderbuffer( glColorRenderbuffer );
  14329. if ( glDepthRenderbuffer ) gl.deleteRenderbuffer( glDepthRenderbuffer );
  14330. glFramebuffer = null;
  14331. glMultisampledFramebuffer = null;
  14332. glColorRenderbuffer = null;
  14333. glDepthRenderbuffer = null;
  14334. glBaseLayer = null;
  14335. glProjLayer = null;
  14336. glBinding = null;
  14337. session = null;
  14338. //
  14339. animation.stop();
  14340. scope.isPresenting = false;
  14341. scope.dispatchEvent( { type: 'sessionend' } );
  14342. }
  14343. this.setFramebufferScaleFactor = function ( value ) {
  14344. framebufferScaleFactor = value;
  14345. if ( scope.isPresenting === true ) {
  14346. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  14347. }
  14348. };
  14349. this.setReferenceSpaceType = function ( value ) {
  14350. referenceSpaceType = value;
  14351. if ( scope.isPresenting === true ) {
  14352. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  14353. }
  14354. };
  14355. this.getReferenceSpace = function () {
  14356. return referenceSpace;
  14357. };
  14358. this.getBaseLayer = function () {
  14359. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  14360. };
  14361. this.getBinding = function () {
  14362. return glBinding;
  14363. };
  14364. this.getFrame = function () {
  14365. return xrFrame;
  14366. };
  14367. this.getSession = function () {
  14368. return session;
  14369. };
  14370. this.setSession = async function ( value ) {
  14371. session = value;
  14372. if ( session !== null ) {
  14373. session.addEventListener( 'select', onSessionEvent );
  14374. session.addEventListener( 'selectstart', onSessionEvent );
  14375. session.addEventListener( 'selectend', onSessionEvent );
  14376. session.addEventListener( 'squeeze', onSessionEvent );
  14377. session.addEventListener( 'squeezestart', onSessionEvent );
  14378. session.addEventListener( 'squeezeend', onSessionEvent );
  14379. session.addEventListener( 'end', onSessionEnd );
  14380. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  14381. const attributes = gl.getContextAttributes();
  14382. if ( attributes.xrCompatible !== true ) {
  14383. await gl.makeXRCompatible();
  14384. }
  14385. if ( session.renderState.layers === undefined ) {
  14386. const layerInit = {
  14387. antialias: attributes.antialias,
  14388. alpha: attributes.alpha,
  14389. depth: attributes.depth,
  14390. stencil: attributes.stencil,
  14391. framebufferScaleFactor: framebufferScaleFactor
  14392. };
  14393. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  14394. session.updateRenderState( { baseLayer: glBaseLayer } );
  14395. } else if ( gl instanceof WebGLRenderingContext ) {
  14396. // Use old style webgl layer because we can't use MSAA
  14397. // WebGL2 support.
  14398. const layerInit = {
  14399. antialias: true,
  14400. alpha: attributes.alpha,
  14401. depth: attributes.depth,
  14402. stencil: attributes.stencil,
  14403. framebufferScaleFactor: framebufferScaleFactor
  14404. };
  14405. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  14406. session.updateRenderState( { layers: [ glBaseLayer ] } );
  14407. } else {
  14408. isMultisample = attributes.antialias;
  14409. let depthFormat = null;
  14410. if ( attributes.depth ) {
  14411. clearStyle = 256;
  14412. if ( attributes.stencil ) clearStyle |= 1024;
  14413. depthStyle = attributes.stencil ? 33306 : 36096;
  14414. depthFormat = attributes.stencil ? 35056 : 33190;
  14415. }
  14416. const projectionlayerInit = {
  14417. colorFormat: attributes.alpha ? 32856 : 32849,
  14418. depthFormat: depthFormat,
  14419. scaleFactor: framebufferScaleFactor
  14420. };
  14421. glBinding = new XRWebGLBinding( session, gl );
  14422. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  14423. glFramebuffer = gl.createFramebuffer();
  14424. session.updateRenderState( { layers: [ glProjLayer ] } );
  14425. if ( isMultisample ) {
  14426. glMultisampledFramebuffer = gl.createFramebuffer();
  14427. glColorRenderbuffer = gl.createRenderbuffer();
  14428. gl.bindRenderbuffer( 36161, glColorRenderbuffer );
  14429. gl.renderbufferStorageMultisample(
  14430. 36161,
  14431. 4,
  14432. 32856,
  14433. glProjLayer.textureWidth,
  14434. glProjLayer.textureHeight );
  14435. state.bindFramebuffer( 36160, glMultisampledFramebuffer );
  14436. gl.framebufferRenderbuffer( 36160, 36064, 36161, glColorRenderbuffer );
  14437. gl.bindRenderbuffer( 36161, null );
  14438. if ( depthFormat !== null ) {
  14439. glDepthRenderbuffer = gl.createRenderbuffer();
  14440. gl.bindRenderbuffer( 36161, glDepthRenderbuffer );
  14441. gl.renderbufferStorageMultisample( 36161, 4, depthFormat, glProjLayer.textureWidth, glProjLayer.textureHeight );
  14442. gl.framebufferRenderbuffer( 36160, depthStyle, 36161, glDepthRenderbuffer );
  14443. gl.bindRenderbuffer( 36161, null );
  14444. }
  14445. state.bindFramebuffer( 36160, null );
  14446. }
  14447. }
  14448. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  14449. animation.setContext( session );
  14450. animation.start();
  14451. scope.isPresenting = true;
  14452. scope.dispatchEvent( { type: 'sessionstart' } );
  14453. }
  14454. };
  14455. function onInputSourcesChange( event ) {
  14456. const inputSources = session.inputSources;
  14457. // Assign inputSources to available controllers
  14458. for ( let i = 0; i < controllers.length; i ++ ) {
  14459. inputSourcesMap.set( inputSources[ i ], controllers[ i ] );
  14460. }
  14461. // Notify disconnected
  14462. for ( let i = 0; i < event.removed.length; i ++ ) {
  14463. const inputSource = event.removed[ i ];
  14464. const controller = inputSourcesMap.get( inputSource );
  14465. if ( controller ) {
  14466. controller.dispatchEvent( { type: 'disconnected', data: inputSource } );
  14467. inputSourcesMap.delete( inputSource );
  14468. }
  14469. }
  14470. // Notify connected
  14471. for ( let i = 0; i < event.added.length; i ++ ) {
  14472. const inputSource = event.added[ i ];
  14473. const controller = inputSourcesMap.get( inputSource );
  14474. if ( controller ) {
  14475. controller.dispatchEvent( { type: 'connected', data: inputSource } );
  14476. }
  14477. }
  14478. }
  14479. //
  14480. const cameraLPos = new Vector3();
  14481. const cameraRPos = new Vector3();
  14482. /**
  14483. * Assumes 2 cameras that are parallel and share an X-axis, and that
  14484. * the cameras' projection and world matrices have already been set.
  14485. * And that near and far planes are identical for both cameras.
  14486. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  14487. */
  14488. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  14489. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  14490. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  14491. const ipd = cameraLPos.distanceTo( cameraRPos );
  14492. const projL = cameraL.projectionMatrix.elements;
  14493. const projR = cameraR.projectionMatrix.elements;
  14494. // VR systems will have identical far and near planes, and
  14495. // most likely identical top and bottom frustum extents.
  14496. // Use the left camera for these values.
  14497. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  14498. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  14499. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  14500. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  14501. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  14502. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  14503. const left = near * leftFov;
  14504. const right = near * rightFov;
  14505. // Calculate the new camera's position offset from the
  14506. // left camera. xOffset should be roughly half `ipd`.
  14507. const zOffset = ipd / ( - leftFov + rightFov );
  14508. const xOffset = zOffset * - leftFov;
  14509. // TODO: Better way to apply this offset?
  14510. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  14511. camera.translateX( xOffset );
  14512. camera.translateZ( zOffset );
  14513. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  14514. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  14515. // Find the union of the frustum values of the cameras and scale
  14516. // the values so that the near plane's position does not change in world space,
  14517. // although must now be relative to the new union camera.
  14518. const near2 = near + zOffset;
  14519. const far2 = far + zOffset;
  14520. const left2 = left - xOffset;
  14521. const right2 = right + ( ipd - xOffset );
  14522. const top2 = topFov * far / far2 * near2;
  14523. const bottom2 = bottomFov * far / far2 * near2;
  14524. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  14525. }
  14526. function updateCamera( camera, parent ) {
  14527. if ( parent === null ) {
  14528. camera.matrixWorld.copy( camera.matrix );
  14529. } else {
  14530. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  14531. }
  14532. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  14533. }
  14534. this.updateCamera = function ( camera ) {
  14535. if ( session === null ) return;
  14536. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  14537. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  14538. if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) {
  14539. // Note that the new renderState won't apply until the next frame. See #18320
  14540. session.updateRenderState( {
  14541. depthNear: cameraVR.near,
  14542. depthFar: cameraVR.far
  14543. } );
  14544. _currentDepthNear = cameraVR.near;
  14545. _currentDepthFar = cameraVR.far;
  14546. }
  14547. const parent = camera.parent;
  14548. const cameras = cameraVR.cameras;
  14549. updateCamera( cameraVR, parent );
  14550. for ( let i = 0; i < cameras.length; i ++ ) {
  14551. updateCamera( cameras[ i ], parent );
  14552. }
  14553. cameraVR.matrixWorld.decompose( cameraVR.position, cameraVR.quaternion, cameraVR.scale );
  14554. // update user camera and its children
  14555. camera.position.copy( cameraVR.position );
  14556. camera.quaternion.copy( cameraVR.quaternion );
  14557. camera.scale.copy( cameraVR.scale );
  14558. camera.matrix.copy( cameraVR.matrix );
  14559. camera.matrixWorld.copy( cameraVR.matrixWorld );
  14560. const children = camera.children;
  14561. for ( let i = 0, l = children.length; i < l; i ++ ) {
  14562. children[ i ].updateMatrixWorld( true );
  14563. }
  14564. // update projection matrix for proper view frustum culling
  14565. if ( cameras.length === 2 ) {
  14566. setProjectionFromUnion( cameraVR, cameraL, cameraR );
  14567. } else {
  14568. // assume single camera setup (AR)
  14569. cameraVR.projectionMatrix.copy( cameraL.projectionMatrix );
  14570. }
  14571. };
  14572. this.getCamera = function () {
  14573. return cameraVR;
  14574. };
  14575. this.getFoveation = function () {
  14576. if ( glProjLayer !== null ) {
  14577. return glProjLayer.fixedFoveation;
  14578. }
  14579. if ( glBaseLayer !== null ) {
  14580. return glBaseLayer.fixedFoveation;
  14581. }
  14582. return undefined;
  14583. };
  14584. this.setFoveation = function ( foveation ) {
  14585. // 0 = no foveation = full resolution
  14586. // 1 = maximum foveation = the edges render at lower resolution
  14587. if ( glProjLayer !== null ) {
  14588. glProjLayer.fixedFoveation = foveation;
  14589. }
  14590. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  14591. glBaseLayer.fixedFoveation = foveation;
  14592. }
  14593. };
  14594. // Animation Loop
  14595. let onAnimationFrameCallback = null;
  14596. function onAnimationFrame( time, frame ) {
  14597. pose = frame.getViewerPose( referenceSpace );
  14598. xrFrame = frame;
  14599. if ( pose !== null ) {
  14600. const views = pose.views;
  14601. if ( glBaseLayer !== null ) {
  14602. state.bindXRFramebuffer( glBaseLayer.framebuffer );
  14603. }
  14604. let cameraVRNeedsUpdate = false;
  14605. // check if it's necessary to rebuild cameraVR's camera list
  14606. if ( views.length !== cameraVR.cameras.length ) {
  14607. cameraVR.cameras.length = 0;
  14608. cameraVRNeedsUpdate = true;
  14609. }
  14610. for ( let i = 0; i < views.length; i ++ ) {
  14611. const view = views[ i ];
  14612. let viewport = null;
  14613. if ( glBaseLayer !== null ) {
  14614. viewport = glBaseLayer.getViewport( view );
  14615. } else {
  14616. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  14617. state.bindXRFramebuffer( glFramebuffer );
  14618. if ( glSubImage.depthStencilTexture !== undefined ) {
  14619. gl.framebufferTexture2D( 36160, depthStyle, 3553, glSubImage.depthStencilTexture, 0 );
  14620. }
  14621. gl.framebufferTexture2D( 36160, 36064, 3553, glSubImage.colorTexture, 0 );
  14622. viewport = glSubImage.viewport;
  14623. }
  14624. const camera = cameras[ i ];
  14625. camera.matrix.fromArray( view.transform.matrix );
  14626. camera.projectionMatrix.fromArray( view.projectionMatrix );
  14627. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  14628. if ( i === 0 ) {
  14629. cameraVR.matrix.copy( camera.matrix );
  14630. }
  14631. if ( cameraVRNeedsUpdate === true ) {
  14632. cameraVR.cameras.push( camera );
  14633. }
  14634. }
  14635. if ( isMultisample ) {
  14636. state.bindXRFramebuffer( glMultisampledFramebuffer );
  14637. if ( clearStyle !== null ) gl.clear( clearStyle );
  14638. }
  14639. }
  14640. //
  14641. const inputSources = session.inputSources;
  14642. for ( let i = 0; i < controllers.length; i ++ ) {
  14643. const controller = controllers[ i ];
  14644. const inputSource = inputSources[ i ];
  14645. controller.update( inputSource, frame, referenceSpace );
  14646. }
  14647. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  14648. if ( isMultisample ) {
  14649. const width = glProjLayer.textureWidth;
  14650. const height = glProjLayer.textureHeight;
  14651. state.bindFramebuffer( 36008, glMultisampledFramebuffer );
  14652. state.bindFramebuffer( 36009, glFramebuffer );
  14653. // Invalidate the depth here to avoid flush of the depth data to main memory.
  14654. gl.invalidateFramebuffer( 36008, [ depthStyle ] );
  14655. gl.invalidateFramebuffer( 36009, [ depthStyle ] );
  14656. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, 16384, 9728 );
  14657. // Invalidate the MSAA buffer because it's not needed anymore.
  14658. gl.invalidateFramebuffer( 36008, [ 36064 ] );
  14659. state.bindFramebuffer( 36008, null );
  14660. state.bindFramebuffer( 36009, null );
  14661. state.bindFramebuffer( 36160, glMultisampledFramebuffer );
  14662. }
  14663. xrFrame = null;
  14664. }
  14665. const animation = new WebGLAnimation();
  14666. animation.setAnimationLoop( onAnimationFrame );
  14667. this.setAnimationLoop = function ( callback ) {
  14668. onAnimationFrameCallback = callback;
  14669. };
  14670. this.dispose = function () {};
  14671. }
  14672. }
  14673. function WebGLMaterials( properties ) {
  14674. function refreshFogUniforms( uniforms, fog ) {
  14675. uniforms.fogColor.value.copy( fog.color );
  14676. if ( fog.isFog ) {
  14677. uniforms.fogNear.value = fog.near;
  14678. uniforms.fogFar.value = fog.far;
  14679. } else if ( fog.isFogExp2 ) {
  14680. uniforms.fogDensity.value = fog.density;
  14681. }
  14682. }
  14683. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  14684. if ( material.isMeshBasicMaterial ) {
  14685. refreshUniformsCommon( uniforms, material );
  14686. } else if ( material.isMeshLambertMaterial ) {
  14687. refreshUniformsCommon( uniforms, material );
  14688. refreshUniformsLambert( uniforms, material );
  14689. } else if ( material.isMeshToonMaterial ) {
  14690. refreshUniformsCommon( uniforms, material );
  14691. refreshUniformsToon( uniforms, material );
  14692. } else if ( material.isMeshPhongMaterial ) {
  14693. refreshUniformsCommon( uniforms, material );
  14694. refreshUniformsPhong( uniforms, material );
  14695. } else if ( material.isMeshStandardMaterial ) {
  14696. refreshUniformsCommon( uniforms, material );
  14697. if ( material.isMeshPhysicalMaterial ) {
  14698. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  14699. } else {
  14700. refreshUniformsStandard( uniforms, material );
  14701. }
  14702. } else if ( material.isMeshMatcapMaterial ) {
  14703. refreshUniformsCommon( uniforms, material );
  14704. refreshUniformsMatcap( uniforms, material );
  14705. } else if ( material.isMeshDepthMaterial ) {
  14706. refreshUniformsCommon( uniforms, material );
  14707. refreshUniformsDepth( uniforms, material );
  14708. } else if ( material.isMeshDistanceMaterial ) {
  14709. refreshUniformsCommon( uniforms, material );
  14710. refreshUniformsDistance( uniforms, material );
  14711. } else if ( material.isMeshNormalMaterial ) {
  14712. refreshUniformsCommon( uniforms, material );
  14713. refreshUniformsNormal( uniforms, material );
  14714. } else if ( material.isLineBasicMaterial ) {
  14715. refreshUniformsLine( uniforms, material );
  14716. if ( material.isLineDashedMaterial ) {
  14717. refreshUniformsDash( uniforms, material );
  14718. }
  14719. } else if ( material.isPointsMaterial ) {
  14720. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  14721. } else if ( material.isSpriteMaterial ) {
  14722. refreshUniformsSprites( uniforms, material );
  14723. } else if ( material.isShadowMaterial ) {
  14724. uniforms.color.value.copy( material.color );
  14725. uniforms.opacity.value = material.opacity;
  14726. } else if ( material.isShaderMaterial ) {
  14727. material.uniformsNeedUpdate = false; // #15581
  14728. }
  14729. }
  14730. function refreshUniformsCommon( uniforms, material ) {
  14731. uniforms.opacity.value = material.opacity;
  14732. if ( material.color ) {
  14733. uniforms.diffuse.value.copy( material.color );
  14734. }
  14735. if ( material.emissive ) {
  14736. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  14737. }
  14738. if ( material.map ) {
  14739. uniforms.map.value = material.map;
  14740. }
  14741. if ( material.alphaMap ) {
  14742. uniforms.alphaMap.value = material.alphaMap;
  14743. }
  14744. if ( material.specularMap ) {
  14745. uniforms.specularMap.value = material.specularMap;
  14746. }
  14747. if ( material.alphaTest > 0 ) {
  14748. uniforms.alphaTest.value = material.alphaTest;
  14749. }
  14750. const envMap = properties.get( material ).envMap;
  14751. if ( envMap ) {
  14752. uniforms.envMap.value = envMap;
  14753. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  14754. uniforms.reflectivity.value = material.reflectivity;
  14755. uniforms.ior.value = material.ior;
  14756. uniforms.refractionRatio.value = material.refractionRatio;
  14757. const maxMipLevel = properties.get( envMap ).__maxMipLevel;
  14758. if ( maxMipLevel !== undefined ) {
  14759. uniforms.maxMipLevel.value = maxMipLevel;
  14760. }
  14761. }
  14762. if ( material.lightMap ) {
  14763. uniforms.lightMap.value = material.lightMap;
  14764. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  14765. }
  14766. if ( material.aoMap ) {
  14767. uniforms.aoMap.value = material.aoMap;
  14768. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  14769. }
  14770. // uv repeat and offset setting priorities
  14771. // 1. color map
  14772. // 2. specular map
  14773. // 3. displacementMap map
  14774. // 4. normal map
  14775. // 5. bump map
  14776. // 6. roughnessMap map
  14777. // 7. metalnessMap map
  14778. // 8. alphaMap map
  14779. // 9. emissiveMap map
  14780. // 10. clearcoat map
  14781. // 11. clearcoat normal map
  14782. // 12. clearcoat roughnessMap map
  14783. // 13. specular intensity map
  14784. // 14. specular tint map
  14785. // 15. transmission map
  14786. // 16. thickness map
  14787. let uvScaleMap;
  14788. if ( material.map ) {
  14789. uvScaleMap = material.map;
  14790. } else if ( material.specularMap ) {
  14791. uvScaleMap = material.specularMap;
  14792. } else if ( material.displacementMap ) {
  14793. uvScaleMap = material.displacementMap;
  14794. } else if ( material.normalMap ) {
  14795. uvScaleMap = material.normalMap;
  14796. } else if ( material.bumpMap ) {
  14797. uvScaleMap = material.bumpMap;
  14798. } else if ( material.roughnessMap ) {
  14799. uvScaleMap = material.roughnessMap;
  14800. } else if ( material.metalnessMap ) {
  14801. uvScaleMap = material.metalnessMap;
  14802. } else if ( material.alphaMap ) {
  14803. uvScaleMap = material.alphaMap;
  14804. } else if ( material.emissiveMap ) {
  14805. uvScaleMap = material.emissiveMap;
  14806. } else if ( material.clearcoatMap ) {
  14807. uvScaleMap = material.clearcoatMap;
  14808. } else if ( material.clearcoatNormalMap ) {
  14809. uvScaleMap = material.clearcoatNormalMap;
  14810. } else if ( material.clearcoatRoughnessMap ) {
  14811. uvScaleMap = material.clearcoatRoughnessMap;
  14812. } else if ( material.specularIntensityMap ) {
  14813. uvScaleMap = material.specularIntensityMap;
  14814. } else if ( material.specularTintMap ) {
  14815. uvScaleMap = material.specularTintMap;
  14816. } else if ( material.transmissionMap ) {
  14817. uvScaleMap = material.transmissionMap;
  14818. } else if ( material.thicknessMap ) {
  14819. uvScaleMap = material.thicknessMap;
  14820. }
  14821. if ( uvScaleMap !== undefined ) {
  14822. // backwards compatibility
  14823. if ( uvScaleMap.isWebGLRenderTarget ) {
  14824. uvScaleMap = uvScaleMap.texture;
  14825. }
  14826. if ( uvScaleMap.matrixAutoUpdate === true ) {
  14827. uvScaleMap.updateMatrix();
  14828. }
  14829. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  14830. }
  14831. // uv repeat and offset setting priorities for uv2
  14832. // 1. ao map
  14833. // 2. light map
  14834. let uv2ScaleMap;
  14835. if ( material.aoMap ) {
  14836. uv2ScaleMap = material.aoMap;
  14837. } else if ( material.lightMap ) {
  14838. uv2ScaleMap = material.lightMap;
  14839. }
  14840. if ( uv2ScaleMap !== undefined ) {
  14841. // backwards compatibility
  14842. if ( uv2ScaleMap.isWebGLRenderTarget ) {
  14843. uv2ScaleMap = uv2ScaleMap.texture;
  14844. }
  14845. if ( uv2ScaleMap.matrixAutoUpdate === true ) {
  14846. uv2ScaleMap.updateMatrix();
  14847. }
  14848. uniforms.uv2Transform.value.copy( uv2ScaleMap.matrix );
  14849. }
  14850. }
  14851. function refreshUniformsLine( uniforms, material ) {
  14852. uniforms.diffuse.value.copy( material.color );
  14853. uniforms.opacity.value = material.opacity;
  14854. }
  14855. function refreshUniformsDash( uniforms, material ) {
  14856. uniforms.dashSize.value = material.dashSize;
  14857. uniforms.totalSize.value = material.dashSize + material.gapSize;
  14858. uniforms.scale.value = material.scale;
  14859. }
  14860. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  14861. uniforms.diffuse.value.copy( material.color );
  14862. uniforms.opacity.value = material.opacity;
  14863. uniforms.size.value = material.size * pixelRatio;
  14864. uniforms.scale.value = height * 0.5;
  14865. if ( material.map ) {
  14866. uniforms.map.value = material.map;
  14867. }
  14868. if ( material.alphaMap ) {
  14869. uniforms.alphaMap.value = material.alphaMap;
  14870. }
  14871. if ( material.alphaTest > 0 ) {
  14872. uniforms.alphaTest.value = material.alphaTest;
  14873. }
  14874. // uv repeat and offset setting priorities
  14875. // 1. color map
  14876. // 2. alpha map
  14877. let uvScaleMap;
  14878. if ( material.map ) {
  14879. uvScaleMap = material.map;
  14880. } else if ( material.alphaMap ) {
  14881. uvScaleMap = material.alphaMap;
  14882. }
  14883. if ( uvScaleMap !== undefined ) {
  14884. if ( uvScaleMap.matrixAutoUpdate === true ) {
  14885. uvScaleMap.updateMatrix();
  14886. }
  14887. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  14888. }
  14889. }
  14890. function refreshUniformsSprites( uniforms, material ) {
  14891. uniforms.diffuse.value.copy( material.color );
  14892. uniforms.opacity.value = material.opacity;
  14893. uniforms.rotation.value = material.rotation;
  14894. if ( material.map ) {
  14895. uniforms.map.value = material.map;
  14896. }
  14897. if ( material.alphaMap ) {
  14898. uniforms.alphaMap.value = material.alphaMap;
  14899. }
  14900. if ( material.alphaTest > 0 ) {
  14901. uniforms.alphaTest.value = material.alphaTest;
  14902. }
  14903. // uv repeat and offset setting priorities
  14904. // 1. color map
  14905. // 2. alpha map
  14906. let uvScaleMap;
  14907. if ( material.map ) {
  14908. uvScaleMap = material.map;
  14909. } else if ( material.alphaMap ) {
  14910. uvScaleMap = material.alphaMap;
  14911. }
  14912. if ( uvScaleMap !== undefined ) {
  14913. if ( uvScaleMap.matrixAutoUpdate === true ) {
  14914. uvScaleMap.updateMatrix();
  14915. }
  14916. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  14917. }
  14918. }
  14919. function refreshUniformsLambert( uniforms, material ) {
  14920. if ( material.emissiveMap ) {
  14921. uniforms.emissiveMap.value = material.emissiveMap;
  14922. }
  14923. }
  14924. function refreshUniformsPhong( uniforms, material ) {
  14925. uniforms.specular.value.copy( material.specular );
  14926. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  14927. if ( material.emissiveMap ) {
  14928. uniforms.emissiveMap.value = material.emissiveMap;
  14929. }
  14930. if ( material.bumpMap ) {
  14931. uniforms.bumpMap.value = material.bumpMap;
  14932. uniforms.bumpScale.value = material.bumpScale;
  14933. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  14934. }
  14935. if ( material.normalMap ) {
  14936. uniforms.normalMap.value = material.normalMap;
  14937. uniforms.normalScale.value.copy( material.normalScale );
  14938. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  14939. }
  14940. if ( material.displacementMap ) {
  14941. uniforms.displacementMap.value = material.displacementMap;
  14942. uniforms.displacementScale.value = material.displacementScale;
  14943. uniforms.displacementBias.value = material.displacementBias;
  14944. }
  14945. }
  14946. function refreshUniformsToon( uniforms, material ) {
  14947. if ( material.gradientMap ) {
  14948. uniforms.gradientMap.value = material.gradientMap;
  14949. }
  14950. if ( material.emissiveMap ) {
  14951. uniforms.emissiveMap.value = material.emissiveMap;
  14952. }
  14953. if ( material.bumpMap ) {
  14954. uniforms.bumpMap.value = material.bumpMap;
  14955. uniforms.bumpScale.value = material.bumpScale;
  14956. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  14957. }
  14958. if ( material.normalMap ) {
  14959. uniforms.normalMap.value = material.normalMap;
  14960. uniforms.normalScale.value.copy( material.normalScale );
  14961. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  14962. }
  14963. if ( material.displacementMap ) {
  14964. uniforms.displacementMap.value = material.displacementMap;
  14965. uniforms.displacementScale.value = material.displacementScale;
  14966. uniforms.displacementBias.value = material.displacementBias;
  14967. }
  14968. }
  14969. function refreshUniformsStandard( uniforms, material ) {
  14970. uniforms.roughness.value = material.roughness;
  14971. uniforms.metalness.value = material.metalness;
  14972. if ( material.roughnessMap ) {
  14973. uniforms.roughnessMap.value = material.roughnessMap;
  14974. }
  14975. if ( material.metalnessMap ) {
  14976. uniforms.metalnessMap.value = material.metalnessMap;
  14977. }
  14978. if ( material.emissiveMap ) {
  14979. uniforms.emissiveMap.value = material.emissiveMap;
  14980. }
  14981. if ( material.bumpMap ) {
  14982. uniforms.bumpMap.value = material.bumpMap;
  14983. uniforms.bumpScale.value = material.bumpScale;
  14984. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  14985. }
  14986. if ( material.normalMap ) {
  14987. uniforms.normalMap.value = material.normalMap;
  14988. uniforms.normalScale.value.copy( material.normalScale );
  14989. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  14990. }
  14991. if ( material.displacementMap ) {
  14992. uniforms.displacementMap.value = material.displacementMap;
  14993. uniforms.displacementScale.value = material.displacementScale;
  14994. uniforms.displacementBias.value = material.displacementBias;
  14995. }
  14996. const envMap = properties.get( material ).envMap;
  14997. if ( envMap ) {
  14998. //uniforms.envMap.value = material.envMap; // part of uniforms common
  14999. uniforms.envMapIntensity.value = material.envMapIntensity;
  15000. }
  15001. }
  15002. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  15003. refreshUniformsStandard( uniforms, material );
  15004. uniforms.ior.value = material.ior; // also part of uniforms common
  15005. if ( material.sheen > 0 ) {
  15006. uniforms.sheenTint.value.copy( material.sheenTint ).multiplyScalar( material.sheen );
  15007. uniforms.sheenRoughness.value = material.sheenRoughness;
  15008. }
  15009. if ( material.clearcoat > 0 ) {
  15010. uniforms.clearcoat.value = material.clearcoat;
  15011. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  15012. if ( material.clearcoatMap ) {
  15013. uniforms.clearcoatMap.value = material.clearcoatMap;
  15014. }
  15015. if ( material.clearcoatRoughnessMap ) {
  15016. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  15017. }
  15018. if ( material.clearcoatNormalMap ) {
  15019. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  15020. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  15021. if ( material.side === BackSide ) {
  15022. uniforms.clearcoatNormalScale.value.negate();
  15023. }
  15024. }
  15025. }
  15026. if ( material.transmission > 0 ) {
  15027. uniforms.transmission.value = material.transmission;
  15028. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  15029. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  15030. if ( material.transmissionMap ) {
  15031. uniforms.transmissionMap.value = material.transmissionMap;
  15032. }
  15033. uniforms.thickness.value = material.thickness;
  15034. if ( material.thicknessMap ) {
  15035. uniforms.thicknessMap.value = material.thicknessMap;
  15036. }
  15037. uniforms.attenuationDistance.value = material.attenuationDistance;
  15038. uniforms.attenuationTint.value.copy( material.attenuationTint );
  15039. }
  15040. uniforms.specularIntensity.value = material.specularIntensity;
  15041. uniforms.specularTint.value.copy( material.specularTint );
  15042. if ( material.specularIntensityMap ) {
  15043. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  15044. }
  15045. if ( material.specularTintMap ) {
  15046. uniforms.specularTintMap.value = material.specularTintMap;
  15047. }
  15048. }
  15049. function refreshUniformsMatcap( uniforms, material ) {
  15050. if ( material.matcap ) {
  15051. uniforms.matcap.value = material.matcap;
  15052. }
  15053. if ( material.bumpMap ) {
  15054. uniforms.bumpMap.value = material.bumpMap;
  15055. uniforms.bumpScale.value = material.bumpScale;
  15056. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  15057. }
  15058. if ( material.normalMap ) {
  15059. uniforms.normalMap.value = material.normalMap;
  15060. uniforms.normalScale.value.copy( material.normalScale );
  15061. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  15062. }
  15063. if ( material.displacementMap ) {
  15064. uniforms.displacementMap.value = material.displacementMap;
  15065. uniforms.displacementScale.value = material.displacementScale;
  15066. uniforms.displacementBias.value = material.displacementBias;
  15067. }
  15068. }
  15069. function refreshUniformsDepth( uniforms, material ) {
  15070. if ( material.displacementMap ) {
  15071. uniforms.displacementMap.value = material.displacementMap;
  15072. uniforms.displacementScale.value = material.displacementScale;
  15073. uniforms.displacementBias.value = material.displacementBias;
  15074. }
  15075. }
  15076. function refreshUniformsDistance( uniforms, material ) {
  15077. if ( material.displacementMap ) {
  15078. uniforms.displacementMap.value = material.displacementMap;
  15079. uniforms.displacementScale.value = material.displacementScale;
  15080. uniforms.displacementBias.value = material.displacementBias;
  15081. }
  15082. uniforms.referencePosition.value.copy( material.referencePosition );
  15083. uniforms.nearDistance.value = material.nearDistance;
  15084. uniforms.farDistance.value = material.farDistance;
  15085. }
  15086. function refreshUniformsNormal( uniforms, material ) {
  15087. if ( material.bumpMap ) {
  15088. uniforms.bumpMap.value = material.bumpMap;
  15089. uniforms.bumpScale.value = material.bumpScale;
  15090. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  15091. }
  15092. if ( material.normalMap ) {
  15093. uniforms.normalMap.value = material.normalMap;
  15094. uniforms.normalScale.value.copy( material.normalScale );
  15095. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  15096. }
  15097. if ( material.displacementMap ) {
  15098. uniforms.displacementMap.value = material.displacementMap;
  15099. uniforms.displacementScale.value = material.displacementScale;
  15100. uniforms.displacementBias.value = material.displacementBias;
  15101. }
  15102. }
  15103. return {
  15104. refreshFogUniforms: refreshFogUniforms,
  15105. refreshMaterialUniforms: refreshMaterialUniforms
  15106. };
  15107. }
  15108. function createCanvasElement() {
  15109. const canvas = createElementNS( 'canvas' );
  15110. canvas.style.display = 'block';
  15111. return canvas;
  15112. }
  15113. function WebGLRenderer( parameters = {} ) {
  15114. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  15115. _context = parameters.context !== undefined ? parameters.context : null,
  15116. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  15117. _depth = parameters.depth !== undefined ? parameters.depth : true,
  15118. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  15119. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  15120. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  15121. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  15122. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  15123. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  15124. let currentRenderList = null;
  15125. let currentRenderState = null;
  15126. // render() can be called from within a callback triggered by another render.
  15127. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  15128. const renderListStack = [];
  15129. const renderStateStack = [];
  15130. // public properties
  15131. this.domElement = _canvas;
  15132. // Debug configuration container
  15133. this.debug = {
  15134. /**
  15135. * Enables error checking and reporting when shader programs are being compiled
  15136. * @type {boolean}
  15137. */
  15138. checkShaderErrors: true
  15139. };
  15140. // clearing
  15141. this.autoClear = true;
  15142. this.autoClearColor = true;
  15143. this.autoClearDepth = true;
  15144. this.autoClearStencil = true;
  15145. // scene graph
  15146. this.sortObjects = true;
  15147. // user-defined clipping
  15148. this.clippingPlanes = [];
  15149. this.localClippingEnabled = false;
  15150. // physically based shading
  15151. this.gammaFactor = 2.0; // for backwards compatibility
  15152. this.outputEncoding = LinearEncoding;
  15153. // physical lights
  15154. this.physicallyCorrectLights = false;
  15155. // tone mapping
  15156. this.toneMapping = NoToneMapping;
  15157. this.toneMappingExposure = 1.0;
  15158. // internal properties
  15159. const _this = this;
  15160. let _isContextLost = false;
  15161. // internal state cache
  15162. let _currentActiveCubeFace = 0;
  15163. let _currentActiveMipmapLevel = 0;
  15164. let _currentRenderTarget = null;
  15165. let _currentMaterialId = - 1;
  15166. let _currentCamera = null;
  15167. const _currentViewport = new Vector4();
  15168. const _currentScissor = new Vector4();
  15169. let _currentScissorTest = null;
  15170. //
  15171. let _width = _canvas.width;
  15172. let _height = _canvas.height;
  15173. let _pixelRatio = 1;
  15174. let _opaqueSort = null;
  15175. let _transparentSort = null;
  15176. const _viewport = new Vector4( 0, 0, _width, _height );
  15177. const _scissor = new Vector4( 0, 0, _width, _height );
  15178. let _scissorTest = false;
  15179. //
  15180. const _currentDrawBuffers = [];
  15181. // frustum
  15182. const _frustum = new Frustum();
  15183. // clipping
  15184. let _clippingEnabled = false;
  15185. let _localClippingEnabled = false;
  15186. // transmission
  15187. let _transmissionRenderTarget = null;
  15188. // camera matrices cache
  15189. const _projScreenMatrix = new Matrix4();
  15190. const _vector3 = new Vector3();
  15191. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  15192. function getTargetPixelRatio() {
  15193. return _currentRenderTarget === null ? _pixelRatio : 1;
  15194. }
  15195. // initialize
  15196. let _gl = _context;
  15197. function getContext( contextNames, contextAttributes ) {
  15198. for ( let i = 0; i < contextNames.length; i ++ ) {
  15199. const contextName = contextNames[ i ];
  15200. const context = _canvas.getContext( contextName, contextAttributes );
  15201. if ( context !== null ) return context;
  15202. }
  15203. return null;
  15204. }
  15205. try {
  15206. const contextAttributes = {
  15207. alpha: _alpha,
  15208. depth: _depth,
  15209. stencil: _stencil,
  15210. antialias: _antialias,
  15211. premultipliedAlpha: _premultipliedAlpha,
  15212. preserveDrawingBuffer: _preserveDrawingBuffer,
  15213. powerPreference: _powerPreference,
  15214. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  15215. };
  15216. // event listeners must be registered before WebGL context is created, see #12753
  15217. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  15218. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  15219. if ( _gl === null ) {
  15220. const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ];
  15221. if ( _this.isWebGL1Renderer === true ) {
  15222. contextNames.shift();
  15223. }
  15224. _gl = getContext( contextNames, contextAttributes );
  15225. if ( _gl === null ) {
  15226. if ( getContext( contextNames ) ) {
  15227. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  15228. } else {
  15229. throw new Error( 'Error creating WebGL context.' );
  15230. }
  15231. }
  15232. }
  15233. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  15234. if ( _gl.getShaderPrecisionFormat === undefined ) {
  15235. _gl.getShaderPrecisionFormat = function () {
  15236. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  15237. };
  15238. }
  15239. } catch ( error ) {
  15240. console.error( 'THREE.WebGLRenderer: ' + error.message );
  15241. throw error;
  15242. }
  15243. let extensions, capabilities, state, info;
  15244. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  15245. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  15246. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  15247. let utils, bindingStates;
  15248. function initGLContext() {
  15249. extensions = new WebGLExtensions( _gl );
  15250. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  15251. extensions.init( capabilities );
  15252. utils = new WebGLUtils( _gl, extensions, capabilities );
  15253. state = new WebGLState( _gl, extensions, capabilities );
  15254. _currentDrawBuffers[ 0 ] = 1029;
  15255. info = new WebGLInfo( _gl );
  15256. properties = new WebGLProperties();
  15257. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  15258. cubemaps = new WebGLCubeMaps( _this );
  15259. cubeuvmaps = new WebGLCubeUVMaps( _this );
  15260. attributes = new WebGLAttributes( _gl, capabilities );
  15261. bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities );
  15262. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  15263. objects = new WebGLObjects( _gl, geometries, attributes, info );
  15264. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  15265. clipping = new WebGLClipping( properties );
  15266. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  15267. materials = new WebGLMaterials( properties );
  15268. renderLists = new WebGLRenderLists( properties );
  15269. renderStates = new WebGLRenderStates( extensions, capabilities );
  15270. background = new WebGLBackground( _this, cubemaps, state, objects, _premultipliedAlpha );
  15271. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  15272. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  15273. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  15274. info.programs = programCache.programs;
  15275. _this.capabilities = capabilities;
  15276. _this.extensions = extensions;
  15277. _this.properties = properties;
  15278. _this.renderLists = renderLists;
  15279. _this.shadowMap = shadowMap;
  15280. _this.state = state;
  15281. _this.info = info;
  15282. }
  15283. initGLContext();
  15284. // xr
  15285. const xr = new WebXRManager( _this, _gl );
  15286. this.xr = xr;
  15287. // API
  15288. this.getContext = function () {
  15289. return _gl;
  15290. };
  15291. this.getContextAttributes = function () {
  15292. return _gl.getContextAttributes();
  15293. };
  15294. this.forceContextLoss = function () {
  15295. const extension = extensions.get( 'WEBGL_lose_context' );
  15296. if ( extension ) extension.loseContext();
  15297. };
  15298. this.forceContextRestore = function () {
  15299. const extension = extensions.get( 'WEBGL_lose_context' );
  15300. if ( extension ) extension.restoreContext();
  15301. };
  15302. this.getPixelRatio = function () {
  15303. return _pixelRatio;
  15304. };
  15305. this.setPixelRatio = function ( value ) {
  15306. if ( value === undefined ) return;
  15307. _pixelRatio = value;
  15308. this.setSize( _width, _height, false );
  15309. };
  15310. this.getSize = function ( target ) {
  15311. return target.set( _width, _height );
  15312. };
  15313. this.setSize = function ( width, height, updateStyle ) {
  15314. if ( xr.isPresenting ) {
  15315. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  15316. return;
  15317. }
  15318. _width = width;
  15319. _height = height;
  15320. _canvas.width = Math.floor( width * _pixelRatio );
  15321. _canvas.height = Math.floor( height * _pixelRatio );
  15322. if ( updateStyle !== false ) {
  15323. _canvas.style.width = width + 'px';
  15324. _canvas.style.height = height + 'px';
  15325. }
  15326. this.setViewport( 0, 0, width, height );
  15327. };
  15328. this.getDrawingBufferSize = function ( target ) {
  15329. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  15330. };
  15331. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  15332. _width = width;
  15333. _height = height;
  15334. _pixelRatio = pixelRatio;
  15335. _canvas.width = Math.floor( width * pixelRatio );
  15336. _canvas.height = Math.floor( height * pixelRatio );
  15337. this.setViewport( 0, 0, width, height );
  15338. };
  15339. this.getCurrentViewport = function ( target ) {
  15340. return target.copy( _currentViewport );
  15341. };
  15342. this.getViewport = function ( target ) {
  15343. return target.copy( _viewport );
  15344. };
  15345. this.setViewport = function ( x, y, width, height ) {
  15346. if ( x.isVector4 ) {
  15347. _viewport.set( x.x, x.y, x.z, x.w );
  15348. } else {
  15349. _viewport.set( x, y, width, height );
  15350. }
  15351. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  15352. };
  15353. this.getScissor = function ( target ) {
  15354. return target.copy( _scissor );
  15355. };
  15356. this.setScissor = function ( x, y, width, height ) {
  15357. if ( x.isVector4 ) {
  15358. _scissor.set( x.x, x.y, x.z, x.w );
  15359. } else {
  15360. _scissor.set( x, y, width, height );
  15361. }
  15362. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  15363. };
  15364. this.getScissorTest = function () {
  15365. return _scissorTest;
  15366. };
  15367. this.setScissorTest = function ( boolean ) {
  15368. state.setScissorTest( _scissorTest = boolean );
  15369. };
  15370. this.setOpaqueSort = function ( method ) {
  15371. _opaqueSort = method;
  15372. };
  15373. this.setTransparentSort = function ( method ) {
  15374. _transparentSort = method;
  15375. };
  15376. // Clearing
  15377. this.getClearColor = function ( target ) {
  15378. return target.copy( background.getClearColor() );
  15379. };
  15380. this.setClearColor = function () {
  15381. background.setClearColor.apply( background, arguments );
  15382. };
  15383. this.getClearAlpha = function () {
  15384. return background.getClearAlpha();
  15385. };
  15386. this.setClearAlpha = function () {
  15387. background.setClearAlpha.apply( background, arguments );
  15388. };
  15389. this.clear = function ( color, depth, stencil ) {
  15390. let bits = 0;
  15391. if ( color === undefined || color ) bits |= 16384;
  15392. if ( depth === undefined || depth ) bits |= 256;
  15393. if ( stencil === undefined || stencil ) bits |= 1024;
  15394. _gl.clear( bits );
  15395. };
  15396. this.clearColor = function () {
  15397. this.clear( true, false, false );
  15398. };
  15399. this.clearDepth = function () {
  15400. this.clear( false, true, false );
  15401. };
  15402. this.clearStencil = function () {
  15403. this.clear( false, false, true );
  15404. };
  15405. //
  15406. this.dispose = function () {
  15407. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  15408. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  15409. renderLists.dispose();
  15410. renderStates.dispose();
  15411. properties.dispose();
  15412. cubemaps.dispose();
  15413. cubeuvmaps.dispose();
  15414. objects.dispose();
  15415. bindingStates.dispose();
  15416. xr.dispose();
  15417. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  15418. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  15419. if ( _transmissionRenderTarget ) {
  15420. _transmissionRenderTarget.dispose();
  15421. _transmissionRenderTarget = null;
  15422. }
  15423. animation.stop();
  15424. };
  15425. // Events
  15426. function onContextLost( event ) {
  15427. event.preventDefault();
  15428. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  15429. _isContextLost = true;
  15430. }
  15431. function onContextRestore( /* event */ ) {
  15432. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  15433. _isContextLost = false;
  15434. const infoAutoReset = info.autoReset;
  15435. const shadowMapEnabled = shadowMap.enabled;
  15436. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  15437. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  15438. const shadowMapType = shadowMap.type;
  15439. initGLContext();
  15440. info.autoReset = infoAutoReset;
  15441. shadowMap.enabled = shadowMapEnabled;
  15442. shadowMap.autoUpdate = shadowMapAutoUpdate;
  15443. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  15444. shadowMap.type = shadowMapType;
  15445. }
  15446. function onMaterialDispose( event ) {
  15447. const material = event.target;
  15448. material.removeEventListener( 'dispose', onMaterialDispose );
  15449. deallocateMaterial( material );
  15450. }
  15451. // Buffer deallocation
  15452. function deallocateMaterial( material ) {
  15453. releaseMaterialProgramReferences( material );
  15454. properties.remove( material );
  15455. }
  15456. function releaseMaterialProgramReferences( material ) {
  15457. const programs = properties.get( material ).programs;
  15458. if ( programs !== undefined ) {
  15459. programs.forEach( function ( program ) {
  15460. programCache.releaseProgram( program );
  15461. } );
  15462. }
  15463. }
  15464. // Buffer rendering
  15465. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  15466. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  15467. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  15468. const program = setProgram( camera, scene, geometry, material, object );
  15469. state.setMaterial( material, frontFaceCW );
  15470. //
  15471. let index = geometry.index;
  15472. const position = geometry.attributes.position;
  15473. //
  15474. if ( index === null ) {
  15475. if ( position === undefined || position.count === 0 ) return;
  15476. } else if ( index.count === 0 ) {
  15477. return;
  15478. }
  15479. //
  15480. let rangeFactor = 1;
  15481. if ( material.wireframe === true ) {
  15482. index = geometries.getWireframeAttribute( geometry );
  15483. rangeFactor = 2;
  15484. }
  15485. bindingStates.setup( object, material, program, geometry, index );
  15486. let attribute;
  15487. let renderer = bufferRenderer;
  15488. if ( index !== null ) {
  15489. attribute = attributes.get( index );
  15490. renderer = indexedBufferRenderer;
  15491. renderer.setIndex( attribute );
  15492. }
  15493. //
  15494. const dataCount = ( index !== null ) ? index.count : position.count;
  15495. const rangeStart = geometry.drawRange.start * rangeFactor;
  15496. const rangeCount = geometry.drawRange.count * rangeFactor;
  15497. const groupStart = group !== null ? group.start * rangeFactor : 0;
  15498. const groupCount = group !== null ? group.count * rangeFactor : Infinity;
  15499. const drawStart = Math.max( rangeStart, groupStart );
  15500. const drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  15501. const drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  15502. if ( drawCount === 0 ) return;
  15503. //
  15504. if ( object.isMesh ) {
  15505. if ( material.wireframe === true ) {
  15506. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  15507. renderer.setMode( 1 );
  15508. } else {
  15509. renderer.setMode( 4 );
  15510. }
  15511. } else if ( object.isLine ) {
  15512. let lineWidth = material.linewidth;
  15513. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  15514. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  15515. if ( object.isLineSegments ) {
  15516. renderer.setMode( 1 );
  15517. } else if ( object.isLineLoop ) {
  15518. renderer.setMode( 2 );
  15519. } else {
  15520. renderer.setMode( 3 );
  15521. }
  15522. } else if ( object.isPoints ) {
  15523. renderer.setMode( 0 );
  15524. } else if ( object.isSprite ) {
  15525. renderer.setMode( 4 );
  15526. }
  15527. if ( object.isInstancedMesh ) {
  15528. renderer.renderInstances( drawStart, drawCount, object.count );
  15529. } else if ( geometry.isInstancedBufferGeometry ) {
  15530. const instanceCount = Math.min( geometry.instanceCount, geometry._maxInstanceCount );
  15531. renderer.renderInstances( drawStart, drawCount, instanceCount );
  15532. } else {
  15533. renderer.render( drawStart, drawCount );
  15534. }
  15535. };
  15536. // Compile
  15537. this.compile = function ( scene, camera ) {
  15538. currentRenderState = renderStates.get( scene );
  15539. currentRenderState.init();
  15540. renderStateStack.push( currentRenderState );
  15541. scene.traverseVisible( function ( object ) {
  15542. if ( object.isLight && object.layers.test( camera.layers ) ) {
  15543. currentRenderState.pushLight( object );
  15544. if ( object.castShadow ) {
  15545. currentRenderState.pushShadow( object );
  15546. }
  15547. }
  15548. } );
  15549. currentRenderState.setupLights( _this.physicallyCorrectLights );
  15550. scene.traverse( function ( object ) {
  15551. const material = object.material;
  15552. if ( material ) {
  15553. if ( Array.isArray( material ) ) {
  15554. for ( let i = 0; i < material.length; i ++ ) {
  15555. const material2 = material[ i ];
  15556. getProgram( material2, scene, object );
  15557. }
  15558. } else {
  15559. getProgram( material, scene, object );
  15560. }
  15561. }
  15562. } );
  15563. renderStateStack.pop();
  15564. currentRenderState = null;
  15565. };
  15566. // Animation Loop
  15567. let onAnimationFrameCallback = null;
  15568. function onAnimationFrame( time ) {
  15569. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  15570. }
  15571. function onXRSessionStart() {
  15572. animation.stop();
  15573. }
  15574. function onXRSessionEnd() {
  15575. animation.start();
  15576. }
  15577. const animation = new WebGLAnimation();
  15578. animation.setAnimationLoop( onAnimationFrame );
  15579. if ( typeof window !== 'undefined' ) animation.setContext( window );
  15580. this.setAnimationLoop = function ( callback ) {
  15581. onAnimationFrameCallback = callback;
  15582. xr.setAnimationLoop( callback );
  15583. ( callback === null ) ? animation.stop() : animation.start();
  15584. };
  15585. xr.addEventListener( 'sessionstart', onXRSessionStart );
  15586. xr.addEventListener( 'sessionend', onXRSessionEnd );
  15587. // Rendering
  15588. this.render = function ( scene, camera ) {
  15589. if ( camera !== undefined && camera.isCamera !== true ) {
  15590. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  15591. return;
  15592. }
  15593. if ( _isContextLost === true ) return;
  15594. // update scene graph
  15595. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  15596. // update camera matrices and frustum
  15597. if ( camera.parent === null ) camera.updateMatrixWorld();
  15598. if ( xr.enabled === true && xr.isPresenting === true ) {
  15599. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  15600. camera = xr.getCamera(); // use XR camera for rendering
  15601. }
  15602. //
  15603. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  15604. currentRenderState = renderStates.get( scene, renderStateStack.length );
  15605. currentRenderState.init();
  15606. renderStateStack.push( currentRenderState );
  15607. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  15608. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  15609. _localClippingEnabled = this.localClippingEnabled;
  15610. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  15611. currentRenderList = renderLists.get( scene, renderListStack.length );
  15612. currentRenderList.init();
  15613. renderListStack.push( currentRenderList );
  15614. projectObject( scene, camera, 0, _this.sortObjects );
  15615. currentRenderList.finish();
  15616. if ( _this.sortObjects === true ) {
  15617. currentRenderList.sort( _opaqueSort, _transparentSort );
  15618. }
  15619. //
  15620. if ( _clippingEnabled === true ) clipping.beginShadows();
  15621. const shadowsArray = currentRenderState.state.shadowsArray;
  15622. shadowMap.render( shadowsArray, scene, camera );
  15623. if ( _clippingEnabled === true ) clipping.endShadows();
  15624. //
  15625. if ( this.info.autoReset === true ) this.info.reset();
  15626. //
  15627. background.render( currentRenderList, scene );
  15628. // render scene
  15629. currentRenderState.setupLights( _this.physicallyCorrectLights );
  15630. if ( camera.isArrayCamera ) {
  15631. const cameras = camera.cameras;
  15632. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  15633. const camera2 = cameras[ i ];
  15634. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  15635. }
  15636. } else {
  15637. renderScene( currentRenderList, scene, camera );
  15638. }
  15639. //
  15640. if ( _currentRenderTarget !== null ) {
  15641. // resolve multisample renderbuffers to a single-sample texture if necessary
  15642. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  15643. // Generate mipmap if we're using any kind of mipmap filtering
  15644. textures.updateRenderTargetMipmap( _currentRenderTarget );
  15645. }
  15646. //
  15647. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  15648. // Ensure depth buffer writing is enabled so it can be cleared on next render
  15649. state.buffers.depth.setTest( true );
  15650. state.buffers.depth.setMask( true );
  15651. state.buffers.color.setMask( true );
  15652. state.setPolygonOffset( false );
  15653. // _gl.finish();
  15654. bindingStates.resetDefaultState();
  15655. _currentMaterialId = - 1;
  15656. _currentCamera = null;
  15657. renderStateStack.pop();
  15658. if ( renderStateStack.length > 0 ) {
  15659. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  15660. } else {
  15661. currentRenderState = null;
  15662. }
  15663. renderListStack.pop();
  15664. if ( renderListStack.length > 0 ) {
  15665. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  15666. } else {
  15667. currentRenderList = null;
  15668. }
  15669. };
  15670. function projectObject( object, camera, groupOrder, sortObjects ) {
  15671. if ( object.visible === false ) return;
  15672. const visible = object.layers.test( camera.layers );
  15673. if ( visible ) {
  15674. if ( object.isGroup ) {
  15675. groupOrder = object.renderOrder;
  15676. } else if ( object.isLOD ) {
  15677. if ( object.autoUpdate === true ) object.update( camera );
  15678. } else if ( object.isLight ) {
  15679. currentRenderState.pushLight( object );
  15680. if ( object.castShadow ) {
  15681. currentRenderState.pushShadow( object );
  15682. }
  15683. } else if ( object.isSprite ) {
  15684. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  15685. if ( sortObjects ) {
  15686. _vector3.setFromMatrixPosition( object.matrixWorld )
  15687. .applyMatrix4( _projScreenMatrix );
  15688. }
  15689. const geometry = objects.update( object );
  15690. const material = object.material;
  15691. if ( material.visible ) {
  15692. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  15693. }
  15694. }
  15695. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  15696. if ( object.isSkinnedMesh ) {
  15697. // update skeleton only once in a frame
  15698. if ( object.skeleton.frame !== info.render.frame ) {
  15699. object.skeleton.update();
  15700. object.skeleton.frame = info.render.frame;
  15701. }
  15702. }
  15703. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  15704. if ( sortObjects ) {
  15705. _vector3.setFromMatrixPosition( object.matrixWorld )
  15706. .applyMatrix4( _projScreenMatrix );
  15707. }
  15708. const geometry = objects.update( object );
  15709. const material = object.material;
  15710. if ( Array.isArray( material ) ) {
  15711. const groups = geometry.groups;
  15712. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  15713. const group = groups[ i ];
  15714. const groupMaterial = material[ group.materialIndex ];
  15715. if ( groupMaterial && groupMaterial.visible ) {
  15716. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  15717. }
  15718. }
  15719. } else if ( material.visible ) {
  15720. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  15721. }
  15722. }
  15723. }
  15724. }
  15725. const children = object.children;
  15726. for ( let i = 0, l = children.length; i < l; i ++ ) {
  15727. projectObject( children[ i ], camera, groupOrder, sortObjects );
  15728. }
  15729. }
  15730. function renderScene( currentRenderList, scene, camera, viewport ) {
  15731. const opaqueObjects = currentRenderList.opaque;
  15732. const transmissiveObjects = currentRenderList.transmissive;
  15733. const transparentObjects = currentRenderList.transparent;
  15734. currentRenderState.setupLightsView( camera );
  15735. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, scene, camera );
  15736. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  15737. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  15738. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  15739. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  15740. }
  15741. function renderTransmissionPass( opaqueObjects, scene, camera ) {
  15742. if ( _transmissionRenderTarget === null ) {
  15743. const needsAntialias = _antialias === true && capabilities.isWebGL2 === true;
  15744. const renderTargetType = needsAntialias ? WebGLMultisampleRenderTarget : WebGLRenderTarget;
  15745. _transmissionRenderTarget = new renderTargetType( 1024, 1024, {
  15746. generateMipmaps: true,
  15747. type: utils.convert( HalfFloatType ) !== null ? HalfFloatType : UnsignedByteType,
  15748. minFilter: LinearMipmapLinearFilter,
  15749. magFilter: NearestFilter,
  15750. wrapS: ClampToEdgeWrapping,
  15751. wrapT: ClampToEdgeWrapping
  15752. } );
  15753. }
  15754. const currentRenderTarget = _this.getRenderTarget();
  15755. _this.setRenderTarget( _transmissionRenderTarget );
  15756. _this.clear();
  15757. // Turn off the features which can affect the frag color for opaque objects pass.
  15758. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  15759. const currentToneMapping = _this.toneMapping;
  15760. _this.toneMapping = NoToneMapping;
  15761. renderObjects( opaqueObjects, scene, camera );
  15762. _this.toneMapping = currentToneMapping;
  15763. textures.updateMultisampleRenderTarget( _transmissionRenderTarget );
  15764. textures.updateRenderTargetMipmap( _transmissionRenderTarget );
  15765. _this.setRenderTarget( currentRenderTarget );
  15766. }
  15767. function renderObjects( renderList, scene, camera ) {
  15768. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  15769. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  15770. const renderItem = renderList[ i ];
  15771. const object = renderItem.object;
  15772. const geometry = renderItem.geometry;
  15773. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  15774. const group = renderItem.group;
  15775. if ( object.layers.test( camera.layers ) ) {
  15776. renderObject( object, scene, camera, geometry, material, group );
  15777. }
  15778. }
  15779. }
  15780. function renderObject( object, scene, camera, geometry, material, group ) {
  15781. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  15782. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  15783. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  15784. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  15785. if ( material.transparent === true && material.side === DoubleSide ) {
  15786. material.side = BackSide;
  15787. material.needsUpdate = true;
  15788. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  15789. material.side = FrontSide;
  15790. material.needsUpdate = true;
  15791. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  15792. material.side = DoubleSide;
  15793. } else {
  15794. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  15795. }
  15796. object.onAfterRender( _this, scene, camera, geometry, material, group );
  15797. }
  15798. function getProgram( material, scene, object ) {
  15799. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  15800. const materialProperties = properties.get( material );
  15801. const lights = currentRenderState.state.lights;
  15802. const shadowsArray = currentRenderState.state.shadowsArray;
  15803. const lightsStateVersion = lights.state.version;
  15804. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  15805. const programCacheKey = programCache.getProgramCacheKey( parameters );
  15806. let programs = materialProperties.programs;
  15807. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  15808. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  15809. materialProperties.fog = scene.fog;
  15810. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  15811. if ( programs === undefined ) {
  15812. // new material
  15813. material.addEventListener( 'dispose', onMaterialDispose );
  15814. programs = new Map();
  15815. materialProperties.programs = programs;
  15816. }
  15817. let program = programs.get( programCacheKey );
  15818. if ( program !== undefined ) {
  15819. // early out if program and light state is identical
  15820. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  15821. updateCommonMaterialProperties( material, parameters );
  15822. return program;
  15823. }
  15824. } else {
  15825. parameters.uniforms = programCache.getUniforms( material );
  15826. material.onBuild( object, parameters, _this );
  15827. material.onBeforeCompile( parameters, _this );
  15828. program = programCache.acquireProgram( parameters, programCacheKey );
  15829. programs.set( programCacheKey, program );
  15830. materialProperties.uniforms = parameters.uniforms;
  15831. }
  15832. const uniforms = materialProperties.uniforms;
  15833. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  15834. uniforms.clippingPlanes = clipping.uniform;
  15835. }
  15836. updateCommonMaterialProperties( material, parameters );
  15837. // store the light setup it was created for
  15838. materialProperties.needsLights = materialNeedsLights( material );
  15839. materialProperties.lightsStateVersion = lightsStateVersion;
  15840. if ( materialProperties.needsLights ) {
  15841. // wire up the material to this renderer's lighting state
  15842. uniforms.ambientLightColor.value = lights.state.ambient;
  15843. uniforms.lightProbe.value = lights.state.probe;
  15844. uniforms.directionalLights.value = lights.state.directional;
  15845. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  15846. uniforms.spotLights.value = lights.state.spot;
  15847. uniforms.spotLightShadows.value = lights.state.spotShadow;
  15848. uniforms.rectAreaLights.value = lights.state.rectArea;
  15849. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  15850. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  15851. uniforms.pointLights.value = lights.state.point;
  15852. uniforms.pointLightShadows.value = lights.state.pointShadow;
  15853. uniforms.hemisphereLights.value = lights.state.hemi;
  15854. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  15855. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  15856. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  15857. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  15858. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  15859. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  15860. // TODO (abelnation): add area lights shadow info to uniforms
  15861. }
  15862. const progUniforms = program.getUniforms();
  15863. const uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  15864. materialProperties.currentProgram = program;
  15865. materialProperties.uniformsList = uniformsList;
  15866. return program;
  15867. }
  15868. function updateCommonMaterialProperties( material, parameters ) {
  15869. const materialProperties = properties.get( material );
  15870. materialProperties.outputEncoding = parameters.outputEncoding;
  15871. materialProperties.instancing = parameters.instancing;
  15872. materialProperties.skinning = parameters.skinning;
  15873. materialProperties.morphTargets = parameters.morphTargets;
  15874. materialProperties.morphNormals = parameters.morphNormals;
  15875. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  15876. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  15877. materialProperties.numIntersection = parameters.numClipIntersection;
  15878. materialProperties.vertexAlphas = parameters.vertexAlphas;
  15879. materialProperties.vertexTangents = parameters.vertexTangents;
  15880. }
  15881. function setProgram( camera, scene, geometry, material, object ) {
  15882. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  15883. textures.resetTextureUnits();
  15884. const fog = scene.fog;
  15885. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  15886. const encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : _currentRenderTarget.texture.encoding;
  15887. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  15888. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  15889. const vertexTangents = !! material.normalMap && !! geometry.attributes.tangent;
  15890. const morphTargets = !! geometry.morphAttributes.position;
  15891. const morphNormals = !! geometry.morphAttributes.normal;
  15892. const morphTargetsCount = !! geometry.morphAttributes.position ? geometry.morphAttributes.position.length : 0;
  15893. const materialProperties = properties.get( material );
  15894. const lights = currentRenderState.state.lights;
  15895. if ( _clippingEnabled === true ) {
  15896. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  15897. const useCache =
  15898. camera === _currentCamera &&
  15899. material.id === _currentMaterialId;
  15900. // we might want to call this function with some ClippingGroup
  15901. // object instead of the material, once it becomes feasible
  15902. // (#8465, #8379)
  15903. clipping.setState( material, camera, useCache );
  15904. }
  15905. }
  15906. //
  15907. let needsProgramChange = false;
  15908. if ( material.version === materialProperties.__version ) {
  15909. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  15910. needsProgramChange = true;
  15911. } else if ( materialProperties.outputEncoding !== encoding ) {
  15912. needsProgramChange = true;
  15913. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  15914. needsProgramChange = true;
  15915. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  15916. needsProgramChange = true;
  15917. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  15918. needsProgramChange = true;
  15919. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  15920. needsProgramChange = true;
  15921. } else if ( materialProperties.envMap !== envMap ) {
  15922. needsProgramChange = true;
  15923. } else if ( material.fog && materialProperties.fog !== fog ) {
  15924. needsProgramChange = true;
  15925. } else if ( materialProperties.numClippingPlanes !== undefined &&
  15926. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  15927. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  15928. needsProgramChange = true;
  15929. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  15930. needsProgramChange = true;
  15931. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  15932. needsProgramChange = true;
  15933. } else if ( materialProperties.morphTargets !== morphTargets ) {
  15934. needsProgramChange = true;
  15935. } else if ( materialProperties.morphNormals !== morphNormals ) {
  15936. needsProgramChange = true;
  15937. } else if ( capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount ) {
  15938. needsProgramChange = true;
  15939. }
  15940. } else {
  15941. needsProgramChange = true;
  15942. materialProperties.__version = material.version;
  15943. }
  15944. //
  15945. let program = materialProperties.currentProgram;
  15946. if ( needsProgramChange === true ) {
  15947. program = getProgram( material, scene, object );
  15948. }
  15949. let refreshProgram = false;
  15950. let refreshMaterial = false;
  15951. let refreshLights = false;
  15952. const p_uniforms = program.getUniforms(),
  15953. m_uniforms = materialProperties.uniforms;
  15954. if ( state.useProgram( program.program ) ) {
  15955. refreshProgram = true;
  15956. refreshMaterial = true;
  15957. refreshLights = true;
  15958. }
  15959. if ( material.id !== _currentMaterialId ) {
  15960. _currentMaterialId = material.id;
  15961. refreshMaterial = true;
  15962. }
  15963. if ( refreshProgram || _currentCamera !== camera ) {
  15964. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  15965. if ( capabilities.logarithmicDepthBuffer ) {
  15966. p_uniforms.setValue( _gl, 'logDepthBufFC',
  15967. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  15968. }
  15969. if ( _currentCamera !== camera ) {
  15970. _currentCamera = camera;
  15971. // lighting uniforms depend on the camera so enforce an update
  15972. // now, in case this material supports lights - or later, when
  15973. // the next material that does gets activated:
  15974. refreshMaterial = true; // set to true on material change
  15975. refreshLights = true; // remains set until update done
  15976. }
  15977. // load material specific uniforms
  15978. // (shader material also gets them for the sake of genericity)
  15979. if ( material.isShaderMaterial ||
  15980. material.isMeshPhongMaterial ||
  15981. material.isMeshToonMaterial ||
  15982. material.isMeshStandardMaterial ||
  15983. material.envMap ) {
  15984. const uCamPos = p_uniforms.map.cameraPosition;
  15985. if ( uCamPos !== undefined ) {
  15986. uCamPos.setValue( _gl,
  15987. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  15988. }
  15989. }
  15990. if ( material.isMeshPhongMaterial ||
  15991. material.isMeshToonMaterial ||
  15992. material.isMeshLambertMaterial ||
  15993. material.isMeshBasicMaterial ||
  15994. material.isMeshStandardMaterial ||
  15995. material.isShaderMaterial ) {
  15996. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  15997. }
  15998. if ( material.isMeshPhongMaterial ||
  15999. material.isMeshToonMaterial ||
  16000. material.isMeshLambertMaterial ||
  16001. material.isMeshBasicMaterial ||
  16002. material.isMeshStandardMaterial ||
  16003. material.isShaderMaterial ||
  16004. material.isShadowMaterial ||
  16005. object.isSkinnedMesh ) {
  16006. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  16007. }
  16008. }
  16009. // skinning and morph target uniforms must be set even if material didn't change
  16010. // auto-setting of texture unit for bone and morph texture must go before other textures
  16011. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  16012. if ( object.isSkinnedMesh ) {
  16013. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  16014. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  16015. const skeleton = object.skeleton;
  16016. if ( skeleton ) {
  16017. if ( capabilities.floatVertexTextures ) {
  16018. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  16019. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  16020. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  16021. } else {
  16022. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  16023. }
  16024. }
  16025. }
  16026. if ( !! geometry && ( geometry.morphAttributes.position !== undefined || geometry.morphAttributes.normal !== undefined ) ) {
  16027. morphtargets.update( object, geometry, material, program );
  16028. }
  16029. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  16030. materialProperties.receiveShadow = object.receiveShadow;
  16031. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  16032. }
  16033. if ( refreshMaterial ) {
  16034. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  16035. if ( materialProperties.needsLights ) {
  16036. // the current material requires lighting info
  16037. // note: all lighting uniforms are always set correctly
  16038. // they simply reference the renderer's state for their
  16039. // values
  16040. //
  16041. // use the current material's .needsUpdate flags to set
  16042. // the GL state when required
  16043. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  16044. }
  16045. // refresh uniforms common to several materials
  16046. if ( fog && material.fog ) {
  16047. materials.refreshFogUniforms( m_uniforms, fog );
  16048. }
  16049. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget );
  16050. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  16051. }
  16052. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  16053. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  16054. material.uniformsNeedUpdate = false;
  16055. }
  16056. if ( material.isSpriteMaterial ) {
  16057. p_uniforms.setValue( _gl, 'center', object.center );
  16058. }
  16059. // common matrices
  16060. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  16061. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  16062. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  16063. return program;
  16064. }
  16065. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  16066. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  16067. uniforms.ambientLightColor.needsUpdate = value;
  16068. uniforms.lightProbe.needsUpdate = value;
  16069. uniforms.directionalLights.needsUpdate = value;
  16070. uniforms.directionalLightShadows.needsUpdate = value;
  16071. uniforms.pointLights.needsUpdate = value;
  16072. uniforms.pointLightShadows.needsUpdate = value;
  16073. uniforms.spotLights.needsUpdate = value;
  16074. uniforms.spotLightShadows.needsUpdate = value;
  16075. uniforms.rectAreaLights.needsUpdate = value;
  16076. uniforms.hemisphereLights.needsUpdate = value;
  16077. }
  16078. function materialNeedsLights( material ) {
  16079. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  16080. material.isMeshStandardMaterial || material.isShadowMaterial ||
  16081. ( material.isShaderMaterial && material.lights === true );
  16082. }
  16083. this.getActiveCubeFace = function () {
  16084. return _currentActiveCubeFace;
  16085. };
  16086. this.getActiveMipmapLevel = function () {
  16087. return _currentActiveMipmapLevel;
  16088. };
  16089. this.getRenderTarget = function () {
  16090. return _currentRenderTarget;
  16091. };
  16092. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  16093. _currentRenderTarget = renderTarget;
  16094. _currentActiveCubeFace = activeCubeFace;
  16095. _currentActiveMipmapLevel = activeMipmapLevel;
  16096. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  16097. textures.setupRenderTarget( renderTarget );
  16098. }
  16099. let framebuffer = null;
  16100. let isCube = false;
  16101. let isRenderTarget3D = false;
  16102. if ( renderTarget ) {
  16103. const texture = renderTarget.texture;
  16104. if ( texture.isDataTexture3D || texture.isDataTexture2DArray ) {
  16105. isRenderTarget3D = true;
  16106. }
  16107. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  16108. if ( renderTarget.isWebGLCubeRenderTarget ) {
  16109. framebuffer = __webglFramebuffer[ activeCubeFace ];
  16110. isCube = true;
  16111. } else if ( renderTarget.isWebGLMultisampleRenderTarget ) {
  16112. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  16113. } else {
  16114. framebuffer = __webglFramebuffer;
  16115. }
  16116. _currentViewport.copy( renderTarget.viewport );
  16117. _currentScissor.copy( renderTarget.scissor );
  16118. _currentScissorTest = renderTarget.scissorTest;
  16119. } else {
  16120. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  16121. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  16122. _currentScissorTest = _scissorTest;
  16123. }
  16124. const framebufferBound = state.bindFramebuffer( 36160, framebuffer );
  16125. if ( framebufferBound && capabilities.drawBuffers ) {
  16126. let needsUpdate = false;
  16127. if ( renderTarget ) {
  16128. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  16129. const textures = renderTarget.texture;
  16130. if ( _currentDrawBuffers.length !== textures.length || _currentDrawBuffers[ 0 ] !== 36064 ) {
  16131. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  16132. _currentDrawBuffers[ i ] = 36064 + i;
  16133. }
  16134. _currentDrawBuffers.length = textures.length;
  16135. needsUpdate = true;
  16136. }
  16137. } else {
  16138. if ( _currentDrawBuffers.length !== 1 || _currentDrawBuffers[ 0 ] !== 36064 ) {
  16139. _currentDrawBuffers[ 0 ] = 36064;
  16140. _currentDrawBuffers.length = 1;
  16141. needsUpdate = true;
  16142. }
  16143. }
  16144. } else {
  16145. if ( _currentDrawBuffers.length !== 1 || _currentDrawBuffers[ 0 ] !== 1029 ) {
  16146. _currentDrawBuffers[ 0 ] = 1029;
  16147. _currentDrawBuffers.length = 1;
  16148. needsUpdate = true;
  16149. }
  16150. }
  16151. if ( needsUpdate ) {
  16152. if ( capabilities.isWebGL2 ) {
  16153. _gl.drawBuffers( _currentDrawBuffers );
  16154. } else {
  16155. extensions.get( 'WEBGL_draw_buffers' ).drawBuffersWEBGL( _currentDrawBuffers );
  16156. }
  16157. }
  16158. }
  16159. state.viewport( _currentViewport );
  16160. state.scissor( _currentScissor );
  16161. state.setScissorTest( _currentScissorTest );
  16162. if ( isCube ) {
  16163. const textureProperties = properties.get( renderTarget.texture );
  16164. _gl.framebufferTexture2D( 36160, 36064, 34069 + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  16165. } else if ( isRenderTarget3D ) {
  16166. const textureProperties = properties.get( renderTarget.texture );
  16167. const layer = activeCubeFace || 0;
  16168. _gl.framebufferTextureLayer( 36160, 36064, textureProperties.__webglTexture, activeMipmapLevel || 0, layer );
  16169. }
  16170. _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings
  16171. };
  16172. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  16173. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  16174. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  16175. return;
  16176. }
  16177. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  16178. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  16179. framebuffer = framebuffer[ activeCubeFaceIndex ];
  16180. }
  16181. if ( framebuffer ) {
  16182. state.bindFramebuffer( 36160, framebuffer );
  16183. try {
  16184. const texture = renderTarget.texture;
  16185. const textureFormat = texture.format;
  16186. const textureType = texture.type;
  16187. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( 35739 ) ) {
  16188. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  16189. return;
  16190. }
  16191. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || ( capabilities.isWebGL2 && extensions.has( 'EXT_color_buffer_float' ) ) );
  16192. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( 35738 ) && // Edge and Chrome Mac < 52 (#9513)
  16193. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.has( 'OES_texture_float' ) || extensions.has( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  16194. ! halfFloatSupportedByExt ) {
  16195. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  16196. return;
  16197. }
  16198. if ( _gl.checkFramebufferStatus( 36160 ) === 36053 ) {
  16199. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  16200. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  16201. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  16202. }
  16203. } else {
  16204. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  16205. }
  16206. } finally {
  16207. // restore framebuffer of current render target if necessary
  16208. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  16209. state.bindFramebuffer( 36160, framebuffer );
  16210. }
  16211. }
  16212. };
  16213. this.copyFramebufferToTexture = function ( position, texture, level = 0 ) {
  16214. const levelScale = Math.pow( 2, - level );
  16215. const width = Math.floor( texture.image.width * levelScale );
  16216. const height = Math.floor( texture.image.height * levelScale );
  16217. let glFormat = utils.convert( texture.format );
  16218. if ( capabilities.isWebGL2 ) {
  16219. // Workaround for https://bugs.chromium.org/p/chromium/issues/detail?id=1120100
  16220. // Not needed in Chrome 93+
  16221. if ( glFormat === 6407 ) glFormat = 32849;
  16222. if ( glFormat === 6408 ) glFormat = 32856;
  16223. }
  16224. textures.setTexture2D( texture, 0 );
  16225. _gl.copyTexImage2D( 3553, level, glFormat, position.x, position.y, width, height, 0 );
  16226. state.unbindTexture();
  16227. };
  16228. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) {
  16229. const width = srcTexture.image.width;
  16230. const height = srcTexture.image.height;
  16231. const glFormat = utils.convert( dstTexture.format );
  16232. const glType = utils.convert( dstTexture.type );
  16233. textures.setTexture2D( dstTexture, 0 );
  16234. // As another texture upload may have changed pixelStorei
  16235. // parameters, make sure they are correct for the dstTexture
  16236. _gl.pixelStorei( 37440, dstTexture.flipY );
  16237. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  16238. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  16239. if ( srcTexture.isDataTexture ) {
  16240. _gl.texSubImage2D( 3553, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  16241. } else {
  16242. if ( srcTexture.isCompressedTexture ) {
  16243. _gl.compressedTexSubImage2D( 3553, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data );
  16244. } else {
  16245. _gl.texSubImage2D( 3553, level, position.x, position.y, glFormat, glType, srcTexture.image );
  16246. }
  16247. }
  16248. // Generate mipmaps only when copying level 0
  16249. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( 3553 );
  16250. state.unbindTexture();
  16251. };
  16252. this.copyTextureToTexture3D = function ( sourceBox, position, srcTexture, dstTexture, level = 0 ) {
  16253. if ( _this.isWebGL1Renderer ) {
  16254. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.' );
  16255. return;
  16256. }
  16257. const width = sourceBox.max.x - sourceBox.min.x + 1;
  16258. const height = sourceBox.max.y - sourceBox.min.y + 1;
  16259. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  16260. const glFormat = utils.convert( dstTexture.format );
  16261. const glType = utils.convert( dstTexture.type );
  16262. let glTarget;
  16263. if ( dstTexture.isDataTexture3D ) {
  16264. textures.setTexture3D( dstTexture, 0 );
  16265. glTarget = 32879;
  16266. } else if ( dstTexture.isDataTexture2DArray ) {
  16267. textures.setTexture2DArray( dstTexture, 0 );
  16268. glTarget = 35866;
  16269. } else {
  16270. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' );
  16271. return;
  16272. }
  16273. _gl.pixelStorei( 37440, dstTexture.flipY );
  16274. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  16275. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  16276. const unpackRowLen = _gl.getParameter( 3314 );
  16277. const unpackImageHeight = _gl.getParameter( 32878 );
  16278. const unpackSkipPixels = _gl.getParameter( 3316 );
  16279. const unpackSkipRows = _gl.getParameter( 3315 );
  16280. const unpackSkipImages = _gl.getParameter( 32877 );
  16281. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ 0 ] : srcTexture.image;
  16282. _gl.pixelStorei( 3314, image.width );
  16283. _gl.pixelStorei( 32878, image.height );
  16284. _gl.pixelStorei( 3316, sourceBox.min.x );
  16285. _gl.pixelStorei( 3315, sourceBox.min.y );
  16286. _gl.pixelStorei( 32877, sourceBox.min.z );
  16287. if ( srcTexture.isDataTexture || srcTexture.isDataTexture3D ) {
  16288. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data );
  16289. } else {
  16290. if ( srcTexture.isCompressedTexture ) {
  16291. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.' );
  16292. _gl.compressedTexSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data );
  16293. } else {
  16294. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image );
  16295. }
  16296. }
  16297. _gl.pixelStorei( 3314, unpackRowLen );
  16298. _gl.pixelStorei( 32878, unpackImageHeight );
  16299. _gl.pixelStorei( 3316, unpackSkipPixels );
  16300. _gl.pixelStorei( 3315, unpackSkipRows );
  16301. _gl.pixelStorei( 32877, unpackSkipImages );
  16302. // Generate mipmaps only when copying level 0
  16303. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget );
  16304. state.unbindTexture();
  16305. };
  16306. this.initTexture = function ( texture ) {
  16307. textures.setTexture2D( texture, 0 );
  16308. state.unbindTexture();
  16309. };
  16310. this.resetState = function () {
  16311. _currentActiveCubeFace = 0;
  16312. _currentActiveMipmapLevel = 0;
  16313. _currentRenderTarget = null;
  16314. state.reset();
  16315. bindingStates.reset();
  16316. };
  16317. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  16318. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef
  16319. }
  16320. }
  16321. WebGLRenderer.prototype.isWebGLRenderer = true;
  16322. class WebGL1Renderer extends WebGLRenderer {}
  16323. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  16324. class FogExp2 {
  16325. constructor( color, density = 0.00025 ) {
  16326. this.name = '';
  16327. this.color = new Color( color );
  16328. this.density = density;
  16329. }
  16330. clone() {
  16331. return new FogExp2( this.color, this.density );
  16332. }
  16333. toJSON( /* meta */ ) {
  16334. return {
  16335. type: 'FogExp2',
  16336. color: this.color.getHex(),
  16337. density: this.density
  16338. };
  16339. }
  16340. }
  16341. FogExp2.prototype.isFogExp2 = true;
  16342. class Fog {
  16343. constructor( color, near = 1, far = 1000 ) {
  16344. this.name = '';
  16345. this.color = new Color( color );
  16346. this.near = near;
  16347. this.far = far;
  16348. }
  16349. clone() {
  16350. return new Fog( this.color, this.near, this.far );
  16351. }
  16352. toJSON( /* meta */ ) {
  16353. return {
  16354. type: 'Fog',
  16355. color: this.color.getHex(),
  16356. near: this.near,
  16357. far: this.far
  16358. };
  16359. }
  16360. }
  16361. Fog.prototype.isFog = true;
  16362. class Scene extends Object3D {
  16363. constructor() {
  16364. super();
  16365. this.type = 'Scene';
  16366. this.background = null;
  16367. this.environment = null;
  16368. this.fog = null;
  16369. this.overrideMaterial = null;
  16370. this.autoUpdate = true; // checked by the renderer
  16371. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  16372. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef
  16373. }
  16374. }
  16375. copy( source, recursive ) {
  16376. super.copy( source, recursive );
  16377. if ( source.background !== null ) this.background = source.background.clone();
  16378. if ( source.environment !== null ) this.environment = source.environment.clone();
  16379. if ( source.fog !== null ) this.fog = source.fog.clone();
  16380. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  16381. this.autoUpdate = source.autoUpdate;
  16382. this.matrixAutoUpdate = source.matrixAutoUpdate;
  16383. return this;
  16384. }
  16385. toJSON( meta ) {
  16386. const data = super.toJSON( meta );
  16387. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  16388. return data;
  16389. }
  16390. }
  16391. Scene.prototype.isScene = true;
  16392. class InterleavedBuffer {
  16393. constructor( array, stride ) {
  16394. this.array = array;
  16395. this.stride = stride;
  16396. this.count = array !== undefined ? array.length / stride : 0;
  16397. this.usage = StaticDrawUsage;
  16398. this.updateRange = { offset: 0, count: - 1 };
  16399. this.version = 0;
  16400. this.uuid = generateUUID();
  16401. }
  16402. onUploadCallback() {}
  16403. set needsUpdate( value ) {
  16404. if ( value === true ) this.version ++;
  16405. }
  16406. setUsage( value ) {
  16407. this.usage = value;
  16408. return this;
  16409. }
  16410. copy( source ) {
  16411. this.array = new source.array.constructor( source.array );
  16412. this.count = source.count;
  16413. this.stride = source.stride;
  16414. this.usage = source.usage;
  16415. return this;
  16416. }
  16417. copyAt( index1, attribute, index2 ) {
  16418. index1 *= this.stride;
  16419. index2 *= attribute.stride;
  16420. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  16421. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  16422. }
  16423. return this;
  16424. }
  16425. set( value, offset = 0 ) {
  16426. this.array.set( value, offset );
  16427. return this;
  16428. }
  16429. clone( data ) {
  16430. if ( data.arrayBuffers === undefined ) {
  16431. data.arrayBuffers = {};
  16432. }
  16433. if ( this.array.buffer._uuid === undefined ) {
  16434. this.array.buffer._uuid = generateUUID();
  16435. }
  16436. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  16437. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  16438. }
  16439. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  16440. const ib = new this.constructor( array, this.stride );
  16441. ib.setUsage( this.usage );
  16442. return ib;
  16443. }
  16444. onUpload( callback ) {
  16445. this.onUploadCallback = callback;
  16446. return this;
  16447. }
  16448. toJSON( data ) {
  16449. if ( data.arrayBuffers === undefined ) {
  16450. data.arrayBuffers = {};
  16451. }
  16452. // generate UUID for array buffer if necessary
  16453. if ( this.array.buffer._uuid === undefined ) {
  16454. this.array.buffer._uuid = generateUUID();
  16455. }
  16456. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  16457. data.arrayBuffers[ this.array.buffer._uuid ] = Array.prototype.slice.call( new Uint32Array( this.array.buffer ) );
  16458. }
  16459. //
  16460. return {
  16461. uuid: this.uuid,
  16462. buffer: this.array.buffer._uuid,
  16463. type: this.array.constructor.name,
  16464. stride: this.stride
  16465. };
  16466. }
  16467. }
  16468. InterleavedBuffer.prototype.isInterleavedBuffer = true;
  16469. const _vector$6 = /*@__PURE__*/ new Vector3();
  16470. class InterleavedBufferAttribute {
  16471. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  16472. this.name = '';
  16473. this.data = interleavedBuffer;
  16474. this.itemSize = itemSize;
  16475. this.offset = offset;
  16476. this.normalized = normalized === true;
  16477. }
  16478. get count() {
  16479. return this.data.count;
  16480. }
  16481. get array() {
  16482. return this.data.array;
  16483. }
  16484. set needsUpdate( value ) {
  16485. this.data.needsUpdate = value;
  16486. }
  16487. applyMatrix4( m ) {
  16488. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  16489. _vector$6.x = this.getX( i );
  16490. _vector$6.y = this.getY( i );
  16491. _vector$6.z = this.getZ( i );
  16492. _vector$6.applyMatrix4( m );
  16493. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  16494. }
  16495. return this;
  16496. }
  16497. applyNormalMatrix( m ) {
  16498. for ( let i = 0, l = this.count; i < l; i ++ ) {
  16499. _vector$6.x = this.getX( i );
  16500. _vector$6.y = this.getY( i );
  16501. _vector$6.z = this.getZ( i );
  16502. _vector$6.applyNormalMatrix( m );
  16503. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  16504. }
  16505. return this;
  16506. }
  16507. transformDirection( m ) {
  16508. for ( let i = 0, l = this.count; i < l; i ++ ) {
  16509. _vector$6.x = this.getX( i );
  16510. _vector$6.y = this.getY( i );
  16511. _vector$6.z = this.getZ( i );
  16512. _vector$6.transformDirection( m );
  16513. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  16514. }
  16515. return this;
  16516. }
  16517. setX( index, x ) {
  16518. this.data.array[ index * this.data.stride + this.offset ] = x;
  16519. return this;
  16520. }
  16521. setY( index, y ) {
  16522. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  16523. return this;
  16524. }
  16525. setZ( index, z ) {
  16526. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  16527. return this;
  16528. }
  16529. setW( index, w ) {
  16530. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  16531. return this;
  16532. }
  16533. getX( index ) {
  16534. return this.data.array[ index * this.data.stride + this.offset ];
  16535. }
  16536. getY( index ) {
  16537. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  16538. }
  16539. getZ( index ) {
  16540. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  16541. }
  16542. getW( index ) {
  16543. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  16544. }
  16545. setXY( index, x, y ) {
  16546. index = index * this.data.stride + this.offset;
  16547. this.data.array[ index + 0 ] = x;
  16548. this.data.array[ index + 1 ] = y;
  16549. return this;
  16550. }
  16551. setXYZ( index, x, y, z ) {
  16552. index = index * this.data.stride + this.offset;
  16553. this.data.array[ index + 0 ] = x;
  16554. this.data.array[ index + 1 ] = y;
  16555. this.data.array[ index + 2 ] = z;
  16556. return this;
  16557. }
  16558. setXYZW( index, x, y, z, w ) {
  16559. index = index * this.data.stride + this.offset;
  16560. this.data.array[ index + 0 ] = x;
  16561. this.data.array[ index + 1 ] = y;
  16562. this.data.array[ index + 2 ] = z;
  16563. this.data.array[ index + 3 ] = w;
  16564. return this;
  16565. }
  16566. clone( data ) {
  16567. if ( data === undefined ) {
  16568. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.' );
  16569. const array = [];
  16570. for ( let i = 0; i < this.count; i ++ ) {
  16571. const index = i * this.data.stride + this.offset;
  16572. for ( let j = 0; j < this.itemSize; j ++ ) {
  16573. array.push( this.data.array[ index + j ] );
  16574. }
  16575. }
  16576. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  16577. } else {
  16578. if ( data.interleavedBuffers === undefined ) {
  16579. data.interleavedBuffers = {};
  16580. }
  16581. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  16582. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  16583. }
  16584. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  16585. }
  16586. }
  16587. toJSON( data ) {
  16588. if ( data === undefined ) {
  16589. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.' );
  16590. const array = [];
  16591. for ( let i = 0; i < this.count; i ++ ) {
  16592. const index = i * this.data.stride + this.offset;
  16593. for ( let j = 0; j < this.itemSize; j ++ ) {
  16594. array.push( this.data.array[ index + j ] );
  16595. }
  16596. }
  16597. // deinterleave data and save it as an ordinary buffer attribute for now
  16598. return {
  16599. itemSize: this.itemSize,
  16600. type: this.array.constructor.name,
  16601. array: array,
  16602. normalized: this.normalized
  16603. };
  16604. } else {
  16605. // save as true interlaved attribtue
  16606. if ( data.interleavedBuffers === undefined ) {
  16607. data.interleavedBuffers = {};
  16608. }
  16609. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  16610. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  16611. }
  16612. return {
  16613. isInterleavedBufferAttribute: true,
  16614. itemSize: this.itemSize,
  16615. data: this.data.uuid,
  16616. offset: this.offset,
  16617. normalized: this.normalized
  16618. };
  16619. }
  16620. }
  16621. }
  16622. InterleavedBufferAttribute.prototype.isInterleavedBufferAttribute = true;
  16623. /**
  16624. * parameters = {
  16625. * color: <hex>,
  16626. * map: new THREE.Texture( <Image> ),
  16627. * alphaMap: new THREE.Texture( <Image> ),
  16628. * rotation: <float>,
  16629. * sizeAttenuation: <bool>
  16630. * }
  16631. */
  16632. class SpriteMaterial extends Material {
  16633. constructor( parameters ) {
  16634. super();
  16635. this.type = 'SpriteMaterial';
  16636. this.color = new Color( 0xffffff );
  16637. this.map = null;
  16638. this.alphaMap = null;
  16639. this.rotation = 0;
  16640. this.sizeAttenuation = true;
  16641. this.transparent = true;
  16642. this.setValues( parameters );
  16643. }
  16644. copy( source ) {
  16645. super.copy( source );
  16646. this.color.copy( source.color );
  16647. this.map = source.map;
  16648. this.alphaMap = source.alphaMap;
  16649. this.rotation = source.rotation;
  16650. this.sizeAttenuation = source.sizeAttenuation;
  16651. return this;
  16652. }
  16653. }
  16654. SpriteMaterial.prototype.isSpriteMaterial = true;
  16655. let _geometry;
  16656. const _intersectPoint = /*@__PURE__*/ new Vector3();
  16657. const _worldScale = /*@__PURE__*/ new Vector3();
  16658. const _mvPosition = /*@__PURE__*/ new Vector3();
  16659. const _alignedPosition = /*@__PURE__*/ new Vector2();
  16660. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  16661. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  16662. const _vA = /*@__PURE__*/ new Vector3();
  16663. const _vB = /*@__PURE__*/ new Vector3();
  16664. const _vC = /*@__PURE__*/ new Vector3();
  16665. const _uvA = /*@__PURE__*/ new Vector2();
  16666. const _uvB = /*@__PURE__*/ new Vector2();
  16667. const _uvC = /*@__PURE__*/ new Vector2();
  16668. class Sprite extends Object3D {
  16669. constructor( material ) {
  16670. super();
  16671. this.type = 'Sprite';
  16672. if ( _geometry === undefined ) {
  16673. _geometry = new BufferGeometry();
  16674. const float32Array = new Float32Array( [
  16675. - 0.5, - 0.5, 0, 0, 0,
  16676. 0.5, - 0.5, 0, 1, 0,
  16677. 0.5, 0.5, 0, 1, 1,
  16678. - 0.5, 0.5, 0, 0, 1
  16679. ] );
  16680. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  16681. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  16682. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  16683. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  16684. }
  16685. this.geometry = _geometry;
  16686. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  16687. this.center = new Vector2( 0.5, 0.5 );
  16688. }
  16689. raycast( raycaster, intersects ) {
  16690. if ( raycaster.camera === null ) {
  16691. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  16692. }
  16693. _worldScale.setFromMatrixScale( this.matrixWorld );
  16694. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  16695. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  16696. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  16697. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  16698. _worldScale.multiplyScalar( - _mvPosition.z );
  16699. }
  16700. const rotation = this.material.rotation;
  16701. let sin, cos;
  16702. if ( rotation !== 0 ) {
  16703. cos = Math.cos( rotation );
  16704. sin = Math.sin( rotation );
  16705. }
  16706. const center = this.center;
  16707. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16708. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16709. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16710. _uvA.set( 0, 0 );
  16711. _uvB.set( 1, 0 );
  16712. _uvC.set( 1, 1 );
  16713. // check first triangle
  16714. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  16715. if ( intersect === null ) {
  16716. // check second triangle
  16717. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16718. _uvB.set( 0, 1 );
  16719. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  16720. if ( intersect === null ) {
  16721. return;
  16722. }
  16723. }
  16724. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  16725. if ( distance < raycaster.near || distance > raycaster.far ) return;
  16726. intersects.push( {
  16727. distance: distance,
  16728. point: _intersectPoint.clone(),
  16729. uv: Triangle.getUV( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  16730. face: null,
  16731. object: this
  16732. } );
  16733. }
  16734. copy( source ) {
  16735. super.copy( source );
  16736. if ( source.center !== undefined ) this.center.copy( source.center );
  16737. this.material = source.material;
  16738. return this;
  16739. }
  16740. }
  16741. Sprite.prototype.isSprite = true;
  16742. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  16743. // compute position in camera space
  16744. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  16745. // to check if rotation is not zero
  16746. if ( sin !== undefined ) {
  16747. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  16748. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  16749. } else {
  16750. _rotatedPosition.copy( _alignedPosition );
  16751. }
  16752. vertexPosition.copy( mvPosition );
  16753. vertexPosition.x += _rotatedPosition.x;
  16754. vertexPosition.y += _rotatedPosition.y;
  16755. // transform to world space
  16756. vertexPosition.applyMatrix4( _viewWorldMatrix );
  16757. }
  16758. const _v1$2 = /*@__PURE__*/ new Vector3();
  16759. const _v2$1 = /*@__PURE__*/ new Vector3();
  16760. class LOD extends Object3D {
  16761. constructor() {
  16762. super();
  16763. this._currentLevel = 0;
  16764. this.type = 'LOD';
  16765. Object.defineProperties( this, {
  16766. levels: {
  16767. enumerable: true,
  16768. value: []
  16769. },
  16770. isLOD: {
  16771. value: true,
  16772. }
  16773. } );
  16774. this.autoUpdate = true;
  16775. }
  16776. copy( source ) {
  16777. super.copy( source, false );
  16778. const levels = source.levels;
  16779. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  16780. const level = levels[ i ];
  16781. this.addLevel( level.object.clone(), level.distance );
  16782. }
  16783. this.autoUpdate = source.autoUpdate;
  16784. return this;
  16785. }
  16786. addLevel( object, distance = 0 ) {
  16787. distance = Math.abs( distance );
  16788. const levels = this.levels;
  16789. let l;
  16790. for ( l = 0; l < levels.length; l ++ ) {
  16791. if ( distance < levels[ l ].distance ) {
  16792. break;
  16793. }
  16794. }
  16795. levels.splice( l, 0, { distance: distance, object: object } );
  16796. this.add( object );
  16797. return this;
  16798. }
  16799. getCurrentLevel() {
  16800. return this._currentLevel;
  16801. }
  16802. getObjectForDistance( distance ) {
  16803. const levels = this.levels;
  16804. if ( levels.length > 0 ) {
  16805. let i, l;
  16806. for ( i = 1, l = levels.length; i < l; i ++ ) {
  16807. if ( distance < levels[ i ].distance ) {
  16808. break;
  16809. }
  16810. }
  16811. return levels[ i - 1 ].object;
  16812. }
  16813. return null;
  16814. }
  16815. raycast( raycaster, intersects ) {
  16816. const levels = this.levels;
  16817. if ( levels.length > 0 ) {
  16818. _v1$2.setFromMatrixPosition( this.matrixWorld );
  16819. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  16820. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  16821. }
  16822. }
  16823. update( camera ) {
  16824. const levels = this.levels;
  16825. if ( levels.length > 1 ) {
  16826. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  16827. _v2$1.setFromMatrixPosition( this.matrixWorld );
  16828. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  16829. levels[ 0 ].object.visible = true;
  16830. let i, l;
  16831. for ( i = 1, l = levels.length; i < l; i ++ ) {
  16832. if ( distance >= levels[ i ].distance ) {
  16833. levels[ i - 1 ].object.visible = false;
  16834. levels[ i ].object.visible = true;
  16835. } else {
  16836. break;
  16837. }
  16838. }
  16839. this._currentLevel = i - 1;
  16840. for ( ; i < l; i ++ ) {
  16841. levels[ i ].object.visible = false;
  16842. }
  16843. }
  16844. }
  16845. toJSON( meta ) {
  16846. const data = super.toJSON( meta );
  16847. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  16848. data.object.levels = [];
  16849. const levels = this.levels;
  16850. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  16851. const level = levels[ i ];
  16852. data.object.levels.push( {
  16853. object: level.object.uuid,
  16854. distance: level.distance
  16855. } );
  16856. }
  16857. return data;
  16858. }
  16859. }
  16860. const _basePosition = /*@__PURE__*/ new Vector3();
  16861. const _skinIndex = /*@__PURE__*/ new Vector4();
  16862. const _skinWeight = /*@__PURE__*/ new Vector4();
  16863. const _vector$5 = /*@__PURE__*/ new Vector3();
  16864. const _matrix = /*@__PURE__*/ new Matrix4();
  16865. class SkinnedMesh extends Mesh {
  16866. constructor( geometry, material ) {
  16867. super( geometry, material );
  16868. this.type = 'SkinnedMesh';
  16869. this.bindMode = 'attached';
  16870. this.bindMatrix = new Matrix4();
  16871. this.bindMatrixInverse = new Matrix4();
  16872. }
  16873. copy( source ) {
  16874. super.copy( source );
  16875. this.bindMode = source.bindMode;
  16876. this.bindMatrix.copy( source.bindMatrix );
  16877. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  16878. this.skeleton = source.skeleton;
  16879. return this;
  16880. }
  16881. bind( skeleton, bindMatrix ) {
  16882. this.skeleton = skeleton;
  16883. if ( bindMatrix === undefined ) {
  16884. this.updateMatrixWorld( true );
  16885. this.skeleton.calculateInverses();
  16886. bindMatrix = this.matrixWorld;
  16887. }
  16888. this.bindMatrix.copy( bindMatrix );
  16889. this.bindMatrixInverse.copy( bindMatrix ).invert();
  16890. }
  16891. pose() {
  16892. this.skeleton.pose();
  16893. }
  16894. normalizeSkinWeights() {
  16895. const vector = new Vector4();
  16896. const skinWeight = this.geometry.attributes.skinWeight;
  16897. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  16898. vector.x = skinWeight.getX( i );
  16899. vector.y = skinWeight.getY( i );
  16900. vector.z = skinWeight.getZ( i );
  16901. vector.w = skinWeight.getW( i );
  16902. const scale = 1.0 / vector.manhattanLength();
  16903. if ( scale !== Infinity ) {
  16904. vector.multiplyScalar( scale );
  16905. } else {
  16906. vector.set( 1, 0, 0, 0 ); // do something reasonable
  16907. }
  16908. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  16909. }
  16910. }
  16911. updateMatrixWorld( force ) {
  16912. super.updateMatrixWorld( force );
  16913. if ( this.bindMode === 'attached' ) {
  16914. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  16915. } else if ( this.bindMode === 'detached' ) {
  16916. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  16917. } else {
  16918. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  16919. }
  16920. }
  16921. boneTransform( index, target ) {
  16922. const skeleton = this.skeleton;
  16923. const geometry = this.geometry;
  16924. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  16925. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  16926. _basePosition.copy( target ).applyMatrix4( this.bindMatrix );
  16927. target.set( 0, 0, 0 );
  16928. for ( let i = 0; i < 4; i ++ ) {
  16929. const weight = _skinWeight.getComponent( i );
  16930. if ( weight !== 0 ) {
  16931. const boneIndex = _skinIndex.getComponent( i );
  16932. _matrix.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  16933. target.addScaledVector( _vector$5.copy( _basePosition ).applyMatrix4( _matrix ), weight );
  16934. }
  16935. }
  16936. return target.applyMatrix4( this.bindMatrixInverse );
  16937. }
  16938. }
  16939. SkinnedMesh.prototype.isSkinnedMesh = true;
  16940. class Bone extends Object3D {
  16941. constructor() {
  16942. super();
  16943. this.type = 'Bone';
  16944. }
  16945. }
  16946. Bone.prototype.isBone = true;
  16947. class DataTexture extends Texture {
  16948. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding ) {
  16949. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  16950. this.image = { data: data, width: width, height: height };
  16951. this.magFilter = magFilter;
  16952. this.minFilter = minFilter;
  16953. this.generateMipmaps = false;
  16954. this.flipY = false;
  16955. this.unpackAlignment = 1;
  16956. this.needsUpdate = true;
  16957. }
  16958. }
  16959. DataTexture.prototype.isDataTexture = true;
  16960. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  16961. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  16962. class Skeleton {
  16963. constructor( bones = [], boneInverses = [] ) {
  16964. this.uuid = generateUUID();
  16965. this.bones = bones.slice( 0 );
  16966. this.boneInverses = boneInverses;
  16967. this.boneMatrices = null;
  16968. this.boneTexture = null;
  16969. this.boneTextureSize = 0;
  16970. this.frame = - 1;
  16971. this.init();
  16972. }
  16973. init() {
  16974. const bones = this.bones;
  16975. const boneInverses = this.boneInverses;
  16976. this.boneMatrices = new Float32Array( bones.length * 16 );
  16977. // calculate inverse bone matrices if necessary
  16978. if ( boneInverses.length === 0 ) {
  16979. this.calculateInverses();
  16980. } else {
  16981. // handle special case
  16982. if ( bones.length !== boneInverses.length ) {
  16983. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  16984. this.boneInverses = [];
  16985. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  16986. this.boneInverses.push( new Matrix4() );
  16987. }
  16988. }
  16989. }
  16990. }
  16991. calculateInverses() {
  16992. this.boneInverses.length = 0;
  16993. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  16994. const inverse = new Matrix4();
  16995. if ( this.bones[ i ] ) {
  16996. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  16997. }
  16998. this.boneInverses.push( inverse );
  16999. }
  17000. }
  17001. pose() {
  17002. // recover the bind-time world matrices
  17003. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17004. const bone = this.bones[ i ];
  17005. if ( bone ) {
  17006. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  17007. }
  17008. }
  17009. // compute the local matrices, positions, rotations and scales
  17010. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17011. const bone = this.bones[ i ];
  17012. if ( bone ) {
  17013. if ( bone.parent && bone.parent.isBone ) {
  17014. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  17015. bone.matrix.multiply( bone.matrixWorld );
  17016. } else {
  17017. bone.matrix.copy( bone.matrixWorld );
  17018. }
  17019. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  17020. }
  17021. }
  17022. }
  17023. update() {
  17024. const bones = this.bones;
  17025. const boneInverses = this.boneInverses;
  17026. const boneMatrices = this.boneMatrices;
  17027. const boneTexture = this.boneTexture;
  17028. // flatten bone matrices to array
  17029. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  17030. // compute the offset between the current and the original transform
  17031. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  17032. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  17033. _offsetMatrix.toArray( boneMatrices, i * 16 );
  17034. }
  17035. if ( boneTexture !== null ) {
  17036. boneTexture.needsUpdate = true;
  17037. }
  17038. }
  17039. clone() {
  17040. return new Skeleton( this.bones, this.boneInverses );
  17041. }
  17042. computeBoneTexture() {
  17043. // layout (1 matrix = 4 pixels)
  17044. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  17045. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  17046. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  17047. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  17048. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  17049. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  17050. size = ceilPowerOfTwo( size );
  17051. size = Math.max( size, 4 );
  17052. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  17053. boneMatrices.set( this.boneMatrices ); // copy current values
  17054. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  17055. this.boneMatrices = boneMatrices;
  17056. this.boneTexture = boneTexture;
  17057. this.boneTextureSize = size;
  17058. return this;
  17059. }
  17060. getBoneByName( name ) {
  17061. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17062. const bone = this.bones[ i ];
  17063. if ( bone.name === name ) {
  17064. return bone;
  17065. }
  17066. }
  17067. return undefined;
  17068. }
  17069. dispose( ) {
  17070. if ( this.boneTexture !== null ) {
  17071. this.boneTexture.dispose();
  17072. this.boneTexture = null;
  17073. }
  17074. }
  17075. fromJSON( json, bones ) {
  17076. this.uuid = json.uuid;
  17077. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  17078. const uuid = json.bones[ i ];
  17079. let bone = bones[ uuid ];
  17080. if ( bone === undefined ) {
  17081. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  17082. bone = new Bone();
  17083. }
  17084. this.bones.push( bone );
  17085. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  17086. }
  17087. this.init();
  17088. return this;
  17089. }
  17090. toJSON() {
  17091. const data = {
  17092. metadata: {
  17093. version: 4.5,
  17094. type: 'Skeleton',
  17095. generator: 'Skeleton.toJSON'
  17096. },
  17097. bones: [],
  17098. boneInverses: []
  17099. };
  17100. data.uuid = this.uuid;
  17101. const bones = this.bones;
  17102. const boneInverses = this.boneInverses;
  17103. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  17104. const bone = bones[ i ];
  17105. data.bones.push( bone.uuid );
  17106. const boneInverse = boneInverses[ i ];
  17107. data.boneInverses.push( boneInverse.toArray() );
  17108. }
  17109. return data;
  17110. }
  17111. }
  17112. class InstancedBufferAttribute extends BufferAttribute {
  17113. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  17114. if ( typeof normalized === 'number' ) {
  17115. meshPerAttribute = normalized;
  17116. normalized = false;
  17117. console.error( 'THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.' );
  17118. }
  17119. super( array, itemSize, normalized );
  17120. this.meshPerAttribute = meshPerAttribute;
  17121. }
  17122. copy( source ) {
  17123. super.copy( source );
  17124. this.meshPerAttribute = source.meshPerAttribute;
  17125. return this;
  17126. }
  17127. toJSON() {
  17128. const data = super.toJSON();
  17129. data.meshPerAttribute = this.meshPerAttribute;
  17130. data.isInstancedBufferAttribute = true;
  17131. return data;
  17132. }
  17133. }
  17134. InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true;
  17135. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  17136. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  17137. const _instanceIntersects = [];
  17138. const _mesh = /*@__PURE__*/ new Mesh();
  17139. class InstancedMesh extends Mesh {
  17140. constructor( geometry, material, count ) {
  17141. super( geometry, material );
  17142. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  17143. this.instanceColor = null;
  17144. this.count = count;
  17145. this.frustumCulled = false;
  17146. }
  17147. copy( source ) {
  17148. super.copy( source );
  17149. this.instanceMatrix.copy( source.instanceMatrix );
  17150. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  17151. this.count = source.count;
  17152. return this;
  17153. }
  17154. getColorAt( index, color ) {
  17155. color.fromArray( this.instanceColor.array, index * 3 );
  17156. }
  17157. getMatrixAt( index, matrix ) {
  17158. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  17159. }
  17160. raycast( raycaster, intersects ) {
  17161. const matrixWorld = this.matrixWorld;
  17162. const raycastTimes = this.count;
  17163. _mesh.geometry = this.geometry;
  17164. _mesh.material = this.material;
  17165. if ( _mesh.material === undefined ) return;
  17166. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  17167. // calculate the world matrix for each instance
  17168. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  17169. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  17170. // the mesh represents this single instance
  17171. _mesh.matrixWorld = _instanceWorldMatrix;
  17172. _mesh.raycast( raycaster, _instanceIntersects );
  17173. // process the result of raycast
  17174. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  17175. const intersect = _instanceIntersects[ i ];
  17176. intersect.instanceId = instanceId;
  17177. intersect.object = this;
  17178. intersects.push( intersect );
  17179. }
  17180. _instanceIntersects.length = 0;
  17181. }
  17182. }
  17183. setColorAt( index, color ) {
  17184. if ( this.instanceColor === null ) {
  17185. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ), 3 );
  17186. }
  17187. color.toArray( this.instanceColor.array, index * 3 );
  17188. }
  17189. setMatrixAt( index, matrix ) {
  17190. matrix.toArray( this.instanceMatrix.array, index * 16 );
  17191. }
  17192. updateMorphTargets() {
  17193. }
  17194. dispose() {
  17195. this.dispatchEvent( { type: 'dispose' } );
  17196. }
  17197. }
  17198. InstancedMesh.prototype.isInstancedMesh = true;
  17199. /**
  17200. * parameters = {
  17201. * color: <hex>,
  17202. * opacity: <float>,
  17203. *
  17204. * linewidth: <float>,
  17205. * linecap: "round",
  17206. * linejoin: "round"
  17207. * }
  17208. */
  17209. class LineBasicMaterial extends Material {
  17210. constructor( parameters ) {
  17211. super();
  17212. this.type = 'LineBasicMaterial';
  17213. this.color = new Color( 0xffffff );
  17214. this.linewidth = 1;
  17215. this.linecap = 'round';
  17216. this.linejoin = 'round';
  17217. this.setValues( parameters );
  17218. }
  17219. copy( source ) {
  17220. super.copy( source );
  17221. this.color.copy( source.color );
  17222. this.linewidth = source.linewidth;
  17223. this.linecap = source.linecap;
  17224. this.linejoin = source.linejoin;
  17225. return this;
  17226. }
  17227. }
  17228. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  17229. const _start$1 = /*@__PURE__*/ new Vector3();
  17230. const _end$1 = /*@__PURE__*/ new Vector3();
  17231. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  17232. const _ray$1 = /*@__PURE__*/ new Ray();
  17233. const _sphere$1 = /*@__PURE__*/ new Sphere();
  17234. class Line extends Object3D {
  17235. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  17236. super();
  17237. this.type = 'Line';
  17238. this.geometry = geometry;
  17239. this.material = material;
  17240. this.updateMorphTargets();
  17241. }
  17242. copy( source ) {
  17243. super.copy( source );
  17244. this.material = source.material;
  17245. this.geometry = source.geometry;
  17246. return this;
  17247. }
  17248. computeLineDistances() {
  17249. const geometry = this.geometry;
  17250. if ( geometry.isBufferGeometry ) {
  17251. // we assume non-indexed geometry
  17252. if ( geometry.index === null ) {
  17253. const positionAttribute = geometry.attributes.position;
  17254. const lineDistances = [ 0 ];
  17255. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  17256. _start$1.fromBufferAttribute( positionAttribute, i - 1 );
  17257. _end$1.fromBufferAttribute( positionAttribute, i );
  17258. lineDistances[ i ] = lineDistances[ i - 1 ];
  17259. lineDistances[ i ] += _start$1.distanceTo( _end$1 );
  17260. }
  17261. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  17262. } else {
  17263. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  17264. }
  17265. } else if ( geometry.isGeometry ) {
  17266. console.error( 'THREE.Line.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  17267. }
  17268. return this;
  17269. }
  17270. raycast( raycaster, intersects ) {
  17271. const geometry = this.geometry;
  17272. const matrixWorld = this.matrixWorld;
  17273. const threshold = raycaster.params.Line.threshold;
  17274. const drawRange = geometry.drawRange;
  17275. // Checking boundingSphere distance to ray
  17276. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  17277. _sphere$1.copy( geometry.boundingSphere );
  17278. _sphere$1.applyMatrix4( matrixWorld );
  17279. _sphere$1.radius += threshold;
  17280. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  17281. //
  17282. _inverseMatrix$1.copy( matrixWorld ).invert();
  17283. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  17284. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  17285. const localThresholdSq = localThreshold * localThreshold;
  17286. const vStart = new Vector3();
  17287. const vEnd = new Vector3();
  17288. const interSegment = new Vector3();
  17289. const interRay = new Vector3();
  17290. const step = this.isLineSegments ? 2 : 1;
  17291. if ( geometry.isBufferGeometry ) {
  17292. const index = geometry.index;
  17293. const attributes = geometry.attributes;
  17294. const positionAttribute = attributes.position;
  17295. if ( index !== null ) {
  17296. const start = Math.max( 0, drawRange.start );
  17297. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  17298. for ( let i = start, l = end - 1; i < l; i += step ) {
  17299. const a = index.getX( i );
  17300. const b = index.getX( i + 1 );
  17301. vStart.fromBufferAttribute( positionAttribute, a );
  17302. vEnd.fromBufferAttribute( positionAttribute, b );
  17303. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  17304. if ( distSq > localThresholdSq ) continue;
  17305. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  17306. const distance = raycaster.ray.origin.distanceTo( interRay );
  17307. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  17308. intersects.push( {
  17309. distance: distance,
  17310. // What do we want? intersection point on the ray or on the segment??
  17311. // point: raycaster.ray.at( distance ),
  17312. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  17313. index: i,
  17314. face: null,
  17315. faceIndex: null,
  17316. object: this
  17317. } );
  17318. }
  17319. } else {
  17320. const start = Math.max( 0, drawRange.start );
  17321. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  17322. for ( let i = start, l = end - 1; i < l; i += step ) {
  17323. vStart.fromBufferAttribute( positionAttribute, i );
  17324. vEnd.fromBufferAttribute( positionAttribute, i + 1 );
  17325. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  17326. if ( distSq > localThresholdSq ) continue;
  17327. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  17328. const distance = raycaster.ray.origin.distanceTo( interRay );
  17329. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  17330. intersects.push( {
  17331. distance: distance,
  17332. // What do we want? intersection point on the ray or on the segment??
  17333. // point: raycaster.ray.at( distance ),
  17334. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  17335. index: i,
  17336. face: null,
  17337. faceIndex: null,
  17338. object: this
  17339. } );
  17340. }
  17341. }
  17342. } else if ( geometry.isGeometry ) {
  17343. console.error( 'THREE.Line.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  17344. }
  17345. }
  17346. updateMorphTargets() {
  17347. const geometry = this.geometry;
  17348. if ( geometry.isBufferGeometry ) {
  17349. const morphAttributes = geometry.morphAttributes;
  17350. const keys = Object.keys( morphAttributes );
  17351. if ( keys.length > 0 ) {
  17352. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  17353. if ( morphAttribute !== undefined ) {
  17354. this.morphTargetInfluences = [];
  17355. this.morphTargetDictionary = {};
  17356. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  17357. const name = morphAttribute[ m ].name || String( m );
  17358. this.morphTargetInfluences.push( 0 );
  17359. this.morphTargetDictionary[ name ] = m;
  17360. }
  17361. }
  17362. }
  17363. } else {
  17364. const morphTargets = geometry.morphTargets;
  17365. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  17366. console.error( 'THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' );
  17367. }
  17368. }
  17369. }
  17370. }
  17371. Line.prototype.isLine = true;
  17372. const _start = /*@__PURE__*/ new Vector3();
  17373. const _end = /*@__PURE__*/ new Vector3();
  17374. class LineSegments extends Line {
  17375. constructor( geometry, material ) {
  17376. super( geometry, material );
  17377. this.type = 'LineSegments';
  17378. }
  17379. computeLineDistances() {
  17380. const geometry = this.geometry;
  17381. if ( geometry.isBufferGeometry ) {
  17382. // we assume non-indexed geometry
  17383. if ( geometry.index === null ) {
  17384. const positionAttribute = geometry.attributes.position;
  17385. const lineDistances = [];
  17386. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  17387. _start.fromBufferAttribute( positionAttribute, i );
  17388. _end.fromBufferAttribute( positionAttribute, i + 1 );
  17389. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  17390. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  17391. }
  17392. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  17393. } else {
  17394. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  17395. }
  17396. } else if ( geometry.isGeometry ) {
  17397. console.error( 'THREE.LineSegments.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  17398. }
  17399. return this;
  17400. }
  17401. }
  17402. LineSegments.prototype.isLineSegments = true;
  17403. class LineLoop extends Line {
  17404. constructor( geometry, material ) {
  17405. super( geometry, material );
  17406. this.type = 'LineLoop';
  17407. }
  17408. }
  17409. LineLoop.prototype.isLineLoop = true;
  17410. /**
  17411. * parameters = {
  17412. * color: <hex>,
  17413. * opacity: <float>,
  17414. * map: new THREE.Texture( <Image> ),
  17415. * alphaMap: new THREE.Texture( <Image> ),
  17416. *
  17417. * size: <float>,
  17418. * sizeAttenuation: <bool>
  17419. *
  17420. * }
  17421. */
  17422. class PointsMaterial extends Material {
  17423. constructor( parameters ) {
  17424. super();
  17425. this.type = 'PointsMaterial';
  17426. this.color = new Color( 0xffffff );
  17427. this.map = null;
  17428. this.alphaMap = null;
  17429. this.size = 1;
  17430. this.sizeAttenuation = true;
  17431. this.setValues( parameters );
  17432. }
  17433. copy( source ) {
  17434. super.copy( source );
  17435. this.color.copy( source.color );
  17436. this.map = source.map;
  17437. this.alphaMap = source.alphaMap;
  17438. this.size = source.size;
  17439. this.sizeAttenuation = source.sizeAttenuation;
  17440. return this;
  17441. }
  17442. }
  17443. PointsMaterial.prototype.isPointsMaterial = true;
  17444. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  17445. const _ray = /*@__PURE__*/ new Ray();
  17446. const _sphere = /*@__PURE__*/ new Sphere();
  17447. const _position$2 = /*@__PURE__*/ new Vector3();
  17448. class Points extends Object3D {
  17449. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  17450. super();
  17451. this.type = 'Points';
  17452. this.geometry = geometry;
  17453. this.material = material;
  17454. this.updateMorphTargets();
  17455. }
  17456. copy( source ) {
  17457. super.copy( source );
  17458. this.material = source.material;
  17459. this.geometry = source.geometry;
  17460. return this;
  17461. }
  17462. raycast( raycaster, intersects ) {
  17463. const geometry = this.geometry;
  17464. const matrixWorld = this.matrixWorld;
  17465. const threshold = raycaster.params.Points.threshold;
  17466. const drawRange = geometry.drawRange;
  17467. // Checking boundingSphere distance to ray
  17468. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  17469. _sphere.copy( geometry.boundingSphere );
  17470. _sphere.applyMatrix4( matrixWorld );
  17471. _sphere.radius += threshold;
  17472. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  17473. //
  17474. _inverseMatrix.copy( matrixWorld ).invert();
  17475. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  17476. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  17477. const localThresholdSq = localThreshold * localThreshold;
  17478. if ( geometry.isBufferGeometry ) {
  17479. const index = geometry.index;
  17480. const attributes = geometry.attributes;
  17481. const positionAttribute = attributes.position;
  17482. if ( index !== null ) {
  17483. const start = Math.max( 0, drawRange.start );
  17484. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  17485. for ( let i = start, il = end; i < il; i ++ ) {
  17486. const a = index.getX( i );
  17487. _position$2.fromBufferAttribute( positionAttribute, a );
  17488. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  17489. }
  17490. } else {
  17491. const start = Math.max( 0, drawRange.start );
  17492. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  17493. for ( let i = start, l = end; i < l; i ++ ) {
  17494. _position$2.fromBufferAttribute( positionAttribute, i );
  17495. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  17496. }
  17497. }
  17498. } else {
  17499. console.error( 'THREE.Points.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  17500. }
  17501. }
  17502. updateMorphTargets() {
  17503. const geometry = this.geometry;
  17504. if ( geometry.isBufferGeometry ) {
  17505. const morphAttributes = geometry.morphAttributes;
  17506. const keys = Object.keys( morphAttributes );
  17507. if ( keys.length > 0 ) {
  17508. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  17509. if ( morphAttribute !== undefined ) {
  17510. this.morphTargetInfluences = [];
  17511. this.morphTargetDictionary = {};
  17512. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  17513. const name = morphAttribute[ m ].name || String( m );
  17514. this.morphTargetInfluences.push( 0 );
  17515. this.morphTargetDictionary[ name ] = m;
  17516. }
  17517. }
  17518. }
  17519. } else {
  17520. const morphTargets = geometry.morphTargets;
  17521. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  17522. console.error( 'THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' );
  17523. }
  17524. }
  17525. }
  17526. }
  17527. Points.prototype.isPoints = true;
  17528. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  17529. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  17530. if ( rayPointDistanceSq < localThresholdSq ) {
  17531. const intersectPoint = new Vector3();
  17532. _ray.closestPointToPoint( point, intersectPoint );
  17533. intersectPoint.applyMatrix4( matrixWorld );
  17534. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  17535. if ( distance < raycaster.near || distance > raycaster.far ) return;
  17536. intersects.push( {
  17537. distance: distance,
  17538. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  17539. point: intersectPoint,
  17540. index: index,
  17541. face: null,
  17542. object: object
  17543. } );
  17544. }
  17545. }
  17546. class VideoTexture extends Texture {
  17547. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  17548. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  17549. this.format = format !== undefined ? format : RGBFormat;
  17550. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  17551. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  17552. this.generateMipmaps = false;
  17553. const scope = this;
  17554. function updateVideo() {
  17555. scope.needsUpdate = true;
  17556. video.requestVideoFrameCallback( updateVideo );
  17557. }
  17558. if ( 'requestVideoFrameCallback' in video ) {
  17559. video.requestVideoFrameCallback( updateVideo );
  17560. }
  17561. }
  17562. clone() {
  17563. return new this.constructor( this.image ).copy( this );
  17564. }
  17565. update() {
  17566. const video = this.image;
  17567. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  17568. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  17569. this.needsUpdate = true;
  17570. }
  17571. }
  17572. }
  17573. VideoTexture.prototype.isVideoTexture = true;
  17574. class CompressedTexture extends Texture {
  17575. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  17576. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  17577. this.image = { width: width, height: height };
  17578. this.mipmaps = mipmaps;
  17579. // no flipping for cube textures
  17580. // (also flipping doesn't work for compressed textures )
  17581. this.flipY = false;
  17582. // can't generate mipmaps for compressed textures
  17583. // mips must be embedded in DDS files
  17584. this.generateMipmaps = false;
  17585. }
  17586. }
  17587. CompressedTexture.prototype.isCompressedTexture = true;
  17588. class CanvasTexture extends Texture {
  17589. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  17590. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  17591. this.needsUpdate = true;
  17592. }
  17593. }
  17594. CanvasTexture.prototype.isCanvasTexture = true;
  17595. class DepthTexture extends Texture {
  17596. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  17597. format = format !== undefined ? format : DepthFormat;
  17598. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  17599. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  17600. }
  17601. if ( type === undefined && format === DepthFormat ) type = UnsignedShortType;
  17602. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  17603. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  17604. this.image = { width: width, height: height };
  17605. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  17606. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  17607. this.flipY = false;
  17608. this.generateMipmaps = false;
  17609. }
  17610. }
  17611. DepthTexture.prototype.isDepthTexture = true;
  17612. class CircleGeometry extends BufferGeometry {
  17613. constructor( radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  17614. super();
  17615. this.type = 'CircleGeometry';
  17616. this.parameters = {
  17617. radius: radius,
  17618. segments: segments,
  17619. thetaStart: thetaStart,
  17620. thetaLength: thetaLength
  17621. };
  17622. segments = Math.max( 3, segments );
  17623. // buffers
  17624. const indices = [];
  17625. const vertices = [];
  17626. const normals = [];
  17627. const uvs = [];
  17628. // helper variables
  17629. const vertex = new Vector3();
  17630. const uv = new Vector2();
  17631. // center point
  17632. vertices.push( 0, 0, 0 );
  17633. normals.push( 0, 0, 1 );
  17634. uvs.push( 0.5, 0.5 );
  17635. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  17636. const segment = thetaStart + s / segments * thetaLength;
  17637. // vertex
  17638. vertex.x = radius * Math.cos( segment );
  17639. vertex.y = radius * Math.sin( segment );
  17640. vertices.push( vertex.x, vertex.y, vertex.z );
  17641. // normal
  17642. normals.push( 0, 0, 1 );
  17643. // uvs
  17644. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  17645. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  17646. uvs.push( uv.x, uv.y );
  17647. }
  17648. // indices
  17649. for ( let i = 1; i <= segments; i ++ ) {
  17650. indices.push( i, i + 1, 0 );
  17651. }
  17652. // build geometry
  17653. this.setIndex( indices );
  17654. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  17655. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  17656. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  17657. }
  17658. static fromJSON( data ) {
  17659. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  17660. }
  17661. }
  17662. class CylinderGeometry extends BufferGeometry {
  17663. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  17664. super();
  17665. this.type = 'CylinderGeometry';
  17666. this.parameters = {
  17667. radiusTop: radiusTop,
  17668. radiusBottom: radiusBottom,
  17669. height: height,
  17670. radialSegments: radialSegments,
  17671. heightSegments: heightSegments,
  17672. openEnded: openEnded,
  17673. thetaStart: thetaStart,
  17674. thetaLength: thetaLength
  17675. };
  17676. const scope = this;
  17677. radialSegments = Math.floor( radialSegments );
  17678. heightSegments = Math.floor( heightSegments );
  17679. // buffers
  17680. const indices = [];
  17681. const vertices = [];
  17682. const normals = [];
  17683. const uvs = [];
  17684. // helper variables
  17685. let index = 0;
  17686. const indexArray = [];
  17687. const halfHeight = height / 2;
  17688. let groupStart = 0;
  17689. // generate geometry
  17690. generateTorso();
  17691. if ( openEnded === false ) {
  17692. if ( radiusTop > 0 ) generateCap( true );
  17693. if ( radiusBottom > 0 ) generateCap( false );
  17694. }
  17695. // build geometry
  17696. this.setIndex( indices );
  17697. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  17698. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  17699. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  17700. function generateTorso() {
  17701. const normal = new Vector3();
  17702. const vertex = new Vector3();
  17703. let groupCount = 0;
  17704. // this will be used to calculate the normal
  17705. const slope = ( radiusBottom - radiusTop ) / height;
  17706. // generate vertices, normals and uvs
  17707. for ( let y = 0; y <= heightSegments; y ++ ) {
  17708. const indexRow = [];
  17709. const v = y / heightSegments;
  17710. // calculate the radius of the current row
  17711. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  17712. for ( let x = 0; x <= radialSegments; x ++ ) {
  17713. const u = x / radialSegments;
  17714. const theta = u * thetaLength + thetaStart;
  17715. const sinTheta = Math.sin( theta );
  17716. const cosTheta = Math.cos( theta );
  17717. // vertex
  17718. vertex.x = radius * sinTheta;
  17719. vertex.y = - v * height + halfHeight;
  17720. vertex.z = radius * cosTheta;
  17721. vertices.push( vertex.x, vertex.y, vertex.z );
  17722. // normal
  17723. normal.set( sinTheta, slope, cosTheta ).normalize();
  17724. normals.push( normal.x, normal.y, normal.z );
  17725. // uv
  17726. uvs.push( u, 1 - v );
  17727. // save index of vertex in respective row
  17728. indexRow.push( index ++ );
  17729. }
  17730. // now save vertices of the row in our index array
  17731. indexArray.push( indexRow );
  17732. }
  17733. // generate indices
  17734. for ( let x = 0; x < radialSegments; x ++ ) {
  17735. for ( let y = 0; y < heightSegments; y ++ ) {
  17736. // we use the index array to access the correct indices
  17737. const a = indexArray[ y ][ x ];
  17738. const b = indexArray[ y + 1 ][ x ];
  17739. const c = indexArray[ y + 1 ][ x + 1 ];
  17740. const d = indexArray[ y ][ x + 1 ];
  17741. // faces
  17742. indices.push( a, b, d );
  17743. indices.push( b, c, d );
  17744. // update group counter
  17745. groupCount += 6;
  17746. }
  17747. }
  17748. // add a group to the geometry. this will ensure multi material support
  17749. scope.addGroup( groupStart, groupCount, 0 );
  17750. // calculate new start value for groups
  17751. groupStart += groupCount;
  17752. }
  17753. function generateCap( top ) {
  17754. // save the index of the first center vertex
  17755. const centerIndexStart = index;
  17756. const uv = new Vector2();
  17757. const vertex = new Vector3();
  17758. let groupCount = 0;
  17759. const radius = ( top === true ) ? radiusTop : radiusBottom;
  17760. const sign = ( top === true ) ? 1 : - 1;
  17761. // first we generate the center vertex data of the cap.
  17762. // because the geometry needs one set of uvs per face,
  17763. // we must generate a center vertex per face/segment
  17764. for ( let x = 1; x <= radialSegments; x ++ ) {
  17765. // vertex
  17766. vertices.push( 0, halfHeight * sign, 0 );
  17767. // normal
  17768. normals.push( 0, sign, 0 );
  17769. // uv
  17770. uvs.push( 0.5, 0.5 );
  17771. // increase index
  17772. index ++;
  17773. }
  17774. // save the index of the last center vertex
  17775. const centerIndexEnd = index;
  17776. // now we generate the surrounding vertices, normals and uvs
  17777. for ( let x = 0; x <= radialSegments; x ++ ) {
  17778. const u = x / radialSegments;
  17779. const theta = u * thetaLength + thetaStart;
  17780. const cosTheta = Math.cos( theta );
  17781. const sinTheta = Math.sin( theta );
  17782. // vertex
  17783. vertex.x = radius * sinTheta;
  17784. vertex.y = halfHeight * sign;
  17785. vertex.z = radius * cosTheta;
  17786. vertices.push( vertex.x, vertex.y, vertex.z );
  17787. // normal
  17788. normals.push( 0, sign, 0 );
  17789. // uv
  17790. uv.x = ( cosTheta * 0.5 ) + 0.5;
  17791. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  17792. uvs.push( uv.x, uv.y );
  17793. // increase index
  17794. index ++;
  17795. }
  17796. // generate indices
  17797. for ( let x = 0; x < radialSegments; x ++ ) {
  17798. const c = centerIndexStart + x;
  17799. const i = centerIndexEnd + x;
  17800. if ( top === true ) {
  17801. // face top
  17802. indices.push( i, i + 1, c );
  17803. } else {
  17804. // face bottom
  17805. indices.push( i + 1, i, c );
  17806. }
  17807. groupCount += 3;
  17808. }
  17809. // add a group to the geometry. this will ensure multi material support
  17810. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  17811. // calculate new start value for groups
  17812. groupStart += groupCount;
  17813. }
  17814. }
  17815. static fromJSON( data ) {
  17816. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  17817. }
  17818. }
  17819. class ConeGeometry extends CylinderGeometry {
  17820. constructor( radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  17821. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  17822. this.type = 'ConeGeometry';
  17823. this.parameters = {
  17824. radius: radius,
  17825. height: height,
  17826. radialSegments: radialSegments,
  17827. heightSegments: heightSegments,
  17828. openEnded: openEnded,
  17829. thetaStart: thetaStart,
  17830. thetaLength: thetaLength
  17831. };
  17832. }
  17833. static fromJSON( data ) {
  17834. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  17835. }
  17836. }
  17837. class PolyhedronGeometry extends BufferGeometry {
  17838. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  17839. super();
  17840. this.type = 'PolyhedronGeometry';
  17841. this.parameters = {
  17842. vertices: vertices,
  17843. indices: indices,
  17844. radius: radius,
  17845. detail: detail
  17846. };
  17847. // default buffer data
  17848. const vertexBuffer = [];
  17849. const uvBuffer = [];
  17850. // the subdivision creates the vertex buffer data
  17851. subdivide( detail );
  17852. // all vertices should lie on a conceptual sphere with a given radius
  17853. applyRadius( radius );
  17854. // finally, create the uv data
  17855. generateUVs();
  17856. // build non-indexed geometry
  17857. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  17858. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  17859. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  17860. if ( detail === 0 ) {
  17861. this.computeVertexNormals(); // flat normals
  17862. } else {
  17863. this.normalizeNormals(); // smooth normals
  17864. }
  17865. // helper functions
  17866. function subdivide( detail ) {
  17867. const a = new Vector3();
  17868. const b = new Vector3();
  17869. const c = new Vector3();
  17870. // iterate over all faces and apply a subdivison with the given detail value
  17871. for ( let i = 0; i < indices.length; i += 3 ) {
  17872. // get the vertices of the face
  17873. getVertexByIndex( indices[ i + 0 ], a );
  17874. getVertexByIndex( indices[ i + 1 ], b );
  17875. getVertexByIndex( indices[ i + 2 ], c );
  17876. // perform subdivision
  17877. subdivideFace( a, b, c, detail );
  17878. }
  17879. }
  17880. function subdivideFace( a, b, c, detail ) {
  17881. const cols = detail + 1;
  17882. // we use this multidimensional array as a data structure for creating the subdivision
  17883. const v = [];
  17884. // construct all of the vertices for this subdivision
  17885. for ( let i = 0; i <= cols; i ++ ) {
  17886. v[ i ] = [];
  17887. const aj = a.clone().lerp( c, i / cols );
  17888. const bj = b.clone().lerp( c, i / cols );
  17889. const rows = cols - i;
  17890. for ( let j = 0; j <= rows; j ++ ) {
  17891. if ( j === 0 && i === cols ) {
  17892. v[ i ][ j ] = aj;
  17893. } else {
  17894. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  17895. }
  17896. }
  17897. }
  17898. // construct all of the faces
  17899. for ( let i = 0; i < cols; i ++ ) {
  17900. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  17901. const k = Math.floor( j / 2 );
  17902. if ( j % 2 === 0 ) {
  17903. pushVertex( v[ i ][ k + 1 ] );
  17904. pushVertex( v[ i + 1 ][ k ] );
  17905. pushVertex( v[ i ][ k ] );
  17906. } else {
  17907. pushVertex( v[ i ][ k + 1 ] );
  17908. pushVertex( v[ i + 1 ][ k + 1 ] );
  17909. pushVertex( v[ i + 1 ][ k ] );
  17910. }
  17911. }
  17912. }
  17913. }
  17914. function applyRadius( radius ) {
  17915. const vertex = new Vector3();
  17916. // iterate over the entire buffer and apply the radius to each vertex
  17917. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  17918. vertex.x = vertexBuffer[ i + 0 ];
  17919. vertex.y = vertexBuffer[ i + 1 ];
  17920. vertex.z = vertexBuffer[ i + 2 ];
  17921. vertex.normalize().multiplyScalar( radius );
  17922. vertexBuffer[ i + 0 ] = vertex.x;
  17923. vertexBuffer[ i + 1 ] = vertex.y;
  17924. vertexBuffer[ i + 2 ] = vertex.z;
  17925. }
  17926. }
  17927. function generateUVs() {
  17928. const vertex = new Vector3();
  17929. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  17930. vertex.x = vertexBuffer[ i + 0 ];
  17931. vertex.y = vertexBuffer[ i + 1 ];
  17932. vertex.z = vertexBuffer[ i + 2 ];
  17933. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  17934. const v = inclination( vertex ) / Math.PI + 0.5;
  17935. uvBuffer.push( u, 1 - v );
  17936. }
  17937. correctUVs();
  17938. correctSeam();
  17939. }
  17940. function correctSeam() {
  17941. // handle case when face straddles the seam, see #3269
  17942. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  17943. // uv data of a single face
  17944. const x0 = uvBuffer[ i + 0 ];
  17945. const x1 = uvBuffer[ i + 2 ];
  17946. const x2 = uvBuffer[ i + 4 ];
  17947. const max = Math.max( x0, x1, x2 );
  17948. const min = Math.min( x0, x1, x2 );
  17949. // 0.9 is somewhat arbitrary
  17950. if ( max > 0.9 && min < 0.1 ) {
  17951. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  17952. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  17953. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  17954. }
  17955. }
  17956. }
  17957. function pushVertex( vertex ) {
  17958. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  17959. }
  17960. function getVertexByIndex( index, vertex ) {
  17961. const stride = index * 3;
  17962. vertex.x = vertices[ stride + 0 ];
  17963. vertex.y = vertices[ stride + 1 ];
  17964. vertex.z = vertices[ stride + 2 ];
  17965. }
  17966. function correctUVs() {
  17967. const a = new Vector3();
  17968. const b = new Vector3();
  17969. const c = new Vector3();
  17970. const centroid = new Vector3();
  17971. const uvA = new Vector2();
  17972. const uvB = new Vector2();
  17973. const uvC = new Vector2();
  17974. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  17975. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  17976. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  17977. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  17978. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  17979. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  17980. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  17981. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  17982. const azi = azimuth( centroid );
  17983. correctUV( uvA, j + 0, a, azi );
  17984. correctUV( uvB, j + 2, b, azi );
  17985. correctUV( uvC, j + 4, c, azi );
  17986. }
  17987. }
  17988. function correctUV( uv, stride, vector, azimuth ) {
  17989. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  17990. uvBuffer[ stride ] = uv.x - 1;
  17991. }
  17992. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  17993. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  17994. }
  17995. }
  17996. // Angle around the Y axis, counter-clockwise when looking from above.
  17997. function azimuth( vector ) {
  17998. return Math.atan2( vector.z, - vector.x );
  17999. }
  18000. // Angle above the XZ plane.
  18001. function inclination( vector ) {
  18002. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  18003. }
  18004. }
  18005. static fromJSON( data ) {
  18006. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  18007. }
  18008. }
  18009. class DodecahedronGeometry extends PolyhedronGeometry {
  18010. constructor( radius = 1, detail = 0 ) {
  18011. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  18012. const r = 1 / t;
  18013. const vertices = [
  18014. // (±1, ±1, ±1)
  18015. - 1, - 1, - 1, - 1, - 1, 1,
  18016. - 1, 1, - 1, - 1, 1, 1,
  18017. 1, - 1, - 1, 1, - 1, 1,
  18018. 1, 1, - 1, 1, 1, 1,
  18019. // (0, ±1/φ, ±φ)
  18020. 0, - r, - t, 0, - r, t,
  18021. 0, r, - t, 0, r, t,
  18022. // (±1/φ, ±φ, 0)
  18023. - r, - t, 0, - r, t, 0,
  18024. r, - t, 0, r, t, 0,
  18025. // (±φ, 0, ±1/φ)
  18026. - t, 0, - r, t, 0, - r,
  18027. - t, 0, r, t, 0, r
  18028. ];
  18029. const indices = [
  18030. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  18031. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  18032. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  18033. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  18034. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  18035. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  18036. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  18037. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  18038. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  18039. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  18040. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  18041. 1, 12, 14, 1, 14, 5, 1, 5, 9
  18042. ];
  18043. super( vertices, indices, radius, detail );
  18044. this.type = 'DodecahedronGeometry';
  18045. this.parameters = {
  18046. radius: radius,
  18047. detail: detail
  18048. };
  18049. }
  18050. static fromJSON( data ) {
  18051. return new DodecahedronGeometry( data.radius, data.detail );
  18052. }
  18053. }
  18054. const _v0 = new Vector3();
  18055. const _v1$1 = new Vector3();
  18056. const _normal = new Vector3();
  18057. const _triangle = new Triangle();
  18058. class EdgesGeometry extends BufferGeometry {
  18059. constructor( geometry = null, thresholdAngle = 1 ) {
  18060. super();
  18061. this.type = 'EdgesGeometry';
  18062. this.parameters = {
  18063. geometry: geometry,
  18064. thresholdAngle: thresholdAngle
  18065. };
  18066. if ( geometry !== null ) {
  18067. const precisionPoints = 4;
  18068. const precision = Math.pow( 10, precisionPoints );
  18069. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  18070. const indexAttr = geometry.getIndex();
  18071. const positionAttr = geometry.getAttribute( 'position' );
  18072. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  18073. const indexArr = [ 0, 0, 0 ];
  18074. const vertKeys = [ 'a', 'b', 'c' ];
  18075. const hashes = new Array( 3 );
  18076. const edgeData = {};
  18077. const vertices = [];
  18078. for ( let i = 0; i < indexCount; i += 3 ) {
  18079. if ( indexAttr ) {
  18080. indexArr[ 0 ] = indexAttr.getX( i );
  18081. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  18082. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  18083. } else {
  18084. indexArr[ 0 ] = i;
  18085. indexArr[ 1 ] = i + 1;
  18086. indexArr[ 2 ] = i + 2;
  18087. }
  18088. const { a, b, c } = _triangle;
  18089. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  18090. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  18091. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  18092. _triangle.getNormal( _normal );
  18093. // create hashes for the edge from the vertices
  18094. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  18095. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  18096. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  18097. // skip degenerate triangles
  18098. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  18099. continue;
  18100. }
  18101. // iterate over every edge
  18102. for ( let j = 0; j < 3; j ++ ) {
  18103. // get the first and next vertex making up the edge
  18104. const jNext = ( j + 1 ) % 3;
  18105. const vecHash0 = hashes[ j ];
  18106. const vecHash1 = hashes[ jNext ];
  18107. const v0 = _triangle[ vertKeys[ j ] ];
  18108. const v1 = _triangle[ vertKeys[ jNext ] ];
  18109. const hash = `${ vecHash0 }_${ vecHash1 }`;
  18110. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  18111. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  18112. // if we found a sibling edge add it into the vertex array if
  18113. // it meets the angle threshold and delete the edge from the map.
  18114. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  18115. vertices.push( v0.x, v0.y, v0.z );
  18116. vertices.push( v1.x, v1.y, v1.z );
  18117. }
  18118. edgeData[ reverseHash ] = null;
  18119. } else if ( ! ( hash in edgeData ) ) {
  18120. // if we've already got an edge here then skip adding a new one
  18121. edgeData[ hash ] = {
  18122. index0: indexArr[ j ],
  18123. index1: indexArr[ jNext ],
  18124. normal: _normal.clone(),
  18125. };
  18126. }
  18127. }
  18128. }
  18129. // iterate over all remaining, unmatched edges and add them to the vertex array
  18130. for ( const key in edgeData ) {
  18131. if ( edgeData[ key ] ) {
  18132. const { index0, index1 } = edgeData[ key ];
  18133. _v0.fromBufferAttribute( positionAttr, index0 );
  18134. _v1$1.fromBufferAttribute( positionAttr, index1 );
  18135. vertices.push( _v0.x, _v0.y, _v0.z );
  18136. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  18137. }
  18138. }
  18139. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18140. }
  18141. }
  18142. }
  18143. /**
  18144. * Extensible curve object.
  18145. *
  18146. * Some common of curve methods:
  18147. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  18148. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  18149. * .getPoints(), .getSpacedPoints()
  18150. * .getLength()
  18151. * .updateArcLengths()
  18152. *
  18153. * This following curves inherit from THREE.Curve:
  18154. *
  18155. * -- 2D curves --
  18156. * THREE.ArcCurve
  18157. * THREE.CubicBezierCurve
  18158. * THREE.EllipseCurve
  18159. * THREE.LineCurve
  18160. * THREE.QuadraticBezierCurve
  18161. * THREE.SplineCurve
  18162. *
  18163. * -- 3D curves --
  18164. * THREE.CatmullRomCurve3
  18165. * THREE.CubicBezierCurve3
  18166. * THREE.LineCurve3
  18167. * THREE.QuadraticBezierCurve3
  18168. *
  18169. * A series of curves can be represented as a THREE.CurvePath.
  18170. *
  18171. **/
  18172. class Curve {
  18173. constructor() {
  18174. this.type = 'Curve';
  18175. this.arcLengthDivisions = 200;
  18176. }
  18177. // Virtual base class method to overwrite and implement in subclasses
  18178. // - t [0 .. 1]
  18179. getPoint( /* t, optionalTarget */ ) {
  18180. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  18181. return null;
  18182. }
  18183. // Get point at relative position in curve according to arc length
  18184. // - u [0 .. 1]
  18185. getPointAt( u, optionalTarget ) {
  18186. const t = this.getUtoTmapping( u );
  18187. return this.getPoint( t, optionalTarget );
  18188. }
  18189. // Get sequence of points using getPoint( t )
  18190. getPoints( divisions = 5 ) {
  18191. const points = [];
  18192. for ( let d = 0; d <= divisions; d ++ ) {
  18193. points.push( this.getPoint( d / divisions ) );
  18194. }
  18195. return points;
  18196. }
  18197. // Get sequence of points using getPointAt( u )
  18198. getSpacedPoints( divisions = 5 ) {
  18199. const points = [];
  18200. for ( let d = 0; d <= divisions; d ++ ) {
  18201. points.push( this.getPointAt( d / divisions ) );
  18202. }
  18203. return points;
  18204. }
  18205. // Get total curve arc length
  18206. getLength() {
  18207. const lengths = this.getLengths();
  18208. return lengths[ lengths.length - 1 ];
  18209. }
  18210. // Get list of cumulative segment lengths
  18211. getLengths( divisions = this.arcLengthDivisions ) {
  18212. if ( this.cacheArcLengths &&
  18213. ( this.cacheArcLengths.length === divisions + 1 ) &&
  18214. ! this.needsUpdate ) {
  18215. return this.cacheArcLengths;
  18216. }
  18217. this.needsUpdate = false;
  18218. const cache = [];
  18219. let current, last = this.getPoint( 0 );
  18220. let sum = 0;
  18221. cache.push( 0 );
  18222. for ( let p = 1; p <= divisions; p ++ ) {
  18223. current = this.getPoint( p / divisions );
  18224. sum += current.distanceTo( last );
  18225. cache.push( sum );
  18226. last = current;
  18227. }
  18228. this.cacheArcLengths = cache;
  18229. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  18230. }
  18231. updateArcLengths() {
  18232. this.needsUpdate = true;
  18233. this.getLengths();
  18234. }
  18235. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  18236. getUtoTmapping( u, distance ) {
  18237. const arcLengths = this.getLengths();
  18238. let i = 0;
  18239. const il = arcLengths.length;
  18240. let targetArcLength; // The targeted u distance value to get
  18241. if ( distance ) {
  18242. targetArcLength = distance;
  18243. } else {
  18244. targetArcLength = u * arcLengths[ il - 1 ];
  18245. }
  18246. // binary search for the index with largest value smaller than target u distance
  18247. let low = 0, high = il - 1, comparison;
  18248. while ( low <= high ) {
  18249. 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
  18250. comparison = arcLengths[ i ] - targetArcLength;
  18251. if ( comparison < 0 ) {
  18252. low = i + 1;
  18253. } else if ( comparison > 0 ) {
  18254. high = i - 1;
  18255. } else {
  18256. high = i;
  18257. break;
  18258. // DONE
  18259. }
  18260. }
  18261. i = high;
  18262. if ( arcLengths[ i ] === targetArcLength ) {
  18263. return i / ( il - 1 );
  18264. }
  18265. // we could get finer grain at lengths, or use simple interpolation between two points
  18266. const lengthBefore = arcLengths[ i ];
  18267. const lengthAfter = arcLengths[ i + 1 ];
  18268. const segmentLength = lengthAfter - lengthBefore;
  18269. // determine where we are between the 'before' and 'after' points
  18270. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  18271. // add that fractional amount to t
  18272. const t = ( i + segmentFraction ) / ( il - 1 );
  18273. return t;
  18274. }
  18275. // Returns a unit vector tangent at t
  18276. // In case any sub curve does not implement its tangent derivation,
  18277. // 2 points a small delta apart will be used to find its gradient
  18278. // which seems to give a reasonable approximation
  18279. getTangent( t, optionalTarget ) {
  18280. const delta = 0.0001;
  18281. let t1 = t - delta;
  18282. let t2 = t + delta;
  18283. // Capping in case of danger
  18284. if ( t1 < 0 ) t1 = 0;
  18285. if ( t2 > 1 ) t2 = 1;
  18286. const pt1 = this.getPoint( t1 );
  18287. const pt2 = this.getPoint( t2 );
  18288. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  18289. tangent.copy( pt2 ).sub( pt1 ).normalize();
  18290. return tangent;
  18291. }
  18292. getTangentAt( u, optionalTarget ) {
  18293. const t = this.getUtoTmapping( u );
  18294. return this.getTangent( t, optionalTarget );
  18295. }
  18296. computeFrenetFrames( segments, closed ) {
  18297. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  18298. const normal = new Vector3();
  18299. const tangents = [];
  18300. const normals = [];
  18301. const binormals = [];
  18302. const vec = new Vector3();
  18303. const mat = new Matrix4();
  18304. // compute the tangent vectors for each segment on the curve
  18305. for ( let i = 0; i <= segments; i ++ ) {
  18306. const u = i / segments;
  18307. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  18308. }
  18309. // select an initial normal vector perpendicular to the first tangent vector,
  18310. // and in the direction of the minimum tangent xyz component
  18311. normals[ 0 ] = new Vector3();
  18312. binormals[ 0 ] = new Vector3();
  18313. let min = Number.MAX_VALUE;
  18314. const tx = Math.abs( tangents[ 0 ].x );
  18315. const ty = Math.abs( tangents[ 0 ].y );
  18316. const tz = Math.abs( tangents[ 0 ].z );
  18317. if ( tx <= min ) {
  18318. min = tx;
  18319. normal.set( 1, 0, 0 );
  18320. }
  18321. if ( ty <= min ) {
  18322. min = ty;
  18323. normal.set( 0, 1, 0 );
  18324. }
  18325. if ( tz <= min ) {
  18326. normal.set( 0, 0, 1 );
  18327. }
  18328. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  18329. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  18330. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  18331. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  18332. for ( let i = 1; i <= segments; i ++ ) {
  18333. normals[ i ] = normals[ i - 1 ].clone();
  18334. binormals[ i ] = binormals[ i - 1 ].clone();
  18335. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  18336. if ( vec.length() > Number.EPSILON ) {
  18337. vec.normalize();
  18338. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  18339. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  18340. }
  18341. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  18342. }
  18343. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  18344. if ( closed === true ) {
  18345. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  18346. theta /= segments;
  18347. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  18348. theta = - theta;
  18349. }
  18350. for ( let i = 1; i <= segments; i ++ ) {
  18351. // twist a little...
  18352. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  18353. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  18354. }
  18355. }
  18356. return {
  18357. tangents: tangents,
  18358. normals: normals,
  18359. binormals: binormals
  18360. };
  18361. }
  18362. clone() {
  18363. return new this.constructor().copy( this );
  18364. }
  18365. copy( source ) {
  18366. this.arcLengthDivisions = source.arcLengthDivisions;
  18367. return this;
  18368. }
  18369. toJSON() {
  18370. const data = {
  18371. metadata: {
  18372. version: 4.5,
  18373. type: 'Curve',
  18374. generator: 'Curve.toJSON'
  18375. }
  18376. };
  18377. data.arcLengthDivisions = this.arcLengthDivisions;
  18378. data.type = this.type;
  18379. return data;
  18380. }
  18381. fromJSON( json ) {
  18382. this.arcLengthDivisions = json.arcLengthDivisions;
  18383. return this;
  18384. }
  18385. }
  18386. class EllipseCurve extends Curve {
  18387. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  18388. super();
  18389. this.type = 'EllipseCurve';
  18390. this.aX = aX;
  18391. this.aY = aY;
  18392. this.xRadius = xRadius;
  18393. this.yRadius = yRadius;
  18394. this.aStartAngle = aStartAngle;
  18395. this.aEndAngle = aEndAngle;
  18396. this.aClockwise = aClockwise;
  18397. this.aRotation = aRotation;
  18398. }
  18399. getPoint( t, optionalTarget ) {
  18400. const point = optionalTarget || new Vector2();
  18401. const twoPi = Math.PI * 2;
  18402. let deltaAngle = this.aEndAngle - this.aStartAngle;
  18403. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  18404. // ensures that deltaAngle is 0 .. 2 PI
  18405. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  18406. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  18407. if ( deltaAngle < Number.EPSILON ) {
  18408. if ( samePoints ) {
  18409. deltaAngle = 0;
  18410. } else {
  18411. deltaAngle = twoPi;
  18412. }
  18413. }
  18414. if ( this.aClockwise === true && ! samePoints ) {
  18415. if ( deltaAngle === twoPi ) {
  18416. deltaAngle = - twoPi;
  18417. } else {
  18418. deltaAngle = deltaAngle - twoPi;
  18419. }
  18420. }
  18421. const angle = this.aStartAngle + t * deltaAngle;
  18422. let x = this.aX + this.xRadius * Math.cos( angle );
  18423. let y = this.aY + this.yRadius * Math.sin( angle );
  18424. if ( this.aRotation !== 0 ) {
  18425. const cos = Math.cos( this.aRotation );
  18426. const sin = Math.sin( this.aRotation );
  18427. const tx = x - this.aX;
  18428. const ty = y - this.aY;
  18429. // Rotate the point about the center of the ellipse.
  18430. x = tx * cos - ty * sin + this.aX;
  18431. y = tx * sin + ty * cos + this.aY;
  18432. }
  18433. return point.set( x, y );
  18434. }
  18435. copy( source ) {
  18436. super.copy( source );
  18437. this.aX = source.aX;
  18438. this.aY = source.aY;
  18439. this.xRadius = source.xRadius;
  18440. this.yRadius = source.yRadius;
  18441. this.aStartAngle = source.aStartAngle;
  18442. this.aEndAngle = source.aEndAngle;
  18443. this.aClockwise = source.aClockwise;
  18444. this.aRotation = source.aRotation;
  18445. return this;
  18446. }
  18447. toJSON() {
  18448. const data = super.toJSON();
  18449. data.aX = this.aX;
  18450. data.aY = this.aY;
  18451. data.xRadius = this.xRadius;
  18452. data.yRadius = this.yRadius;
  18453. data.aStartAngle = this.aStartAngle;
  18454. data.aEndAngle = this.aEndAngle;
  18455. data.aClockwise = this.aClockwise;
  18456. data.aRotation = this.aRotation;
  18457. return data;
  18458. }
  18459. fromJSON( json ) {
  18460. super.fromJSON( json );
  18461. this.aX = json.aX;
  18462. this.aY = json.aY;
  18463. this.xRadius = json.xRadius;
  18464. this.yRadius = json.yRadius;
  18465. this.aStartAngle = json.aStartAngle;
  18466. this.aEndAngle = json.aEndAngle;
  18467. this.aClockwise = json.aClockwise;
  18468. this.aRotation = json.aRotation;
  18469. return this;
  18470. }
  18471. }
  18472. EllipseCurve.prototype.isEllipseCurve = true;
  18473. class ArcCurve extends EllipseCurve {
  18474. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  18475. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  18476. this.type = 'ArcCurve';
  18477. }
  18478. }
  18479. ArcCurve.prototype.isArcCurve = true;
  18480. /**
  18481. * Centripetal CatmullRom Curve - which is useful for avoiding
  18482. * cusps and self-intersections in non-uniform catmull rom curves.
  18483. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  18484. *
  18485. * curve.type accepts centripetal(default), chordal and catmullrom
  18486. * curve.tension is used for catmullrom which defaults to 0.5
  18487. */
  18488. /*
  18489. Based on an optimized c++ solution in
  18490. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  18491. - http://ideone.com/NoEbVM
  18492. This CubicPoly class could be used for reusing some variables and calculations,
  18493. but for three.js curve use, it could be possible inlined and flatten into a single function call
  18494. which can be placed in CurveUtils.
  18495. */
  18496. function CubicPoly() {
  18497. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  18498. /*
  18499. * Compute coefficients for a cubic polynomial
  18500. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  18501. * such that
  18502. * p(0) = x0, p(1) = x1
  18503. * and
  18504. * p'(0) = t0, p'(1) = t1.
  18505. */
  18506. function init( x0, x1, t0, t1 ) {
  18507. c0 = x0;
  18508. c1 = t0;
  18509. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  18510. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  18511. }
  18512. return {
  18513. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  18514. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  18515. },
  18516. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  18517. // compute tangents when parameterized in [t1,t2]
  18518. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  18519. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  18520. // rescale tangents for parametrization in [0,1]
  18521. t1 *= dt1;
  18522. t2 *= dt1;
  18523. init( x1, x2, t1, t2 );
  18524. },
  18525. calc: function ( t ) {
  18526. const t2 = t * t;
  18527. const t3 = t2 * t;
  18528. return c0 + c1 * t + c2 * t2 + c3 * t3;
  18529. }
  18530. };
  18531. }
  18532. //
  18533. const tmp = new Vector3();
  18534. const px = new CubicPoly(), py = new CubicPoly(), pz = new CubicPoly();
  18535. class CatmullRomCurve3 extends Curve {
  18536. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  18537. super();
  18538. this.type = 'CatmullRomCurve3';
  18539. this.points = points;
  18540. this.closed = closed;
  18541. this.curveType = curveType;
  18542. this.tension = tension;
  18543. }
  18544. getPoint( t, optionalTarget = new Vector3() ) {
  18545. const point = optionalTarget;
  18546. const points = this.points;
  18547. const l = points.length;
  18548. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  18549. let intPoint = Math.floor( p );
  18550. let weight = p - intPoint;
  18551. if ( this.closed ) {
  18552. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  18553. } else if ( weight === 0 && intPoint === l - 1 ) {
  18554. intPoint = l - 2;
  18555. weight = 1;
  18556. }
  18557. let p0, p3; // 4 points (p1 & p2 defined below)
  18558. if ( this.closed || intPoint > 0 ) {
  18559. p0 = points[ ( intPoint - 1 ) % l ];
  18560. } else {
  18561. // extrapolate first point
  18562. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  18563. p0 = tmp;
  18564. }
  18565. const p1 = points[ intPoint % l ];
  18566. const p2 = points[ ( intPoint + 1 ) % l ];
  18567. if ( this.closed || intPoint + 2 < l ) {
  18568. p3 = points[ ( intPoint + 2 ) % l ];
  18569. } else {
  18570. // extrapolate last point
  18571. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  18572. p3 = tmp;
  18573. }
  18574. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  18575. // init Centripetal / Chordal Catmull-Rom
  18576. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  18577. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  18578. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  18579. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  18580. // safety check for repeated points
  18581. if ( dt1 < 1e-4 ) dt1 = 1.0;
  18582. if ( dt0 < 1e-4 ) dt0 = dt1;
  18583. if ( dt2 < 1e-4 ) dt2 = dt1;
  18584. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  18585. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  18586. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  18587. } else if ( this.curveType === 'catmullrom' ) {
  18588. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  18589. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  18590. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  18591. }
  18592. point.set(
  18593. px.calc( weight ),
  18594. py.calc( weight ),
  18595. pz.calc( weight )
  18596. );
  18597. return point;
  18598. }
  18599. copy( source ) {
  18600. super.copy( source );
  18601. this.points = [];
  18602. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  18603. const point = source.points[ i ];
  18604. this.points.push( point.clone() );
  18605. }
  18606. this.closed = source.closed;
  18607. this.curveType = source.curveType;
  18608. this.tension = source.tension;
  18609. return this;
  18610. }
  18611. toJSON() {
  18612. const data = super.toJSON();
  18613. data.points = [];
  18614. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  18615. const point = this.points[ i ];
  18616. data.points.push( point.toArray() );
  18617. }
  18618. data.closed = this.closed;
  18619. data.curveType = this.curveType;
  18620. data.tension = this.tension;
  18621. return data;
  18622. }
  18623. fromJSON( json ) {
  18624. super.fromJSON( json );
  18625. this.points = [];
  18626. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  18627. const point = json.points[ i ];
  18628. this.points.push( new Vector3().fromArray( point ) );
  18629. }
  18630. this.closed = json.closed;
  18631. this.curveType = json.curveType;
  18632. this.tension = json.tension;
  18633. return this;
  18634. }
  18635. }
  18636. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  18637. /**
  18638. * Bezier Curves formulas obtained from
  18639. * http://en.wikipedia.org/wiki/Bézier_curve
  18640. */
  18641. function CatmullRom( t, p0, p1, p2, p3 ) {
  18642. const v0 = ( p2 - p0 ) * 0.5;
  18643. const v1 = ( p3 - p1 ) * 0.5;
  18644. const t2 = t * t;
  18645. const t3 = t * t2;
  18646. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18647. }
  18648. //
  18649. function QuadraticBezierP0( t, p ) {
  18650. const k = 1 - t;
  18651. return k * k * p;
  18652. }
  18653. function QuadraticBezierP1( t, p ) {
  18654. return 2 * ( 1 - t ) * t * p;
  18655. }
  18656. function QuadraticBezierP2( t, p ) {
  18657. return t * t * p;
  18658. }
  18659. function QuadraticBezier( t, p0, p1, p2 ) {
  18660. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  18661. QuadraticBezierP2( t, p2 );
  18662. }
  18663. //
  18664. function CubicBezierP0( t, p ) {
  18665. const k = 1 - t;
  18666. return k * k * k * p;
  18667. }
  18668. function CubicBezierP1( t, p ) {
  18669. const k = 1 - t;
  18670. return 3 * k * k * t * p;
  18671. }
  18672. function CubicBezierP2( t, p ) {
  18673. return 3 * ( 1 - t ) * t * t * p;
  18674. }
  18675. function CubicBezierP3( t, p ) {
  18676. return t * t * t * p;
  18677. }
  18678. function CubicBezier( t, p0, p1, p2, p3 ) {
  18679. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  18680. CubicBezierP3( t, p3 );
  18681. }
  18682. class CubicBezierCurve extends Curve {
  18683. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  18684. super();
  18685. this.type = 'CubicBezierCurve';
  18686. this.v0 = v0;
  18687. this.v1 = v1;
  18688. this.v2 = v2;
  18689. this.v3 = v3;
  18690. }
  18691. getPoint( t, optionalTarget = new Vector2() ) {
  18692. const point = optionalTarget;
  18693. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  18694. point.set(
  18695. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  18696. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  18697. );
  18698. return point;
  18699. }
  18700. copy( source ) {
  18701. super.copy( source );
  18702. this.v0.copy( source.v0 );
  18703. this.v1.copy( source.v1 );
  18704. this.v2.copy( source.v2 );
  18705. this.v3.copy( source.v3 );
  18706. return this;
  18707. }
  18708. toJSON() {
  18709. const data = super.toJSON();
  18710. data.v0 = this.v0.toArray();
  18711. data.v1 = this.v1.toArray();
  18712. data.v2 = this.v2.toArray();
  18713. data.v3 = this.v3.toArray();
  18714. return data;
  18715. }
  18716. fromJSON( json ) {
  18717. super.fromJSON( json );
  18718. this.v0.fromArray( json.v0 );
  18719. this.v1.fromArray( json.v1 );
  18720. this.v2.fromArray( json.v2 );
  18721. this.v3.fromArray( json.v3 );
  18722. return this;
  18723. }
  18724. }
  18725. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  18726. class CubicBezierCurve3 extends Curve {
  18727. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  18728. super();
  18729. this.type = 'CubicBezierCurve3';
  18730. this.v0 = v0;
  18731. this.v1 = v1;
  18732. this.v2 = v2;
  18733. this.v3 = v3;
  18734. }
  18735. getPoint( t, optionalTarget = new Vector3() ) {
  18736. const point = optionalTarget;
  18737. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  18738. point.set(
  18739. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  18740. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  18741. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  18742. );
  18743. return point;
  18744. }
  18745. copy( source ) {
  18746. super.copy( source );
  18747. this.v0.copy( source.v0 );
  18748. this.v1.copy( source.v1 );
  18749. this.v2.copy( source.v2 );
  18750. this.v3.copy( source.v3 );
  18751. return this;
  18752. }
  18753. toJSON() {
  18754. const data = super.toJSON();
  18755. data.v0 = this.v0.toArray();
  18756. data.v1 = this.v1.toArray();
  18757. data.v2 = this.v2.toArray();
  18758. data.v3 = this.v3.toArray();
  18759. return data;
  18760. }
  18761. fromJSON( json ) {
  18762. super.fromJSON( json );
  18763. this.v0.fromArray( json.v0 );
  18764. this.v1.fromArray( json.v1 );
  18765. this.v2.fromArray( json.v2 );
  18766. this.v3.fromArray( json.v3 );
  18767. return this;
  18768. }
  18769. }
  18770. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  18771. class LineCurve extends Curve {
  18772. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  18773. super();
  18774. this.type = 'LineCurve';
  18775. this.v1 = v1;
  18776. this.v2 = v2;
  18777. }
  18778. getPoint( t, optionalTarget = new Vector2() ) {
  18779. const point = optionalTarget;
  18780. if ( t === 1 ) {
  18781. point.copy( this.v2 );
  18782. } else {
  18783. point.copy( this.v2 ).sub( this.v1 );
  18784. point.multiplyScalar( t ).add( this.v1 );
  18785. }
  18786. return point;
  18787. }
  18788. // Line curve is linear, so we can overwrite default getPointAt
  18789. getPointAt( u, optionalTarget ) {
  18790. return this.getPoint( u, optionalTarget );
  18791. }
  18792. getTangent( t, optionalTarget ) {
  18793. const tangent = optionalTarget || new Vector2();
  18794. tangent.copy( this.v2 ).sub( this.v1 ).normalize();
  18795. return tangent;
  18796. }
  18797. copy( source ) {
  18798. super.copy( source );
  18799. this.v1.copy( source.v1 );
  18800. this.v2.copy( source.v2 );
  18801. return this;
  18802. }
  18803. toJSON() {
  18804. const data = super.toJSON();
  18805. data.v1 = this.v1.toArray();
  18806. data.v2 = this.v2.toArray();
  18807. return data;
  18808. }
  18809. fromJSON( json ) {
  18810. super.fromJSON( json );
  18811. this.v1.fromArray( json.v1 );
  18812. this.v2.fromArray( json.v2 );
  18813. return this;
  18814. }
  18815. }
  18816. LineCurve.prototype.isLineCurve = true;
  18817. class LineCurve3 extends Curve {
  18818. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  18819. super();
  18820. this.type = 'LineCurve3';
  18821. this.isLineCurve3 = true;
  18822. this.v1 = v1;
  18823. this.v2 = v2;
  18824. }
  18825. getPoint( t, optionalTarget = new Vector3() ) {
  18826. const point = optionalTarget;
  18827. if ( t === 1 ) {
  18828. point.copy( this.v2 );
  18829. } else {
  18830. point.copy( this.v2 ).sub( this.v1 );
  18831. point.multiplyScalar( t ).add( this.v1 );
  18832. }
  18833. return point;
  18834. }
  18835. // Line curve is linear, so we can overwrite default getPointAt
  18836. getPointAt( u, optionalTarget ) {
  18837. return this.getPoint( u, optionalTarget );
  18838. }
  18839. copy( source ) {
  18840. super.copy( source );
  18841. this.v1.copy( source.v1 );
  18842. this.v2.copy( source.v2 );
  18843. return this;
  18844. }
  18845. toJSON() {
  18846. const data = super.toJSON();
  18847. data.v1 = this.v1.toArray();
  18848. data.v2 = this.v2.toArray();
  18849. return data;
  18850. }
  18851. fromJSON( json ) {
  18852. super.fromJSON( json );
  18853. this.v1.fromArray( json.v1 );
  18854. this.v2.fromArray( json.v2 );
  18855. return this;
  18856. }
  18857. }
  18858. class QuadraticBezierCurve extends Curve {
  18859. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  18860. super();
  18861. this.type = 'QuadraticBezierCurve';
  18862. this.v0 = v0;
  18863. this.v1 = v1;
  18864. this.v2 = v2;
  18865. }
  18866. getPoint( t, optionalTarget = new Vector2() ) {
  18867. const point = optionalTarget;
  18868. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  18869. point.set(
  18870. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  18871. QuadraticBezier( t, v0.y, v1.y, v2.y )
  18872. );
  18873. return point;
  18874. }
  18875. copy( source ) {
  18876. super.copy( source );
  18877. this.v0.copy( source.v0 );
  18878. this.v1.copy( source.v1 );
  18879. this.v2.copy( source.v2 );
  18880. return this;
  18881. }
  18882. toJSON() {
  18883. const data = super.toJSON();
  18884. data.v0 = this.v0.toArray();
  18885. data.v1 = this.v1.toArray();
  18886. data.v2 = this.v2.toArray();
  18887. return data;
  18888. }
  18889. fromJSON( json ) {
  18890. super.fromJSON( json );
  18891. this.v0.fromArray( json.v0 );
  18892. this.v1.fromArray( json.v1 );
  18893. this.v2.fromArray( json.v2 );
  18894. return this;
  18895. }
  18896. }
  18897. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  18898. class QuadraticBezierCurve3 extends Curve {
  18899. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  18900. super();
  18901. this.type = 'QuadraticBezierCurve3';
  18902. this.v0 = v0;
  18903. this.v1 = v1;
  18904. this.v2 = v2;
  18905. }
  18906. getPoint( t, optionalTarget = new Vector3() ) {
  18907. const point = optionalTarget;
  18908. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  18909. point.set(
  18910. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  18911. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  18912. QuadraticBezier( t, v0.z, v1.z, v2.z )
  18913. );
  18914. return point;
  18915. }
  18916. copy( source ) {
  18917. super.copy( source );
  18918. this.v0.copy( source.v0 );
  18919. this.v1.copy( source.v1 );
  18920. this.v2.copy( source.v2 );
  18921. return this;
  18922. }
  18923. toJSON() {
  18924. const data = super.toJSON();
  18925. data.v0 = this.v0.toArray();
  18926. data.v1 = this.v1.toArray();
  18927. data.v2 = this.v2.toArray();
  18928. return data;
  18929. }
  18930. fromJSON( json ) {
  18931. super.fromJSON( json );
  18932. this.v0.fromArray( json.v0 );
  18933. this.v1.fromArray( json.v1 );
  18934. this.v2.fromArray( json.v2 );
  18935. return this;
  18936. }
  18937. }
  18938. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  18939. class SplineCurve extends Curve {
  18940. constructor( points = [] ) {
  18941. super();
  18942. this.type = 'SplineCurve';
  18943. this.points = points;
  18944. }
  18945. getPoint( t, optionalTarget = new Vector2() ) {
  18946. const point = optionalTarget;
  18947. const points = this.points;
  18948. const p = ( points.length - 1 ) * t;
  18949. const intPoint = Math.floor( p );
  18950. const weight = p - intPoint;
  18951. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  18952. const p1 = points[ intPoint ];
  18953. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  18954. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  18955. point.set(
  18956. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  18957. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  18958. );
  18959. return point;
  18960. }
  18961. copy( source ) {
  18962. super.copy( source );
  18963. this.points = [];
  18964. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  18965. const point = source.points[ i ];
  18966. this.points.push( point.clone() );
  18967. }
  18968. return this;
  18969. }
  18970. toJSON() {
  18971. const data = super.toJSON();
  18972. data.points = [];
  18973. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  18974. const point = this.points[ i ];
  18975. data.points.push( point.toArray() );
  18976. }
  18977. return data;
  18978. }
  18979. fromJSON( json ) {
  18980. super.fromJSON( json );
  18981. this.points = [];
  18982. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  18983. const point = json.points[ i ];
  18984. this.points.push( new Vector2().fromArray( point ) );
  18985. }
  18986. return this;
  18987. }
  18988. }
  18989. SplineCurve.prototype.isSplineCurve = true;
  18990. var Curves = /*#__PURE__*/Object.freeze({
  18991. __proto__: null,
  18992. ArcCurve: ArcCurve,
  18993. CatmullRomCurve3: CatmullRomCurve3,
  18994. CubicBezierCurve: CubicBezierCurve,
  18995. CubicBezierCurve3: CubicBezierCurve3,
  18996. EllipseCurve: EllipseCurve,
  18997. LineCurve: LineCurve,
  18998. LineCurve3: LineCurve3,
  18999. QuadraticBezierCurve: QuadraticBezierCurve,
  19000. QuadraticBezierCurve3: QuadraticBezierCurve3,
  19001. SplineCurve: SplineCurve
  19002. });
  19003. /**************************************************************
  19004. * Curved Path - a curve path is simply a array of connected
  19005. * curves, but retains the api of a curve
  19006. **************************************************************/
  19007. class CurvePath extends Curve {
  19008. constructor() {
  19009. super();
  19010. this.type = 'CurvePath';
  19011. this.curves = [];
  19012. this.autoClose = false; // Automatically closes the path
  19013. }
  19014. add( curve ) {
  19015. this.curves.push( curve );
  19016. }
  19017. closePath() {
  19018. // Add a line curve if start and end of lines are not connected
  19019. const startPoint = this.curves[ 0 ].getPoint( 0 );
  19020. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  19021. if ( ! startPoint.equals( endPoint ) ) {
  19022. this.curves.push( new LineCurve( endPoint, startPoint ) );
  19023. }
  19024. }
  19025. // To get accurate point with reference to
  19026. // entire path distance at time t,
  19027. // following has to be done:
  19028. // 1. Length of each sub path have to be known
  19029. // 2. Locate and identify type of curve
  19030. // 3. Get t for the curve
  19031. // 4. Return curve.getPointAt(t')
  19032. getPoint( t, optionalTarget ) {
  19033. const d = t * this.getLength();
  19034. const curveLengths = this.getCurveLengths();
  19035. let i = 0;
  19036. // To think about boundaries points.
  19037. while ( i < curveLengths.length ) {
  19038. if ( curveLengths[ i ] >= d ) {
  19039. const diff = curveLengths[ i ] - d;
  19040. const curve = this.curves[ i ];
  19041. const segmentLength = curve.getLength();
  19042. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  19043. return curve.getPointAt( u, optionalTarget );
  19044. }
  19045. i ++;
  19046. }
  19047. return null;
  19048. // loop where sum != 0, sum > d , sum+1 <d
  19049. }
  19050. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  19051. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  19052. // getPoint() depends on getLength
  19053. getLength() {
  19054. const lens = this.getCurveLengths();
  19055. return lens[ lens.length - 1 ];
  19056. }
  19057. // cacheLengths must be recalculated.
  19058. updateArcLengths() {
  19059. this.needsUpdate = true;
  19060. this.cacheLengths = null;
  19061. this.getCurveLengths();
  19062. }
  19063. // Compute lengths and cache them
  19064. // We cannot overwrite getLengths() because UtoT mapping uses it.
  19065. getCurveLengths() {
  19066. // We use cache values if curves and cache array are same length
  19067. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  19068. return this.cacheLengths;
  19069. }
  19070. // Get length of sub-curve
  19071. // Push sums into cached array
  19072. const lengths = [];
  19073. let sums = 0;
  19074. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  19075. sums += this.curves[ i ].getLength();
  19076. lengths.push( sums );
  19077. }
  19078. this.cacheLengths = lengths;
  19079. return lengths;
  19080. }
  19081. getSpacedPoints( divisions = 40 ) {
  19082. const points = [];
  19083. for ( let i = 0; i <= divisions; i ++ ) {
  19084. points.push( this.getPoint( i / divisions ) );
  19085. }
  19086. if ( this.autoClose ) {
  19087. points.push( points[ 0 ] );
  19088. }
  19089. return points;
  19090. }
  19091. getPoints( divisions = 12 ) {
  19092. const points = [];
  19093. let last;
  19094. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  19095. const curve = curves[ i ];
  19096. const resolution = ( curve && curve.isEllipseCurve ) ? divisions * 2
  19097. : ( curve && ( curve.isLineCurve || curve.isLineCurve3 ) ) ? 1
  19098. : ( curve && curve.isSplineCurve ) ? divisions * curve.points.length
  19099. : divisions;
  19100. const pts = curve.getPoints( resolution );
  19101. for ( let j = 0; j < pts.length; j ++ ) {
  19102. const point = pts[ j ];
  19103. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  19104. points.push( point );
  19105. last = point;
  19106. }
  19107. }
  19108. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  19109. points.push( points[ 0 ] );
  19110. }
  19111. return points;
  19112. }
  19113. copy( source ) {
  19114. super.copy( source );
  19115. this.curves = [];
  19116. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  19117. const curve = source.curves[ i ];
  19118. this.curves.push( curve.clone() );
  19119. }
  19120. this.autoClose = source.autoClose;
  19121. return this;
  19122. }
  19123. toJSON() {
  19124. const data = super.toJSON();
  19125. data.autoClose = this.autoClose;
  19126. data.curves = [];
  19127. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  19128. const curve = this.curves[ i ];
  19129. data.curves.push( curve.toJSON() );
  19130. }
  19131. return data;
  19132. }
  19133. fromJSON( json ) {
  19134. super.fromJSON( json );
  19135. this.autoClose = json.autoClose;
  19136. this.curves = [];
  19137. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  19138. const curve = json.curves[ i ];
  19139. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  19140. }
  19141. return this;
  19142. }
  19143. }
  19144. class Path extends CurvePath {
  19145. constructor( points ) {
  19146. super();
  19147. this.type = 'Path';
  19148. this.currentPoint = new Vector2();
  19149. if ( points ) {
  19150. this.setFromPoints( points );
  19151. }
  19152. }
  19153. setFromPoints( points ) {
  19154. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  19155. for ( let i = 1, l = points.length; i < l; i ++ ) {
  19156. this.lineTo( points[ i ].x, points[ i ].y );
  19157. }
  19158. return this;
  19159. }
  19160. moveTo( x, y ) {
  19161. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  19162. return this;
  19163. }
  19164. lineTo( x, y ) {
  19165. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  19166. this.curves.push( curve );
  19167. this.currentPoint.set( x, y );
  19168. return this;
  19169. }
  19170. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  19171. const curve = new QuadraticBezierCurve(
  19172. this.currentPoint.clone(),
  19173. new Vector2( aCPx, aCPy ),
  19174. new Vector2( aX, aY )
  19175. );
  19176. this.curves.push( curve );
  19177. this.currentPoint.set( aX, aY );
  19178. return this;
  19179. }
  19180. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  19181. const curve = new CubicBezierCurve(
  19182. this.currentPoint.clone(),
  19183. new Vector2( aCP1x, aCP1y ),
  19184. new Vector2( aCP2x, aCP2y ),
  19185. new Vector2( aX, aY )
  19186. );
  19187. this.curves.push( curve );
  19188. this.currentPoint.set( aX, aY );
  19189. return this;
  19190. }
  19191. splineThru( pts /*Array of Vector*/ ) {
  19192. const npts = [ this.currentPoint.clone() ].concat( pts );
  19193. const curve = new SplineCurve( npts );
  19194. this.curves.push( curve );
  19195. this.currentPoint.copy( pts[ pts.length - 1 ] );
  19196. return this;
  19197. }
  19198. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19199. const x0 = this.currentPoint.x;
  19200. const y0 = this.currentPoint.y;
  19201. this.absarc( aX + x0, aY + y0, aRadius,
  19202. aStartAngle, aEndAngle, aClockwise );
  19203. return this;
  19204. }
  19205. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19206. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  19207. return this;
  19208. }
  19209. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  19210. const x0 = this.currentPoint.x;
  19211. const y0 = this.currentPoint.y;
  19212. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  19213. return this;
  19214. }
  19215. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  19216. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  19217. if ( this.curves.length > 0 ) {
  19218. // if a previous curve is present, attempt to join
  19219. const firstPoint = curve.getPoint( 0 );
  19220. if ( ! firstPoint.equals( this.currentPoint ) ) {
  19221. this.lineTo( firstPoint.x, firstPoint.y );
  19222. }
  19223. }
  19224. this.curves.push( curve );
  19225. const lastPoint = curve.getPoint( 1 );
  19226. this.currentPoint.copy( lastPoint );
  19227. return this;
  19228. }
  19229. copy( source ) {
  19230. super.copy( source );
  19231. this.currentPoint.copy( source.currentPoint );
  19232. return this;
  19233. }
  19234. toJSON() {
  19235. const data = super.toJSON();
  19236. data.currentPoint = this.currentPoint.toArray();
  19237. return data;
  19238. }
  19239. fromJSON( json ) {
  19240. super.fromJSON( json );
  19241. this.currentPoint.fromArray( json.currentPoint );
  19242. return this;
  19243. }
  19244. }
  19245. class Shape extends Path {
  19246. constructor( points ) {
  19247. super( points );
  19248. this.uuid = generateUUID();
  19249. this.type = 'Shape';
  19250. this.holes = [];
  19251. }
  19252. getPointsHoles( divisions ) {
  19253. const holesPts = [];
  19254. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  19255. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  19256. }
  19257. return holesPts;
  19258. }
  19259. // get points of shape and holes (keypoints based on segments parameter)
  19260. extractPoints( divisions ) {
  19261. return {
  19262. shape: this.getPoints( divisions ),
  19263. holes: this.getPointsHoles( divisions )
  19264. };
  19265. }
  19266. copy( source ) {
  19267. super.copy( source );
  19268. this.holes = [];
  19269. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  19270. const hole = source.holes[ i ];
  19271. this.holes.push( hole.clone() );
  19272. }
  19273. return this;
  19274. }
  19275. toJSON() {
  19276. const data = super.toJSON();
  19277. data.uuid = this.uuid;
  19278. data.holes = [];
  19279. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  19280. const hole = this.holes[ i ];
  19281. data.holes.push( hole.toJSON() );
  19282. }
  19283. return data;
  19284. }
  19285. fromJSON( json ) {
  19286. super.fromJSON( json );
  19287. this.uuid = json.uuid;
  19288. this.holes = [];
  19289. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  19290. const hole = json.holes[ i ];
  19291. this.holes.push( new Path().fromJSON( hole ) );
  19292. }
  19293. return this;
  19294. }
  19295. }
  19296. /**
  19297. * Port from https://github.com/mapbox/earcut (v2.2.2)
  19298. */
  19299. const Earcut = {
  19300. triangulate: function ( data, holeIndices, dim = 2 ) {
  19301. const hasHoles = holeIndices && holeIndices.length;
  19302. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  19303. let outerNode = linkedList( data, 0, outerLen, dim, true );
  19304. const triangles = [];
  19305. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  19306. let minX, minY, maxX, maxY, x, y, invSize;
  19307. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  19308. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  19309. if ( data.length > 80 * dim ) {
  19310. minX = maxX = data[ 0 ];
  19311. minY = maxY = data[ 1 ];
  19312. for ( let i = dim; i < outerLen; i += dim ) {
  19313. x = data[ i ];
  19314. y = data[ i + 1 ];
  19315. if ( x < minX ) minX = x;
  19316. if ( y < minY ) minY = y;
  19317. if ( x > maxX ) maxX = x;
  19318. if ( y > maxY ) maxY = y;
  19319. }
  19320. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  19321. invSize = Math.max( maxX - minX, maxY - minY );
  19322. invSize = invSize !== 0 ? 1 / invSize : 0;
  19323. }
  19324. earcutLinked( outerNode, triangles, dim, minX, minY, invSize );
  19325. return triangles;
  19326. }
  19327. };
  19328. // create a circular doubly linked list from polygon points in the specified winding order
  19329. function linkedList( data, start, end, dim, clockwise ) {
  19330. let i, last;
  19331. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  19332. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  19333. } else {
  19334. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  19335. }
  19336. if ( last && equals( last, last.next ) ) {
  19337. removeNode( last );
  19338. last = last.next;
  19339. }
  19340. return last;
  19341. }
  19342. // eliminate colinear or duplicate points
  19343. function filterPoints( start, end ) {
  19344. if ( ! start ) return start;
  19345. if ( ! end ) end = start;
  19346. let p = start,
  19347. again;
  19348. do {
  19349. again = false;
  19350. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  19351. removeNode( p );
  19352. p = end = p.prev;
  19353. if ( p === p.next ) break;
  19354. again = true;
  19355. } else {
  19356. p = p.next;
  19357. }
  19358. } while ( again || p !== end );
  19359. return end;
  19360. }
  19361. // main ear slicing loop which triangulates a polygon (given as a linked list)
  19362. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  19363. if ( ! ear ) return;
  19364. // interlink polygon nodes in z-order
  19365. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  19366. let stop = ear,
  19367. prev, next;
  19368. // iterate through ears, slicing them one by one
  19369. while ( ear.prev !== ear.next ) {
  19370. prev = ear.prev;
  19371. next = ear.next;
  19372. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  19373. // cut off the triangle
  19374. triangles.push( prev.i / dim );
  19375. triangles.push( ear.i / dim );
  19376. triangles.push( next.i / dim );
  19377. removeNode( ear );
  19378. // skipping the next vertex leads to less sliver triangles
  19379. ear = next.next;
  19380. stop = next.next;
  19381. continue;
  19382. }
  19383. ear = next;
  19384. // if we looped through the whole remaining polygon and can't find any more ears
  19385. if ( ear === stop ) {
  19386. // try filtering points and slicing again
  19387. if ( ! pass ) {
  19388. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  19389. // if this didn't work, try curing all small self-intersections locally
  19390. } else if ( pass === 1 ) {
  19391. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  19392. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  19393. // as a last resort, try splitting the remaining polygon into two
  19394. } else if ( pass === 2 ) {
  19395. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  19396. }
  19397. break;
  19398. }
  19399. }
  19400. }
  19401. // check whether a polygon node forms a valid ear with adjacent nodes
  19402. function isEar( ear ) {
  19403. const a = ear.prev,
  19404. b = ear,
  19405. c = ear.next;
  19406. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  19407. // now make sure we don't have other points inside the potential ear
  19408. let p = ear.next.next;
  19409. while ( p !== ear.prev ) {
  19410. if ( pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  19411. area( p.prev, p, p.next ) >= 0 ) return false;
  19412. p = p.next;
  19413. }
  19414. return true;
  19415. }
  19416. function isEarHashed( ear, minX, minY, invSize ) {
  19417. const a = ear.prev,
  19418. b = ear,
  19419. c = ear.next;
  19420. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  19421. // triangle bbox; min & max are calculated like this for speed
  19422. const minTX = a.x < b.x ? ( a.x < c.x ? a.x : c.x ) : ( b.x < c.x ? b.x : c.x ),
  19423. minTY = a.y < b.y ? ( a.y < c.y ? a.y : c.y ) : ( b.y < c.y ? b.y : c.y ),
  19424. maxTX = a.x > b.x ? ( a.x > c.x ? a.x : c.x ) : ( b.x > c.x ? b.x : c.x ),
  19425. maxTY = a.y > b.y ? ( a.y > c.y ? a.y : c.y ) : ( b.y > c.y ? b.y : c.y );
  19426. // z-order range for the current triangle bbox;
  19427. const minZ = zOrder( minTX, minTY, minX, minY, invSize ),
  19428. maxZ = zOrder( maxTX, maxTY, minX, minY, invSize );
  19429. let p = ear.prevZ,
  19430. n = ear.nextZ;
  19431. // look for points inside the triangle in both directions
  19432. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  19433. if ( p !== ear.prev && p !== ear.next &&
  19434. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  19435. area( p.prev, p, p.next ) >= 0 ) return false;
  19436. p = p.prevZ;
  19437. if ( n !== ear.prev && n !== ear.next &&
  19438. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  19439. area( n.prev, n, n.next ) >= 0 ) return false;
  19440. n = n.nextZ;
  19441. }
  19442. // look for remaining points in decreasing z-order
  19443. while ( p && p.z >= minZ ) {
  19444. if ( p !== ear.prev && p !== ear.next &&
  19445. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  19446. area( p.prev, p, p.next ) >= 0 ) return false;
  19447. p = p.prevZ;
  19448. }
  19449. // look for remaining points in increasing z-order
  19450. while ( n && n.z <= maxZ ) {
  19451. if ( n !== ear.prev && n !== ear.next &&
  19452. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  19453. area( n.prev, n, n.next ) >= 0 ) return false;
  19454. n = n.nextZ;
  19455. }
  19456. return true;
  19457. }
  19458. // go through all polygon nodes and cure small local self-intersections
  19459. function cureLocalIntersections( start, triangles, dim ) {
  19460. let p = start;
  19461. do {
  19462. const a = p.prev,
  19463. b = p.next.next;
  19464. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  19465. triangles.push( a.i / dim );
  19466. triangles.push( p.i / dim );
  19467. triangles.push( b.i / dim );
  19468. // remove two nodes involved
  19469. removeNode( p );
  19470. removeNode( p.next );
  19471. p = start = b;
  19472. }
  19473. p = p.next;
  19474. } while ( p !== start );
  19475. return filterPoints( p );
  19476. }
  19477. // try splitting polygon into two and triangulate them independently
  19478. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  19479. // look for a valid diagonal that divides the polygon into two
  19480. let a = start;
  19481. do {
  19482. let b = a.next.next;
  19483. while ( b !== a.prev ) {
  19484. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  19485. // split the polygon in two by the diagonal
  19486. let c = splitPolygon( a, b );
  19487. // filter colinear points around the cuts
  19488. a = filterPoints( a, a.next );
  19489. c = filterPoints( c, c.next );
  19490. // run earcut on each half
  19491. earcutLinked( a, triangles, dim, minX, minY, invSize );
  19492. earcutLinked( c, triangles, dim, minX, minY, invSize );
  19493. return;
  19494. }
  19495. b = b.next;
  19496. }
  19497. a = a.next;
  19498. } while ( a !== start );
  19499. }
  19500. // link every hole into the outer loop, producing a single-ring polygon without holes
  19501. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  19502. const queue = [];
  19503. let i, len, start, end, list;
  19504. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  19505. start = holeIndices[ i ] * dim;
  19506. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  19507. list = linkedList( data, start, end, dim, false );
  19508. if ( list === list.next ) list.steiner = true;
  19509. queue.push( getLeftmost( list ) );
  19510. }
  19511. queue.sort( compareX );
  19512. // process holes from left to right
  19513. for ( i = 0; i < queue.length; i ++ ) {
  19514. eliminateHole( queue[ i ], outerNode );
  19515. outerNode = filterPoints( outerNode, outerNode.next );
  19516. }
  19517. return outerNode;
  19518. }
  19519. function compareX( a, b ) {
  19520. return a.x - b.x;
  19521. }
  19522. // find a bridge between vertices that connects hole with an outer ring and and link it
  19523. function eliminateHole( hole, outerNode ) {
  19524. outerNode = findHoleBridge( hole, outerNode );
  19525. if ( outerNode ) {
  19526. const b = splitPolygon( outerNode, hole );
  19527. // filter collinear points around the cuts
  19528. filterPoints( outerNode, outerNode.next );
  19529. filterPoints( b, b.next );
  19530. }
  19531. }
  19532. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  19533. function findHoleBridge( hole, outerNode ) {
  19534. let p = outerNode;
  19535. const hx = hole.x;
  19536. const hy = hole.y;
  19537. let qx = - Infinity, m;
  19538. // find a segment intersected by a ray from the hole's leftmost point to the left;
  19539. // segment's endpoint with lesser x will be potential connection point
  19540. do {
  19541. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  19542. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  19543. if ( x <= hx && x > qx ) {
  19544. qx = x;
  19545. if ( x === hx ) {
  19546. if ( hy === p.y ) return p;
  19547. if ( hy === p.next.y ) return p.next;
  19548. }
  19549. m = p.x < p.next.x ? p : p.next;
  19550. }
  19551. }
  19552. p = p.next;
  19553. } while ( p !== outerNode );
  19554. if ( ! m ) return null;
  19555. if ( hx === qx ) return m; // hole touches outer segment; pick leftmost endpoint
  19556. // look for points inside the triangle of hole point, segment intersection and endpoint;
  19557. // if there are no points found, we have a valid connection;
  19558. // otherwise choose the point of the minimum angle with the ray as connection point
  19559. const stop = m,
  19560. mx = m.x,
  19561. my = m.y;
  19562. let tanMin = Infinity, tan;
  19563. p = m;
  19564. do {
  19565. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  19566. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  19567. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  19568. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  19569. m = p;
  19570. tanMin = tan;
  19571. }
  19572. }
  19573. p = p.next;
  19574. } while ( p !== stop );
  19575. return m;
  19576. }
  19577. // whether sector in vertex m contains sector in vertex p in the same coordinates
  19578. function sectorContainsSector( m, p ) {
  19579. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  19580. }
  19581. // interlink polygon nodes in z-order
  19582. function indexCurve( start, minX, minY, invSize ) {
  19583. let p = start;
  19584. do {
  19585. if ( p.z === null ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  19586. p.prevZ = p.prev;
  19587. p.nextZ = p.next;
  19588. p = p.next;
  19589. } while ( p !== start );
  19590. p.prevZ.nextZ = null;
  19591. p.prevZ = null;
  19592. sortLinked( p );
  19593. }
  19594. // Simon Tatham's linked list merge sort algorithm
  19595. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  19596. function sortLinked( list ) {
  19597. let i, p, q, e, tail, numMerges, pSize, qSize,
  19598. inSize = 1;
  19599. do {
  19600. p = list;
  19601. list = null;
  19602. tail = null;
  19603. numMerges = 0;
  19604. while ( p ) {
  19605. numMerges ++;
  19606. q = p;
  19607. pSize = 0;
  19608. for ( i = 0; i < inSize; i ++ ) {
  19609. pSize ++;
  19610. q = q.nextZ;
  19611. if ( ! q ) break;
  19612. }
  19613. qSize = inSize;
  19614. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  19615. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  19616. e = p;
  19617. p = p.nextZ;
  19618. pSize --;
  19619. } else {
  19620. e = q;
  19621. q = q.nextZ;
  19622. qSize --;
  19623. }
  19624. if ( tail ) tail.nextZ = e;
  19625. else list = e;
  19626. e.prevZ = tail;
  19627. tail = e;
  19628. }
  19629. p = q;
  19630. }
  19631. tail.nextZ = null;
  19632. inSize *= 2;
  19633. } while ( numMerges > 1 );
  19634. return list;
  19635. }
  19636. // z-order of a point given coords and inverse of the longer side of data bbox
  19637. function zOrder( x, y, minX, minY, invSize ) {
  19638. // coords are transformed into non-negative 15-bit integer range
  19639. x = 32767 * ( x - minX ) * invSize;
  19640. y = 32767 * ( y - minY ) * invSize;
  19641. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  19642. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  19643. x = ( x | ( x << 2 ) ) & 0x33333333;
  19644. x = ( x | ( x << 1 ) ) & 0x55555555;
  19645. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  19646. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  19647. y = ( y | ( y << 2 ) ) & 0x33333333;
  19648. y = ( y | ( y << 1 ) ) & 0x55555555;
  19649. return x | ( y << 1 );
  19650. }
  19651. // find the leftmost node of a polygon ring
  19652. function getLeftmost( start ) {
  19653. let p = start,
  19654. leftmost = start;
  19655. do {
  19656. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  19657. p = p.next;
  19658. } while ( p !== start );
  19659. return leftmost;
  19660. }
  19661. // check if a point lies within a convex triangle
  19662. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  19663. return ( cx - px ) * ( ay - py ) - ( ax - px ) * ( cy - py ) >= 0 &&
  19664. ( ax - px ) * ( by - py ) - ( bx - px ) * ( ay - py ) >= 0 &&
  19665. ( bx - px ) * ( cy - py ) - ( cx - px ) * ( by - py ) >= 0;
  19666. }
  19667. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  19668. function isValidDiagonal( a, b ) {
  19669. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  19670. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  19671. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  19672. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  19673. }
  19674. // signed area of a triangle
  19675. function area( p, q, r ) {
  19676. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  19677. }
  19678. // check if two points are equal
  19679. function equals( p1, p2 ) {
  19680. return p1.x === p2.x && p1.y === p2.y;
  19681. }
  19682. // check if two segments intersect
  19683. function intersects( p1, q1, p2, q2 ) {
  19684. const o1 = sign( area( p1, q1, p2 ) );
  19685. const o2 = sign( area( p1, q1, q2 ) );
  19686. const o3 = sign( area( p2, q2, p1 ) );
  19687. const o4 = sign( area( p2, q2, q1 ) );
  19688. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  19689. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  19690. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  19691. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  19692. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  19693. return false;
  19694. }
  19695. // for collinear points p, q, r, check if point q lies on segment pr
  19696. function onSegment( p, q, r ) {
  19697. 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 );
  19698. }
  19699. function sign( num ) {
  19700. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  19701. }
  19702. // check if a polygon diagonal intersects any polygon segments
  19703. function intersectsPolygon( a, b ) {
  19704. let p = a;
  19705. do {
  19706. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  19707. intersects( p, p.next, a, b ) ) return true;
  19708. p = p.next;
  19709. } while ( p !== a );
  19710. return false;
  19711. }
  19712. // check if a polygon diagonal is locally inside the polygon
  19713. function locallyInside( a, b ) {
  19714. return area( a.prev, a, a.next ) < 0 ?
  19715. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  19716. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  19717. }
  19718. // check if the middle point of a polygon diagonal is inside the polygon
  19719. function middleInside( a, b ) {
  19720. let p = a,
  19721. inside = false;
  19722. const px = ( a.x + b.x ) / 2,
  19723. py = ( a.y + b.y ) / 2;
  19724. do {
  19725. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  19726. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  19727. inside = ! inside;
  19728. p = p.next;
  19729. } while ( p !== a );
  19730. return inside;
  19731. }
  19732. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  19733. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  19734. function splitPolygon( a, b ) {
  19735. const a2 = new Node( a.i, a.x, a.y ),
  19736. b2 = new Node( b.i, b.x, b.y ),
  19737. an = a.next,
  19738. bp = b.prev;
  19739. a.next = b;
  19740. b.prev = a;
  19741. a2.next = an;
  19742. an.prev = a2;
  19743. b2.next = a2;
  19744. a2.prev = b2;
  19745. bp.next = b2;
  19746. b2.prev = bp;
  19747. return b2;
  19748. }
  19749. // create a node and optionally link it with previous one (in a circular doubly linked list)
  19750. function insertNode( i, x, y, last ) {
  19751. const p = new Node( i, x, y );
  19752. if ( ! last ) {
  19753. p.prev = p;
  19754. p.next = p;
  19755. } else {
  19756. p.next = last.next;
  19757. p.prev = last;
  19758. last.next.prev = p;
  19759. last.next = p;
  19760. }
  19761. return p;
  19762. }
  19763. function removeNode( p ) {
  19764. p.next.prev = p.prev;
  19765. p.prev.next = p.next;
  19766. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  19767. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  19768. }
  19769. function Node( i, x, y ) {
  19770. // vertex index in coordinates array
  19771. this.i = i;
  19772. // vertex coordinates
  19773. this.x = x;
  19774. this.y = y;
  19775. // previous and next vertex nodes in a polygon ring
  19776. this.prev = null;
  19777. this.next = null;
  19778. // z-order curve value
  19779. this.z = null;
  19780. // previous and next nodes in z-order
  19781. this.prevZ = null;
  19782. this.nextZ = null;
  19783. // indicates whether this is a steiner point
  19784. this.steiner = false;
  19785. }
  19786. function signedArea( data, start, end, dim ) {
  19787. let sum = 0;
  19788. for ( let i = start, j = end - dim; i < end; i += dim ) {
  19789. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  19790. j = i;
  19791. }
  19792. return sum;
  19793. }
  19794. class ShapeUtils {
  19795. // calculate area of the contour polygon
  19796. static area( contour ) {
  19797. const n = contour.length;
  19798. let a = 0.0;
  19799. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  19800. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  19801. }
  19802. return a * 0.5;
  19803. }
  19804. static isClockWise( pts ) {
  19805. return ShapeUtils.area( pts ) < 0;
  19806. }
  19807. static triangulateShape( contour, holes ) {
  19808. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  19809. const holeIndices = []; // array of hole indices
  19810. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  19811. removeDupEndPts( contour );
  19812. addContour( vertices, contour );
  19813. //
  19814. let holeIndex = contour.length;
  19815. holes.forEach( removeDupEndPts );
  19816. for ( let i = 0; i < holes.length; i ++ ) {
  19817. holeIndices.push( holeIndex );
  19818. holeIndex += holes[ i ].length;
  19819. addContour( vertices, holes[ i ] );
  19820. }
  19821. //
  19822. const triangles = Earcut.triangulate( vertices, holeIndices );
  19823. //
  19824. for ( let i = 0; i < triangles.length; i += 3 ) {
  19825. faces.push( triangles.slice( i, i + 3 ) );
  19826. }
  19827. return faces;
  19828. }
  19829. }
  19830. function removeDupEndPts( points ) {
  19831. const l = points.length;
  19832. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  19833. points.pop();
  19834. }
  19835. }
  19836. function addContour( vertices, contour ) {
  19837. for ( let i = 0; i < contour.length; i ++ ) {
  19838. vertices.push( contour[ i ].x );
  19839. vertices.push( contour[ i ].y );
  19840. }
  19841. }
  19842. /**
  19843. * Creates extruded geometry from a path shape.
  19844. *
  19845. * parameters = {
  19846. *
  19847. * curveSegments: <int>, // number of points on the curves
  19848. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  19849. * depth: <float>, // Depth to extrude the shape
  19850. *
  19851. * bevelEnabled: <bool>, // turn on bevel
  19852. * bevelThickness: <float>, // how deep into the original shape bevel goes
  19853. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  19854. * bevelOffset: <float>, // how far from shape outline does bevel start
  19855. * bevelSegments: <int>, // number of bevel layers
  19856. *
  19857. * extrudePath: <THREE.Curve> // curve to extrude shape along
  19858. *
  19859. * UVGenerator: <Object> // object that provides UV generator functions
  19860. *
  19861. * }
  19862. */
  19863. class ExtrudeGeometry extends BufferGeometry {
  19864. constructor( shapes = new Shape( [ new Vector2( 0.5, 0.5 ), new Vector2( - 0.5, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), options = {} ) {
  19865. super();
  19866. this.type = 'ExtrudeGeometry';
  19867. this.parameters = {
  19868. shapes: shapes,
  19869. options: options
  19870. };
  19871. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  19872. const scope = this;
  19873. const verticesArray = [];
  19874. const uvArray = [];
  19875. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  19876. const shape = shapes[ i ];
  19877. addShape( shape );
  19878. }
  19879. // build geometry
  19880. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  19881. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  19882. this.computeVertexNormals();
  19883. // functions
  19884. function addShape( shape ) {
  19885. const placeholder = [];
  19886. // options
  19887. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19888. const steps = options.steps !== undefined ? options.steps : 1;
  19889. let depth = options.depth !== undefined ? options.depth : 1;
  19890. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  19891. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  19892. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  19893. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  19894. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  19895. const extrudePath = options.extrudePath;
  19896. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  19897. // deprecated options
  19898. if ( options.amount !== undefined ) {
  19899. console.warn( 'THREE.ExtrudeBufferGeometry: amount has been renamed to depth.' );
  19900. depth = options.amount;
  19901. }
  19902. //
  19903. let extrudePts, extrudeByPath = false;
  19904. let splineTube, binormal, normal, position2;
  19905. if ( extrudePath ) {
  19906. extrudePts = extrudePath.getSpacedPoints( steps );
  19907. extrudeByPath = true;
  19908. bevelEnabled = false; // bevels not supported for path extrusion
  19909. // SETUP TNB variables
  19910. // TODO1 - have a .isClosed in spline?
  19911. splineTube = extrudePath.computeFrenetFrames( steps, false );
  19912. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  19913. binormal = new Vector3();
  19914. normal = new Vector3();
  19915. position2 = new Vector3();
  19916. }
  19917. // Safeguards if bevels are not enabled
  19918. if ( ! bevelEnabled ) {
  19919. bevelSegments = 0;
  19920. bevelThickness = 0;
  19921. bevelSize = 0;
  19922. bevelOffset = 0;
  19923. }
  19924. // Variables initialization
  19925. const shapePoints = shape.extractPoints( curveSegments );
  19926. let vertices = shapePoints.shape;
  19927. const holes = shapePoints.holes;
  19928. const reverse = ! ShapeUtils.isClockWise( vertices );
  19929. if ( reverse ) {
  19930. vertices = vertices.reverse();
  19931. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  19932. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  19933. const ahole = holes[ h ];
  19934. if ( ShapeUtils.isClockWise( ahole ) ) {
  19935. holes[ h ] = ahole.reverse();
  19936. }
  19937. }
  19938. }
  19939. const faces = ShapeUtils.triangulateShape( vertices, holes );
  19940. /* Vertices */
  19941. const contour = vertices; // vertices has all points but contour has only points of circumference
  19942. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  19943. const ahole = holes[ h ];
  19944. vertices = vertices.concat( ahole );
  19945. }
  19946. function scalePt2( pt, vec, size ) {
  19947. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  19948. return vec.clone().multiplyScalar( size ).add( pt );
  19949. }
  19950. const vlen = vertices.length, flen = faces.length;
  19951. // Find directions for point movement
  19952. function getBevelVec( inPt, inPrev, inNext ) {
  19953. // computes for inPt the corresponding point inPt' on a new contour
  19954. // shifted by 1 unit (length of normalized vector) to the left
  19955. // if we walk along contour clockwise, this new contour is outside the old one
  19956. //
  19957. // inPt' is the intersection of the two lines parallel to the two
  19958. // adjacent edges of inPt at a distance of 1 unit on the left side.
  19959. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  19960. // good reading for geometry algorithms (here: line-line intersection)
  19961. // http://geomalgorithms.com/a05-_intersect-1.html
  19962. const v_prev_x = inPt.x - inPrev.x,
  19963. v_prev_y = inPt.y - inPrev.y;
  19964. const v_next_x = inNext.x - inPt.x,
  19965. v_next_y = inNext.y - inPt.y;
  19966. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  19967. // check for collinear edges
  19968. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  19969. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  19970. // not collinear
  19971. // length of vectors for normalizing
  19972. const v_prev_len = Math.sqrt( v_prev_lensq );
  19973. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  19974. // shift adjacent points by unit vectors to the left
  19975. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  19976. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  19977. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  19978. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  19979. // scaling factor for v_prev to intersection point
  19980. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  19981. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  19982. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  19983. // vector from inPt to intersection point
  19984. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  19985. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  19986. // Don't normalize!, otherwise sharp corners become ugly
  19987. // but prevent crazy spikes
  19988. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  19989. if ( v_trans_lensq <= 2 ) {
  19990. return new Vector2( v_trans_x, v_trans_y );
  19991. } else {
  19992. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  19993. }
  19994. } else {
  19995. // handle special case of collinear edges
  19996. let direction_eq = false; // assumes: opposite
  19997. if ( v_prev_x > Number.EPSILON ) {
  19998. if ( v_next_x > Number.EPSILON ) {
  19999. direction_eq = true;
  20000. }
  20001. } else {
  20002. if ( v_prev_x < - Number.EPSILON ) {
  20003. if ( v_next_x < - Number.EPSILON ) {
  20004. direction_eq = true;
  20005. }
  20006. } else {
  20007. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  20008. direction_eq = true;
  20009. }
  20010. }
  20011. }
  20012. if ( direction_eq ) {
  20013. // console.log("Warning: lines are a straight sequence");
  20014. v_trans_x = - v_prev_y;
  20015. v_trans_y = v_prev_x;
  20016. shrink_by = Math.sqrt( v_prev_lensq );
  20017. } else {
  20018. // console.log("Warning: lines are a straight spike");
  20019. v_trans_x = v_prev_x;
  20020. v_trans_y = v_prev_y;
  20021. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  20022. }
  20023. }
  20024. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  20025. }
  20026. const contourMovements = [];
  20027. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  20028. if ( j === il ) j = 0;
  20029. if ( k === il ) k = 0;
  20030. // (j)---(i)---(k)
  20031. // console.log('i,j,k', i, j , k)
  20032. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  20033. }
  20034. const holesMovements = [];
  20035. let oneHoleMovements, verticesMovements = contourMovements.concat();
  20036. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  20037. const ahole = holes[ h ];
  20038. oneHoleMovements = [];
  20039. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  20040. if ( j === il ) j = 0;
  20041. if ( k === il ) k = 0;
  20042. // (j)---(i)---(k)
  20043. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  20044. }
  20045. holesMovements.push( oneHoleMovements );
  20046. verticesMovements = verticesMovements.concat( oneHoleMovements );
  20047. }
  20048. // Loop bevelSegments, 1 for the front, 1 for the back
  20049. for ( let b = 0; b < bevelSegments; b ++ ) {
  20050. //for ( b = bevelSegments; b > 0; b -- ) {
  20051. const t = b / bevelSegments;
  20052. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  20053. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  20054. // contract shape
  20055. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  20056. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  20057. v( vert.x, vert.y, - z );
  20058. }
  20059. // expand holes
  20060. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  20061. const ahole = holes[ h ];
  20062. oneHoleMovements = holesMovements[ h ];
  20063. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  20064. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  20065. v( vert.x, vert.y, - z );
  20066. }
  20067. }
  20068. }
  20069. const bs = bevelSize + bevelOffset;
  20070. // Back facing vertices
  20071. for ( let i = 0; i < vlen; i ++ ) {
  20072. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  20073. if ( ! extrudeByPath ) {
  20074. v( vert.x, vert.y, 0 );
  20075. } else {
  20076. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  20077. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  20078. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  20079. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  20080. v( position2.x, position2.y, position2.z );
  20081. }
  20082. }
  20083. // Add stepped vertices...
  20084. // Including front facing vertices
  20085. for ( let s = 1; s <= steps; s ++ ) {
  20086. for ( let i = 0; i < vlen; i ++ ) {
  20087. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  20088. if ( ! extrudeByPath ) {
  20089. v( vert.x, vert.y, depth / steps * s );
  20090. } else {
  20091. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  20092. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  20093. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  20094. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  20095. v( position2.x, position2.y, position2.z );
  20096. }
  20097. }
  20098. }
  20099. // Add bevel segments planes
  20100. //for ( b = 1; b <= bevelSegments; b ++ ) {
  20101. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  20102. const t = b / bevelSegments;
  20103. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  20104. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  20105. // contract shape
  20106. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  20107. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  20108. v( vert.x, vert.y, depth + z );
  20109. }
  20110. // expand holes
  20111. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  20112. const ahole = holes[ h ];
  20113. oneHoleMovements = holesMovements[ h ];
  20114. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  20115. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  20116. if ( ! extrudeByPath ) {
  20117. v( vert.x, vert.y, depth + z );
  20118. } else {
  20119. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  20120. }
  20121. }
  20122. }
  20123. }
  20124. /* Faces */
  20125. // Top and bottom faces
  20126. buildLidFaces();
  20127. // Sides faces
  20128. buildSideFaces();
  20129. ///// Internal functions
  20130. function buildLidFaces() {
  20131. const start = verticesArray.length / 3;
  20132. if ( bevelEnabled ) {
  20133. let layer = 0; // steps + 1
  20134. let offset = vlen * layer;
  20135. // Bottom faces
  20136. for ( let i = 0; i < flen; i ++ ) {
  20137. const face = faces[ i ];
  20138. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  20139. }
  20140. layer = steps + bevelSegments * 2;
  20141. offset = vlen * layer;
  20142. // Top faces
  20143. for ( let i = 0; i < flen; i ++ ) {
  20144. const face = faces[ i ];
  20145. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  20146. }
  20147. } else {
  20148. // Bottom faces
  20149. for ( let i = 0; i < flen; i ++ ) {
  20150. const face = faces[ i ];
  20151. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  20152. }
  20153. // Top faces
  20154. for ( let i = 0; i < flen; i ++ ) {
  20155. const face = faces[ i ];
  20156. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  20157. }
  20158. }
  20159. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  20160. }
  20161. // Create faces for the z-sides of the shape
  20162. function buildSideFaces() {
  20163. const start = verticesArray.length / 3;
  20164. let layeroffset = 0;
  20165. sidewalls( contour, layeroffset );
  20166. layeroffset += contour.length;
  20167. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  20168. const ahole = holes[ h ];
  20169. sidewalls( ahole, layeroffset );
  20170. //, true
  20171. layeroffset += ahole.length;
  20172. }
  20173. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  20174. }
  20175. function sidewalls( contour, layeroffset ) {
  20176. let i = contour.length;
  20177. while ( -- i >= 0 ) {
  20178. const j = i;
  20179. let k = i - 1;
  20180. if ( k < 0 ) k = contour.length - 1;
  20181. //console.log('b', i,j, i-1, k,vertices.length);
  20182. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  20183. const slen1 = vlen * s;
  20184. const slen2 = vlen * ( s + 1 );
  20185. const a = layeroffset + j + slen1,
  20186. b = layeroffset + k + slen1,
  20187. c = layeroffset + k + slen2,
  20188. d = layeroffset + j + slen2;
  20189. f4( a, b, c, d );
  20190. }
  20191. }
  20192. }
  20193. function v( x, y, z ) {
  20194. placeholder.push( x );
  20195. placeholder.push( y );
  20196. placeholder.push( z );
  20197. }
  20198. function f3( a, b, c ) {
  20199. addVertex( a );
  20200. addVertex( b );
  20201. addVertex( c );
  20202. const nextIndex = verticesArray.length / 3;
  20203. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  20204. addUV( uvs[ 0 ] );
  20205. addUV( uvs[ 1 ] );
  20206. addUV( uvs[ 2 ] );
  20207. }
  20208. function f4( a, b, c, d ) {
  20209. addVertex( a );
  20210. addVertex( b );
  20211. addVertex( d );
  20212. addVertex( b );
  20213. addVertex( c );
  20214. addVertex( d );
  20215. const nextIndex = verticesArray.length / 3;
  20216. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  20217. addUV( uvs[ 0 ] );
  20218. addUV( uvs[ 1 ] );
  20219. addUV( uvs[ 3 ] );
  20220. addUV( uvs[ 1 ] );
  20221. addUV( uvs[ 2 ] );
  20222. addUV( uvs[ 3 ] );
  20223. }
  20224. function addVertex( index ) {
  20225. verticesArray.push( placeholder[ index * 3 + 0 ] );
  20226. verticesArray.push( placeholder[ index * 3 + 1 ] );
  20227. verticesArray.push( placeholder[ index * 3 + 2 ] );
  20228. }
  20229. function addUV( vector2 ) {
  20230. uvArray.push( vector2.x );
  20231. uvArray.push( vector2.y );
  20232. }
  20233. }
  20234. }
  20235. toJSON() {
  20236. const data = super.toJSON();
  20237. const shapes = this.parameters.shapes;
  20238. const options = this.parameters.options;
  20239. return toJSON$1( shapes, options, data );
  20240. }
  20241. static fromJSON( data, shapes ) {
  20242. const geometryShapes = [];
  20243. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  20244. const shape = shapes[ data.shapes[ j ] ];
  20245. geometryShapes.push( shape );
  20246. }
  20247. const extrudePath = data.options.extrudePath;
  20248. if ( extrudePath !== undefined ) {
  20249. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  20250. }
  20251. return new ExtrudeGeometry( geometryShapes, data.options );
  20252. }
  20253. }
  20254. const WorldUVGenerator = {
  20255. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  20256. const a_x = vertices[ indexA * 3 ];
  20257. const a_y = vertices[ indexA * 3 + 1 ];
  20258. const b_x = vertices[ indexB * 3 ];
  20259. const b_y = vertices[ indexB * 3 + 1 ];
  20260. const c_x = vertices[ indexC * 3 ];
  20261. const c_y = vertices[ indexC * 3 + 1 ];
  20262. return [
  20263. new Vector2( a_x, a_y ),
  20264. new Vector2( b_x, b_y ),
  20265. new Vector2( c_x, c_y )
  20266. ];
  20267. },
  20268. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  20269. const a_x = vertices[ indexA * 3 ];
  20270. const a_y = vertices[ indexA * 3 + 1 ];
  20271. const a_z = vertices[ indexA * 3 + 2 ];
  20272. const b_x = vertices[ indexB * 3 ];
  20273. const b_y = vertices[ indexB * 3 + 1 ];
  20274. const b_z = vertices[ indexB * 3 + 2 ];
  20275. const c_x = vertices[ indexC * 3 ];
  20276. const c_y = vertices[ indexC * 3 + 1 ];
  20277. const c_z = vertices[ indexC * 3 + 2 ];
  20278. const d_x = vertices[ indexD * 3 ];
  20279. const d_y = vertices[ indexD * 3 + 1 ];
  20280. const d_z = vertices[ indexD * 3 + 2 ];
  20281. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  20282. return [
  20283. new Vector2( a_x, 1 - a_z ),
  20284. new Vector2( b_x, 1 - b_z ),
  20285. new Vector2( c_x, 1 - c_z ),
  20286. new Vector2( d_x, 1 - d_z )
  20287. ];
  20288. } else {
  20289. return [
  20290. new Vector2( a_y, 1 - a_z ),
  20291. new Vector2( b_y, 1 - b_z ),
  20292. new Vector2( c_y, 1 - c_z ),
  20293. new Vector2( d_y, 1 - d_z )
  20294. ];
  20295. }
  20296. }
  20297. };
  20298. function toJSON$1( shapes, options, data ) {
  20299. data.shapes = [];
  20300. if ( Array.isArray( shapes ) ) {
  20301. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  20302. const shape = shapes[ i ];
  20303. data.shapes.push( shape.uuid );
  20304. }
  20305. } else {
  20306. data.shapes.push( shapes.uuid );
  20307. }
  20308. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  20309. return data;
  20310. }
  20311. class IcosahedronGeometry extends PolyhedronGeometry {
  20312. constructor( radius = 1, detail = 0 ) {
  20313. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20314. const vertices = [
  20315. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  20316. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  20317. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  20318. ];
  20319. const indices = [
  20320. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  20321. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  20322. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  20323. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  20324. ];
  20325. super( vertices, indices, radius, detail );
  20326. this.type = 'IcosahedronGeometry';
  20327. this.parameters = {
  20328. radius: radius,
  20329. detail: detail
  20330. };
  20331. }
  20332. static fromJSON( data ) {
  20333. return new IcosahedronGeometry( data.radius, data.detail );
  20334. }
  20335. }
  20336. class LatheGeometry extends BufferGeometry {
  20337. constructor( points = [ new Vector2( 0, 0.5 ), new Vector2( 0.5, 0 ), new Vector2( 0, - 0.5 ) ], segments = 12, phiStart = 0, phiLength = Math.PI * 2 ) {
  20338. super();
  20339. this.type = 'LatheGeometry';
  20340. this.parameters = {
  20341. points: points,
  20342. segments: segments,
  20343. phiStart: phiStart,
  20344. phiLength: phiLength
  20345. };
  20346. segments = Math.floor( segments );
  20347. // clamp phiLength so it's in range of [ 0, 2PI ]
  20348. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  20349. // buffers
  20350. const indices = [];
  20351. const vertices = [];
  20352. const uvs = [];
  20353. // helper variables
  20354. const inverseSegments = 1.0 / segments;
  20355. const vertex = new Vector3();
  20356. const uv = new Vector2();
  20357. // generate vertices and uvs
  20358. for ( let i = 0; i <= segments; i ++ ) {
  20359. const phi = phiStart + i * inverseSegments * phiLength;
  20360. const sin = Math.sin( phi );
  20361. const cos = Math.cos( phi );
  20362. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  20363. // vertex
  20364. vertex.x = points[ j ].x * sin;
  20365. vertex.y = points[ j ].y;
  20366. vertex.z = points[ j ].x * cos;
  20367. vertices.push( vertex.x, vertex.y, vertex.z );
  20368. // uv
  20369. uv.x = i / segments;
  20370. uv.y = j / ( points.length - 1 );
  20371. uvs.push( uv.x, uv.y );
  20372. }
  20373. }
  20374. // indices
  20375. for ( let i = 0; i < segments; i ++ ) {
  20376. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  20377. const base = j + i * points.length;
  20378. const a = base;
  20379. const b = base + points.length;
  20380. const c = base + points.length + 1;
  20381. const d = base + 1;
  20382. // faces
  20383. indices.push( a, b, d );
  20384. indices.push( b, c, d );
  20385. }
  20386. }
  20387. // build geometry
  20388. this.setIndex( indices );
  20389. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20390. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20391. // generate normals
  20392. this.computeVertexNormals();
  20393. // if the geometry is closed, we need to average the normals along the seam.
  20394. // because the corresponding vertices are identical (but still have different UVs).
  20395. if ( phiLength === Math.PI * 2 ) {
  20396. const normals = this.attributes.normal.array;
  20397. const n1 = new Vector3();
  20398. const n2 = new Vector3();
  20399. const n = new Vector3();
  20400. // this is the buffer offset for the last line of vertices
  20401. const base = segments * points.length * 3;
  20402. for ( let i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  20403. // select the normal of the vertex in the first line
  20404. n1.x = normals[ j + 0 ];
  20405. n1.y = normals[ j + 1 ];
  20406. n1.z = normals[ j + 2 ];
  20407. // select the normal of the vertex in the last line
  20408. n2.x = normals[ base + j + 0 ];
  20409. n2.y = normals[ base + j + 1 ];
  20410. n2.z = normals[ base + j + 2 ];
  20411. // average normals
  20412. n.addVectors( n1, n2 ).normalize();
  20413. // assign the new values to both normals
  20414. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  20415. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  20416. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  20417. }
  20418. }
  20419. }
  20420. static fromJSON( data ) {
  20421. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  20422. }
  20423. }
  20424. class OctahedronGeometry extends PolyhedronGeometry {
  20425. constructor( radius = 1, detail = 0 ) {
  20426. const vertices = [
  20427. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  20428. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  20429. ];
  20430. const indices = [
  20431. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  20432. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  20433. 1, 3, 4, 1, 4, 2
  20434. ];
  20435. super( vertices, indices, radius, detail );
  20436. this.type = 'OctahedronGeometry';
  20437. this.parameters = {
  20438. radius: radius,
  20439. detail: detail
  20440. };
  20441. }
  20442. static fromJSON( data ) {
  20443. return new OctahedronGeometry( data.radius, data.detail );
  20444. }
  20445. }
  20446. class RingGeometry extends BufferGeometry {
  20447. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  20448. super();
  20449. this.type = 'RingGeometry';
  20450. this.parameters = {
  20451. innerRadius: innerRadius,
  20452. outerRadius: outerRadius,
  20453. thetaSegments: thetaSegments,
  20454. phiSegments: phiSegments,
  20455. thetaStart: thetaStart,
  20456. thetaLength: thetaLength
  20457. };
  20458. thetaSegments = Math.max( 3, thetaSegments );
  20459. phiSegments = Math.max( 1, phiSegments );
  20460. // buffers
  20461. const indices = [];
  20462. const vertices = [];
  20463. const normals = [];
  20464. const uvs = [];
  20465. // some helper variables
  20466. let radius = innerRadius;
  20467. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  20468. const vertex = new Vector3();
  20469. const uv = new Vector2();
  20470. // generate vertices, normals and uvs
  20471. for ( let j = 0; j <= phiSegments; j ++ ) {
  20472. for ( let i = 0; i <= thetaSegments; i ++ ) {
  20473. // values are generate from the inside of the ring to the outside
  20474. const segment = thetaStart + i / thetaSegments * thetaLength;
  20475. // vertex
  20476. vertex.x = radius * Math.cos( segment );
  20477. vertex.y = radius * Math.sin( segment );
  20478. vertices.push( vertex.x, vertex.y, vertex.z );
  20479. // normal
  20480. normals.push( 0, 0, 1 );
  20481. // uv
  20482. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  20483. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  20484. uvs.push( uv.x, uv.y );
  20485. }
  20486. // increase the radius for next row of vertices
  20487. radius += radiusStep;
  20488. }
  20489. // indices
  20490. for ( let j = 0; j < phiSegments; j ++ ) {
  20491. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  20492. for ( let i = 0; i < thetaSegments; i ++ ) {
  20493. const segment = i + thetaSegmentLevel;
  20494. const a = segment;
  20495. const b = segment + thetaSegments + 1;
  20496. const c = segment + thetaSegments + 2;
  20497. const d = segment + 1;
  20498. // faces
  20499. indices.push( a, b, d );
  20500. indices.push( b, c, d );
  20501. }
  20502. }
  20503. // build geometry
  20504. this.setIndex( indices );
  20505. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20506. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20507. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20508. }
  20509. static fromJSON( data ) {
  20510. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  20511. }
  20512. }
  20513. class ShapeGeometry extends BufferGeometry {
  20514. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  20515. super();
  20516. this.type = 'ShapeGeometry';
  20517. this.parameters = {
  20518. shapes: shapes,
  20519. curveSegments: curveSegments
  20520. };
  20521. // buffers
  20522. const indices = [];
  20523. const vertices = [];
  20524. const normals = [];
  20525. const uvs = [];
  20526. // helper variables
  20527. let groupStart = 0;
  20528. let groupCount = 0;
  20529. // allow single and array values for "shapes" parameter
  20530. if ( Array.isArray( shapes ) === false ) {
  20531. addShape( shapes );
  20532. } else {
  20533. for ( let i = 0; i < shapes.length; i ++ ) {
  20534. addShape( shapes[ i ] );
  20535. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  20536. groupStart += groupCount;
  20537. groupCount = 0;
  20538. }
  20539. }
  20540. // build geometry
  20541. this.setIndex( indices );
  20542. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20543. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20544. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20545. // helper functions
  20546. function addShape( shape ) {
  20547. const indexOffset = vertices.length / 3;
  20548. const points = shape.extractPoints( curveSegments );
  20549. let shapeVertices = points.shape;
  20550. const shapeHoles = points.holes;
  20551. // check direction of vertices
  20552. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  20553. shapeVertices = shapeVertices.reverse();
  20554. }
  20555. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  20556. const shapeHole = shapeHoles[ i ];
  20557. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  20558. shapeHoles[ i ] = shapeHole.reverse();
  20559. }
  20560. }
  20561. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  20562. // join vertices of inner and outer paths to a single array
  20563. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  20564. const shapeHole = shapeHoles[ i ];
  20565. shapeVertices = shapeVertices.concat( shapeHole );
  20566. }
  20567. // vertices, normals, uvs
  20568. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  20569. const vertex = shapeVertices[ i ];
  20570. vertices.push( vertex.x, vertex.y, 0 );
  20571. normals.push( 0, 0, 1 );
  20572. uvs.push( vertex.x, vertex.y ); // world uvs
  20573. }
  20574. // incides
  20575. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  20576. const face = faces[ i ];
  20577. const a = face[ 0 ] + indexOffset;
  20578. const b = face[ 1 ] + indexOffset;
  20579. const c = face[ 2 ] + indexOffset;
  20580. indices.push( a, b, c );
  20581. groupCount += 3;
  20582. }
  20583. }
  20584. }
  20585. toJSON() {
  20586. const data = super.toJSON();
  20587. const shapes = this.parameters.shapes;
  20588. return toJSON( shapes, data );
  20589. }
  20590. static fromJSON( data, shapes ) {
  20591. const geometryShapes = [];
  20592. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  20593. const shape = shapes[ data.shapes[ j ] ];
  20594. geometryShapes.push( shape );
  20595. }
  20596. return new ShapeGeometry( geometryShapes, data.curveSegments );
  20597. }
  20598. }
  20599. function toJSON( shapes, data ) {
  20600. data.shapes = [];
  20601. if ( Array.isArray( shapes ) ) {
  20602. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  20603. const shape = shapes[ i ];
  20604. data.shapes.push( shape.uuid );
  20605. }
  20606. } else {
  20607. data.shapes.push( shapes.uuid );
  20608. }
  20609. return data;
  20610. }
  20611. class SphereGeometry extends BufferGeometry {
  20612. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  20613. super();
  20614. this.type = 'SphereGeometry';
  20615. this.parameters = {
  20616. radius: radius,
  20617. widthSegments: widthSegments,
  20618. heightSegments: heightSegments,
  20619. phiStart: phiStart,
  20620. phiLength: phiLength,
  20621. thetaStart: thetaStart,
  20622. thetaLength: thetaLength
  20623. };
  20624. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  20625. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  20626. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  20627. let index = 0;
  20628. const grid = [];
  20629. const vertex = new Vector3();
  20630. const normal = new Vector3();
  20631. // buffers
  20632. const indices = [];
  20633. const vertices = [];
  20634. const normals = [];
  20635. const uvs = [];
  20636. // generate vertices, normals and uvs
  20637. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  20638. const verticesRow = [];
  20639. const v = iy / heightSegments;
  20640. // special case for the poles
  20641. let uOffset = 0;
  20642. if ( iy == 0 && thetaStart == 0 ) {
  20643. uOffset = 0.5 / widthSegments;
  20644. } else if ( iy == heightSegments && thetaEnd == Math.PI ) {
  20645. uOffset = - 0.5 / widthSegments;
  20646. }
  20647. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  20648. const u = ix / widthSegments;
  20649. // vertex
  20650. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  20651. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  20652. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  20653. vertices.push( vertex.x, vertex.y, vertex.z );
  20654. // normal
  20655. normal.copy( vertex ).normalize();
  20656. normals.push( normal.x, normal.y, normal.z );
  20657. // uv
  20658. uvs.push( u + uOffset, 1 - v );
  20659. verticesRow.push( index ++ );
  20660. }
  20661. grid.push( verticesRow );
  20662. }
  20663. // indices
  20664. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  20665. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  20666. const a = grid[ iy ][ ix + 1 ];
  20667. const b = grid[ iy ][ ix ];
  20668. const c = grid[ iy + 1 ][ ix ];
  20669. const d = grid[ iy + 1 ][ ix + 1 ];
  20670. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  20671. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  20672. }
  20673. }
  20674. // build geometry
  20675. this.setIndex( indices );
  20676. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20677. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20678. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20679. }
  20680. static fromJSON( data ) {
  20681. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  20682. }
  20683. }
  20684. class TetrahedronGeometry extends PolyhedronGeometry {
  20685. constructor( radius = 1, detail = 0 ) {
  20686. const vertices = [
  20687. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  20688. ];
  20689. const indices = [
  20690. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  20691. ];
  20692. super( vertices, indices, radius, detail );
  20693. this.type = 'TetrahedronGeometry';
  20694. this.parameters = {
  20695. radius: radius,
  20696. detail: detail
  20697. };
  20698. }
  20699. static fromJSON( data ) {
  20700. return new TetrahedronGeometry( data.radius, data.detail );
  20701. }
  20702. }
  20703. class TorusGeometry extends BufferGeometry {
  20704. constructor( radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2 ) {
  20705. super();
  20706. this.type = 'TorusGeometry';
  20707. this.parameters = {
  20708. radius: radius,
  20709. tube: tube,
  20710. radialSegments: radialSegments,
  20711. tubularSegments: tubularSegments,
  20712. arc: arc
  20713. };
  20714. radialSegments = Math.floor( radialSegments );
  20715. tubularSegments = Math.floor( tubularSegments );
  20716. // buffers
  20717. const indices = [];
  20718. const vertices = [];
  20719. const normals = [];
  20720. const uvs = [];
  20721. // helper variables
  20722. const center = new Vector3();
  20723. const vertex = new Vector3();
  20724. const normal = new Vector3();
  20725. // generate vertices, normals and uvs
  20726. for ( let j = 0; j <= radialSegments; j ++ ) {
  20727. for ( let i = 0; i <= tubularSegments; i ++ ) {
  20728. const u = i / tubularSegments * arc;
  20729. const v = j / radialSegments * Math.PI * 2;
  20730. // vertex
  20731. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  20732. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  20733. vertex.z = tube * Math.sin( v );
  20734. vertices.push( vertex.x, vertex.y, vertex.z );
  20735. // normal
  20736. center.x = radius * Math.cos( u );
  20737. center.y = radius * Math.sin( u );
  20738. normal.subVectors( vertex, center ).normalize();
  20739. normals.push( normal.x, normal.y, normal.z );
  20740. // uv
  20741. uvs.push( i / tubularSegments );
  20742. uvs.push( j / radialSegments );
  20743. }
  20744. }
  20745. // generate indices
  20746. for ( let j = 1; j <= radialSegments; j ++ ) {
  20747. for ( let i = 1; i <= tubularSegments; i ++ ) {
  20748. // indices
  20749. const a = ( tubularSegments + 1 ) * j + i - 1;
  20750. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  20751. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  20752. const d = ( tubularSegments + 1 ) * j + i;
  20753. // faces
  20754. indices.push( a, b, d );
  20755. indices.push( b, c, d );
  20756. }
  20757. }
  20758. // build geometry
  20759. this.setIndex( indices );
  20760. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20761. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20762. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20763. }
  20764. static fromJSON( data ) {
  20765. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  20766. }
  20767. }
  20768. class TorusKnotGeometry extends BufferGeometry {
  20769. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  20770. super();
  20771. this.type = 'TorusKnotGeometry';
  20772. this.parameters = {
  20773. radius: radius,
  20774. tube: tube,
  20775. tubularSegments: tubularSegments,
  20776. radialSegments: radialSegments,
  20777. p: p,
  20778. q: q
  20779. };
  20780. tubularSegments = Math.floor( tubularSegments );
  20781. radialSegments = Math.floor( radialSegments );
  20782. // buffers
  20783. const indices = [];
  20784. const vertices = [];
  20785. const normals = [];
  20786. const uvs = [];
  20787. // helper variables
  20788. const vertex = new Vector3();
  20789. const normal = new Vector3();
  20790. const P1 = new Vector3();
  20791. const P2 = new Vector3();
  20792. const B = new Vector3();
  20793. const T = new Vector3();
  20794. const N = new Vector3();
  20795. // generate vertices, normals and uvs
  20796. for ( let i = 0; i <= tubularSegments; ++ i ) {
  20797. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  20798. const u = i / tubularSegments * p * Math.PI * 2;
  20799. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  20800. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  20801. calculatePositionOnCurve( u, p, q, radius, P1 );
  20802. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  20803. // calculate orthonormal basis
  20804. T.subVectors( P2, P1 );
  20805. N.addVectors( P2, P1 );
  20806. B.crossVectors( T, N );
  20807. N.crossVectors( B, T );
  20808. // normalize B, N. T can be ignored, we don't use it
  20809. B.normalize();
  20810. N.normalize();
  20811. for ( let j = 0; j <= radialSegments; ++ j ) {
  20812. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  20813. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  20814. const v = j / radialSegments * Math.PI * 2;
  20815. const cx = - tube * Math.cos( v );
  20816. const cy = tube * Math.sin( v );
  20817. // now calculate the final vertex position.
  20818. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  20819. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  20820. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  20821. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  20822. vertices.push( vertex.x, vertex.y, vertex.z );
  20823. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  20824. normal.subVectors( vertex, P1 ).normalize();
  20825. normals.push( normal.x, normal.y, normal.z );
  20826. // uv
  20827. uvs.push( i / tubularSegments );
  20828. uvs.push( j / radialSegments );
  20829. }
  20830. }
  20831. // generate indices
  20832. for ( let j = 1; j <= tubularSegments; j ++ ) {
  20833. for ( let i = 1; i <= radialSegments; i ++ ) {
  20834. // indices
  20835. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  20836. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  20837. const c = ( radialSegments + 1 ) * j + i;
  20838. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  20839. // faces
  20840. indices.push( a, b, d );
  20841. indices.push( b, c, d );
  20842. }
  20843. }
  20844. // build geometry
  20845. this.setIndex( indices );
  20846. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20847. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20848. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20849. // this function calculates the current position on the torus curve
  20850. function calculatePositionOnCurve( u, p, q, radius, position ) {
  20851. const cu = Math.cos( u );
  20852. const su = Math.sin( u );
  20853. const quOverP = q / p * u;
  20854. const cs = Math.cos( quOverP );
  20855. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  20856. position.y = radius * ( 2 + cs ) * su * 0.5;
  20857. position.z = radius * Math.sin( quOverP ) * 0.5;
  20858. }
  20859. }
  20860. static fromJSON( data ) {
  20861. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  20862. }
  20863. }
  20864. class TubeGeometry extends BufferGeometry {
  20865. constructor( path = new QuadraticBezierCurve3( new Vector3( - 1, - 1, 0 ), new Vector3( - 1, 1, 0 ), new Vector3( 1, 1, 0 ) ), tubularSegments = 64, radius = 1, radialSegments = 8, closed = false ) {
  20866. super();
  20867. this.type = 'TubeGeometry';
  20868. this.parameters = {
  20869. path: path,
  20870. tubularSegments: tubularSegments,
  20871. radius: radius,
  20872. radialSegments: radialSegments,
  20873. closed: closed
  20874. };
  20875. const frames = path.computeFrenetFrames( tubularSegments, closed );
  20876. // expose internals
  20877. this.tangents = frames.tangents;
  20878. this.normals = frames.normals;
  20879. this.binormals = frames.binormals;
  20880. // helper variables
  20881. const vertex = new Vector3();
  20882. const normal = new Vector3();
  20883. const uv = new Vector2();
  20884. let P = new Vector3();
  20885. // buffer
  20886. const vertices = [];
  20887. const normals = [];
  20888. const uvs = [];
  20889. const indices = [];
  20890. // create buffer data
  20891. generateBufferData();
  20892. // build geometry
  20893. this.setIndex( indices );
  20894. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20895. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20896. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20897. // functions
  20898. function generateBufferData() {
  20899. for ( let i = 0; i < tubularSegments; i ++ ) {
  20900. generateSegment( i );
  20901. }
  20902. // if the geometry is not closed, generate the last row of vertices and normals
  20903. // at the regular position on the given path
  20904. //
  20905. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  20906. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  20907. // uvs are generated in a separate function.
  20908. // this makes it easy compute correct values for closed geometries
  20909. generateUVs();
  20910. // finally create faces
  20911. generateIndices();
  20912. }
  20913. function generateSegment( i ) {
  20914. // we use getPointAt to sample evenly distributed points from the given path
  20915. P = path.getPointAt( i / tubularSegments, P );
  20916. // retrieve corresponding normal and binormal
  20917. const N = frames.normals[ i ];
  20918. const B = frames.binormals[ i ];
  20919. // generate normals and vertices for the current segment
  20920. for ( let j = 0; j <= radialSegments; j ++ ) {
  20921. const v = j / radialSegments * Math.PI * 2;
  20922. const sin = Math.sin( v );
  20923. const cos = - Math.cos( v );
  20924. // normal
  20925. normal.x = ( cos * N.x + sin * B.x );
  20926. normal.y = ( cos * N.y + sin * B.y );
  20927. normal.z = ( cos * N.z + sin * B.z );
  20928. normal.normalize();
  20929. normals.push( normal.x, normal.y, normal.z );
  20930. // vertex
  20931. vertex.x = P.x + radius * normal.x;
  20932. vertex.y = P.y + radius * normal.y;
  20933. vertex.z = P.z + radius * normal.z;
  20934. vertices.push( vertex.x, vertex.y, vertex.z );
  20935. }
  20936. }
  20937. function generateIndices() {
  20938. for ( let j = 1; j <= tubularSegments; j ++ ) {
  20939. for ( let i = 1; i <= radialSegments; i ++ ) {
  20940. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  20941. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  20942. const c = ( radialSegments + 1 ) * j + i;
  20943. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  20944. // faces
  20945. indices.push( a, b, d );
  20946. indices.push( b, c, d );
  20947. }
  20948. }
  20949. }
  20950. function generateUVs() {
  20951. for ( let i = 0; i <= tubularSegments; i ++ ) {
  20952. for ( let j = 0; j <= radialSegments; j ++ ) {
  20953. uv.x = i / tubularSegments;
  20954. uv.y = j / radialSegments;
  20955. uvs.push( uv.x, uv.y );
  20956. }
  20957. }
  20958. }
  20959. }
  20960. toJSON() {
  20961. const data = super.toJSON();
  20962. data.path = this.parameters.path.toJSON();
  20963. return data;
  20964. }
  20965. static fromJSON( data ) {
  20966. // This only works for built-in curves (e.g. CatmullRomCurve3).
  20967. // User defined curves or instances of CurvePath will not be deserialized.
  20968. return new TubeGeometry(
  20969. new Curves[ data.path.type ]().fromJSON( data.path ),
  20970. data.tubularSegments,
  20971. data.radius,
  20972. data.radialSegments,
  20973. data.closed
  20974. );
  20975. }
  20976. }
  20977. class WireframeGeometry extends BufferGeometry {
  20978. constructor( geometry = null ) {
  20979. super();
  20980. this.type = 'WireframeGeometry';
  20981. this.parameters = {
  20982. geometry: geometry
  20983. };
  20984. if ( geometry !== null ) {
  20985. // buffer
  20986. const vertices = [];
  20987. const edges = new Set();
  20988. // helper variables
  20989. const start = new Vector3();
  20990. const end = new Vector3();
  20991. if ( geometry.index !== null ) {
  20992. // indexed BufferGeometry
  20993. const position = geometry.attributes.position;
  20994. const indices = geometry.index;
  20995. let groups = geometry.groups;
  20996. if ( groups.length === 0 ) {
  20997. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  20998. }
  20999. // create a data structure that contains all eges without duplicates
  21000. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  21001. const group = groups[ o ];
  21002. const groupStart = group.start;
  21003. const groupCount = group.count;
  21004. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  21005. for ( let j = 0; j < 3; j ++ ) {
  21006. const index1 = indices.getX( i + j );
  21007. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  21008. start.fromBufferAttribute( position, index1 );
  21009. end.fromBufferAttribute( position, index2 );
  21010. if ( isUniqueEdge( start, end, edges ) === true ) {
  21011. vertices.push( start.x, start.y, start.z );
  21012. vertices.push( end.x, end.y, end.z );
  21013. }
  21014. }
  21015. }
  21016. }
  21017. } else {
  21018. // non-indexed BufferGeometry
  21019. const position = geometry.attributes.position;
  21020. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  21021. for ( let j = 0; j < 3; j ++ ) {
  21022. // three edges per triangle, an edge is represented as (index1, index2)
  21023. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  21024. const index1 = 3 * i + j;
  21025. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  21026. start.fromBufferAttribute( position, index1 );
  21027. end.fromBufferAttribute( position, index2 );
  21028. if ( isUniqueEdge( start, end, edges ) === true ) {
  21029. vertices.push( start.x, start.y, start.z );
  21030. vertices.push( end.x, end.y, end.z );
  21031. }
  21032. }
  21033. }
  21034. }
  21035. // build geometry
  21036. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21037. }
  21038. }
  21039. }
  21040. function isUniqueEdge( start, end, edges ) {
  21041. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  21042. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  21043. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  21044. return false;
  21045. } else {
  21046. edges.add( hash1, hash2 );
  21047. return true;
  21048. }
  21049. }
  21050. var Geometries = /*#__PURE__*/Object.freeze({
  21051. __proto__: null,
  21052. BoxGeometry: BoxGeometry,
  21053. BoxBufferGeometry: BoxGeometry,
  21054. CircleGeometry: CircleGeometry,
  21055. CircleBufferGeometry: CircleGeometry,
  21056. ConeGeometry: ConeGeometry,
  21057. ConeBufferGeometry: ConeGeometry,
  21058. CylinderGeometry: CylinderGeometry,
  21059. CylinderBufferGeometry: CylinderGeometry,
  21060. DodecahedronGeometry: DodecahedronGeometry,
  21061. DodecahedronBufferGeometry: DodecahedronGeometry,
  21062. EdgesGeometry: EdgesGeometry,
  21063. ExtrudeGeometry: ExtrudeGeometry,
  21064. ExtrudeBufferGeometry: ExtrudeGeometry,
  21065. IcosahedronGeometry: IcosahedronGeometry,
  21066. IcosahedronBufferGeometry: IcosahedronGeometry,
  21067. LatheGeometry: LatheGeometry,
  21068. LatheBufferGeometry: LatheGeometry,
  21069. OctahedronGeometry: OctahedronGeometry,
  21070. OctahedronBufferGeometry: OctahedronGeometry,
  21071. PlaneGeometry: PlaneGeometry,
  21072. PlaneBufferGeometry: PlaneGeometry,
  21073. PolyhedronGeometry: PolyhedronGeometry,
  21074. PolyhedronBufferGeometry: PolyhedronGeometry,
  21075. RingGeometry: RingGeometry,
  21076. RingBufferGeometry: RingGeometry,
  21077. ShapeGeometry: ShapeGeometry,
  21078. ShapeBufferGeometry: ShapeGeometry,
  21079. SphereGeometry: SphereGeometry,
  21080. SphereBufferGeometry: SphereGeometry,
  21081. TetrahedronGeometry: TetrahedronGeometry,
  21082. TetrahedronBufferGeometry: TetrahedronGeometry,
  21083. TorusGeometry: TorusGeometry,
  21084. TorusBufferGeometry: TorusGeometry,
  21085. TorusKnotGeometry: TorusKnotGeometry,
  21086. TorusKnotBufferGeometry: TorusKnotGeometry,
  21087. TubeGeometry: TubeGeometry,
  21088. TubeBufferGeometry: TubeGeometry,
  21089. WireframeGeometry: WireframeGeometry
  21090. });
  21091. /**
  21092. * parameters = {
  21093. * color: <THREE.Color>
  21094. * }
  21095. */
  21096. class ShadowMaterial extends Material {
  21097. constructor( parameters ) {
  21098. super();
  21099. this.type = 'ShadowMaterial';
  21100. this.color = new Color( 0x000000 );
  21101. this.transparent = true;
  21102. this.setValues( parameters );
  21103. }
  21104. copy( source ) {
  21105. super.copy( source );
  21106. this.color.copy( source.color );
  21107. return this;
  21108. }
  21109. }
  21110. ShadowMaterial.prototype.isShadowMaterial = true;
  21111. /**
  21112. * parameters = {
  21113. * color: <hex>,
  21114. * roughness: <float>,
  21115. * metalness: <float>,
  21116. * opacity: <float>,
  21117. *
  21118. * map: new THREE.Texture( <Image> ),
  21119. *
  21120. * lightMap: new THREE.Texture( <Image> ),
  21121. * lightMapIntensity: <float>
  21122. *
  21123. * aoMap: new THREE.Texture( <Image> ),
  21124. * aoMapIntensity: <float>
  21125. *
  21126. * emissive: <hex>,
  21127. * emissiveIntensity: <float>
  21128. * emissiveMap: new THREE.Texture( <Image> ),
  21129. *
  21130. * bumpMap: new THREE.Texture( <Image> ),
  21131. * bumpScale: <float>,
  21132. *
  21133. * normalMap: new THREE.Texture( <Image> ),
  21134. * normalMapType: THREE.TangentSpaceNormalMap,
  21135. * normalScale: <Vector2>,
  21136. *
  21137. * displacementMap: new THREE.Texture( <Image> ),
  21138. * displacementScale: <float>,
  21139. * displacementBias: <float>,
  21140. *
  21141. * roughnessMap: new THREE.Texture( <Image> ),
  21142. *
  21143. * metalnessMap: new THREE.Texture( <Image> ),
  21144. *
  21145. * alphaMap: new THREE.Texture( <Image> ),
  21146. *
  21147. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  21148. * envMapIntensity: <float>
  21149. *
  21150. * refractionRatio: <float>,
  21151. *
  21152. * wireframe: <boolean>,
  21153. * wireframeLinewidth: <float>,
  21154. *
  21155. * flatShading: <bool>
  21156. * }
  21157. */
  21158. class MeshStandardMaterial extends Material {
  21159. constructor( parameters ) {
  21160. super();
  21161. this.defines = { 'STANDARD': '' };
  21162. this.type = 'MeshStandardMaterial';
  21163. this.color = new Color( 0xffffff ); // diffuse
  21164. this.roughness = 1.0;
  21165. this.metalness = 0.0;
  21166. this.map = null;
  21167. this.lightMap = null;
  21168. this.lightMapIntensity = 1.0;
  21169. this.aoMap = null;
  21170. this.aoMapIntensity = 1.0;
  21171. this.emissive = new Color( 0x000000 );
  21172. this.emissiveIntensity = 1.0;
  21173. this.emissiveMap = null;
  21174. this.bumpMap = null;
  21175. this.bumpScale = 1;
  21176. this.normalMap = null;
  21177. this.normalMapType = TangentSpaceNormalMap;
  21178. this.normalScale = new Vector2( 1, 1 );
  21179. this.displacementMap = null;
  21180. this.displacementScale = 1;
  21181. this.displacementBias = 0;
  21182. this.roughnessMap = null;
  21183. this.metalnessMap = null;
  21184. this.alphaMap = null;
  21185. this.envMap = null;
  21186. this.envMapIntensity = 1.0;
  21187. this.refractionRatio = 0.98;
  21188. this.wireframe = false;
  21189. this.wireframeLinewidth = 1;
  21190. this.wireframeLinecap = 'round';
  21191. this.wireframeLinejoin = 'round';
  21192. this.flatShading = false;
  21193. this.setValues( parameters );
  21194. }
  21195. copy( source ) {
  21196. super.copy( source );
  21197. this.defines = { 'STANDARD': '' };
  21198. this.color.copy( source.color );
  21199. this.roughness = source.roughness;
  21200. this.metalness = source.metalness;
  21201. this.map = source.map;
  21202. this.lightMap = source.lightMap;
  21203. this.lightMapIntensity = source.lightMapIntensity;
  21204. this.aoMap = source.aoMap;
  21205. this.aoMapIntensity = source.aoMapIntensity;
  21206. this.emissive.copy( source.emissive );
  21207. this.emissiveMap = source.emissiveMap;
  21208. this.emissiveIntensity = source.emissiveIntensity;
  21209. this.bumpMap = source.bumpMap;
  21210. this.bumpScale = source.bumpScale;
  21211. this.normalMap = source.normalMap;
  21212. this.normalMapType = source.normalMapType;
  21213. this.normalScale.copy( source.normalScale );
  21214. this.displacementMap = source.displacementMap;
  21215. this.displacementScale = source.displacementScale;
  21216. this.displacementBias = source.displacementBias;
  21217. this.roughnessMap = source.roughnessMap;
  21218. this.metalnessMap = source.metalnessMap;
  21219. this.alphaMap = source.alphaMap;
  21220. this.envMap = source.envMap;
  21221. this.envMapIntensity = source.envMapIntensity;
  21222. this.refractionRatio = source.refractionRatio;
  21223. this.wireframe = source.wireframe;
  21224. this.wireframeLinewidth = source.wireframeLinewidth;
  21225. this.wireframeLinecap = source.wireframeLinecap;
  21226. this.wireframeLinejoin = source.wireframeLinejoin;
  21227. this.flatShading = source.flatShading;
  21228. return this;
  21229. }
  21230. }
  21231. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  21232. /**
  21233. * parameters = {
  21234. * clearcoat: <float>,
  21235. * clearcoatMap: new THREE.Texture( <Image> ),
  21236. * clearcoatRoughness: <float>,
  21237. * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
  21238. * clearcoatNormalScale: <Vector2>,
  21239. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  21240. *
  21241. * ior: <float>,
  21242. * reflectivity: <float>,
  21243. *
  21244. * sheen: <float>,
  21245. * sheenTint: <Color>,
  21246. * sheenRoughness: <float>,
  21247. *
  21248. * transmission: <float>,
  21249. * transmissionMap: new THREE.Texture( <Image> ),
  21250. *
  21251. * thickness: <float>,
  21252. * thicknessMap: new THREE.Texture( <Image> ),
  21253. * attenuationDistance: <float>,
  21254. * attenuationTint: <Color>,
  21255. *
  21256. * specularIntensity: <float>,
  21257. * specularIntensityhMap: new THREE.Texture( <Image> ),
  21258. * specularTint: <Color>,
  21259. * specularTintMap: new THREE.Texture( <Image> )
  21260. * }
  21261. */
  21262. class MeshPhysicalMaterial extends MeshStandardMaterial {
  21263. constructor( parameters ) {
  21264. super();
  21265. this.defines = {
  21266. 'STANDARD': '',
  21267. 'PHYSICAL': ''
  21268. };
  21269. this.type = 'MeshPhysicalMaterial';
  21270. this.clearcoatMap = null;
  21271. this.clearcoatRoughness = 0.0;
  21272. this.clearcoatRoughnessMap = null;
  21273. this.clearcoatNormalScale = new Vector2( 1, 1 );
  21274. this.clearcoatNormalMap = null;
  21275. this.ior = 1.5;
  21276. Object.defineProperty( this, 'reflectivity', {
  21277. get: function () {
  21278. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  21279. },
  21280. set: function ( reflectivity ) {
  21281. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  21282. }
  21283. } );
  21284. this.sheenTint = new Color( 0x000000 );
  21285. this.sheenRoughness = 1.0;
  21286. this.transmissionMap = null;
  21287. this.thickness = 0.01;
  21288. this.thicknessMap = null;
  21289. this.attenuationDistance = 0.0;
  21290. this.attenuationTint = new Color( 1, 1, 1 );
  21291. this.specularIntensity = 1.0;
  21292. this.specularIntensityMap = null;
  21293. this.specularTint = new Color( 1, 1, 1 );
  21294. this.specularTintMap = null;
  21295. this._sheen = 0.0;
  21296. this._clearcoat = 0;
  21297. this._transmission = 0;
  21298. this.setValues( parameters );
  21299. }
  21300. get sheen() {
  21301. return this._sheen;
  21302. }
  21303. set sheen( value ) {
  21304. if ( this._sheen > 0 !== value > 0 ) {
  21305. this.version ++;
  21306. }
  21307. this._sheen = value;
  21308. }
  21309. get clearcoat() {
  21310. return this._clearcoat;
  21311. }
  21312. set clearcoat( value ) {
  21313. if ( this._clearcoat > 0 !== value > 0 ) {
  21314. this.version ++;
  21315. }
  21316. this._clearcoat = value;
  21317. }
  21318. get transmission() {
  21319. return this._transmission;
  21320. }
  21321. set transmission( value ) {
  21322. if ( this._transmission > 0 !== value > 0 ) {
  21323. this.version ++;
  21324. }
  21325. this._transmission = value;
  21326. }
  21327. copy( source ) {
  21328. super.copy( source );
  21329. this.defines = {
  21330. 'STANDARD': '',
  21331. 'PHYSICAL': ''
  21332. };
  21333. this.clearcoat = source.clearcoat;
  21334. this.clearcoatMap = source.clearcoatMap;
  21335. this.clearcoatRoughness = source.clearcoatRoughness;
  21336. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  21337. this.clearcoatNormalMap = source.clearcoatNormalMap;
  21338. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  21339. this.ior = source.ior;
  21340. this.sheen = source.sheen;
  21341. this.sheenTint.copy( source.sheenTint );
  21342. this.sheenRoughness = source.sheenRoughness;
  21343. this.transmission = source.transmission;
  21344. this.transmissionMap = source.transmissionMap;
  21345. this.thickness = source.thickness;
  21346. this.thicknessMap = source.thicknessMap;
  21347. this.attenuationDistance = source.attenuationDistance;
  21348. this.attenuationTint.copy( source.attenuationTint );
  21349. this.specularIntensity = source.specularIntensity;
  21350. this.specularIntensityMap = source.specularIntensityMap;
  21351. this.specularTint.copy( source.specularTint );
  21352. this.specularTintMap = source.specularTintMap;
  21353. return this;
  21354. }
  21355. }
  21356. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  21357. /**
  21358. * parameters = {
  21359. * color: <hex>,
  21360. * specular: <hex>,
  21361. * shininess: <float>,
  21362. * opacity: <float>,
  21363. *
  21364. * map: new THREE.Texture( <Image> ),
  21365. *
  21366. * lightMap: new THREE.Texture( <Image> ),
  21367. * lightMapIntensity: <float>
  21368. *
  21369. * aoMap: new THREE.Texture( <Image> ),
  21370. * aoMapIntensity: <float>
  21371. *
  21372. * emissive: <hex>,
  21373. * emissiveIntensity: <float>
  21374. * emissiveMap: new THREE.Texture( <Image> ),
  21375. *
  21376. * bumpMap: new THREE.Texture( <Image> ),
  21377. * bumpScale: <float>,
  21378. *
  21379. * normalMap: new THREE.Texture( <Image> ),
  21380. * normalMapType: THREE.TangentSpaceNormalMap,
  21381. * normalScale: <Vector2>,
  21382. *
  21383. * displacementMap: new THREE.Texture( <Image> ),
  21384. * displacementScale: <float>,
  21385. * displacementBias: <float>,
  21386. *
  21387. * specularMap: new THREE.Texture( <Image> ),
  21388. *
  21389. * alphaMap: new THREE.Texture( <Image> ),
  21390. *
  21391. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  21392. * combine: THREE.MultiplyOperation,
  21393. * reflectivity: <float>,
  21394. * refractionRatio: <float>,
  21395. *
  21396. * wireframe: <boolean>,
  21397. * wireframeLinewidth: <float>,
  21398. *
  21399. * flatShading: <bool>
  21400. * }
  21401. */
  21402. class MeshPhongMaterial extends Material {
  21403. constructor( parameters ) {
  21404. super();
  21405. this.type = 'MeshPhongMaterial';
  21406. this.color = new Color( 0xffffff ); // diffuse
  21407. this.specular = new Color( 0x111111 );
  21408. this.shininess = 30;
  21409. this.map = null;
  21410. this.lightMap = null;
  21411. this.lightMapIntensity = 1.0;
  21412. this.aoMap = null;
  21413. this.aoMapIntensity = 1.0;
  21414. this.emissive = new Color( 0x000000 );
  21415. this.emissiveIntensity = 1.0;
  21416. this.emissiveMap = null;
  21417. this.bumpMap = null;
  21418. this.bumpScale = 1;
  21419. this.normalMap = null;
  21420. this.normalMapType = TangentSpaceNormalMap;
  21421. this.normalScale = new Vector2( 1, 1 );
  21422. this.displacementMap = null;
  21423. this.displacementScale = 1;
  21424. this.displacementBias = 0;
  21425. this.specularMap = null;
  21426. this.alphaMap = null;
  21427. this.envMap = null;
  21428. this.combine = MultiplyOperation;
  21429. this.reflectivity = 1;
  21430. this.refractionRatio = 0.98;
  21431. this.wireframe = false;
  21432. this.wireframeLinewidth = 1;
  21433. this.wireframeLinecap = 'round';
  21434. this.wireframeLinejoin = 'round';
  21435. this.flatShading = false;
  21436. this.setValues( parameters );
  21437. }
  21438. copy( source ) {
  21439. super.copy( source );
  21440. this.color.copy( source.color );
  21441. this.specular.copy( source.specular );
  21442. this.shininess = source.shininess;
  21443. this.map = source.map;
  21444. this.lightMap = source.lightMap;
  21445. this.lightMapIntensity = source.lightMapIntensity;
  21446. this.aoMap = source.aoMap;
  21447. this.aoMapIntensity = source.aoMapIntensity;
  21448. this.emissive.copy( source.emissive );
  21449. this.emissiveMap = source.emissiveMap;
  21450. this.emissiveIntensity = source.emissiveIntensity;
  21451. this.bumpMap = source.bumpMap;
  21452. this.bumpScale = source.bumpScale;
  21453. this.normalMap = source.normalMap;
  21454. this.normalMapType = source.normalMapType;
  21455. this.normalScale.copy( source.normalScale );
  21456. this.displacementMap = source.displacementMap;
  21457. this.displacementScale = source.displacementScale;
  21458. this.displacementBias = source.displacementBias;
  21459. this.specularMap = source.specularMap;
  21460. this.alphaMap = source.alphaMap;
  21461. this.envMap = source.envMap;
  21462. this.combine = source.combine;
  21463. this.reflectivity = source.reflectivity;
  21464. this.refractionRatio = source.refractionRatio;
  21465. this.wireframe = source.wireframe;
  21466. this.wireframeLinewidth = source.wireframeLinewidth;
  21467. this.wireframeLinecap = source.wireframeLinecap;
  21468. this.wireframeLinejoin = source.wireframeLinejoin;
  21469. this.flatShading = source.flatShading;
  21470. return this;
  21471. }
  21472. }
  21473. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  21474. /**
  21475. * parameters = {
  21476. * color: <hex>,
  21477. *
  21478. * map: new THREE.Texture( <Image> ),
  21479. * gradientMap: new THREE.Texture( <Image> ),
  21480. *
  21481. * lightMap: new THREE.Texture( <Image> ),
  21482. * lightMapIntensity: <float>
  21483. *
  21484. * aoMap: new THREE.Texture( <Image> ),
  21485. * aoMapIntensity: <float>
  21486. *
  21487. * emissive: <hex>,
  21488. * emissiveIntensity: <float>
  21489. * emissiveMap: new THREE.Texture( <Image> ),
  21490. *
  21491. * bumpMap: new THREE.Texture( <Image> ),
  21492. * bumpScale: <float>,
  21493. *
  21494. * normalMap: new THREE.Texture( <Image> ),
  21495. * normalMapType: THREE.TangentSpaceNormalMap,
  21496. * normalScale: <Vector2>,
  21497. *
  21498. * displacementMap: new THREE.Texture( <Image> ),
  21499. * displacementScale: <float>,
  21500. * displacementBias: <float>,
  21501. *
  21502. * alphaMap: new THREE.Texture( <Image> ),
  21503. *
  21504. * wireframe: <boolean>,
  21505. * wireframeLinewidth: <float>,
  21506. *
  21507. * }
  21508. */
  21509. class MeshToonMaterial extends Material {
  21510. constructor( parameters ) {
  21511. super();
  21512. this.defines = { 'TOON': '' };
  21513. this.type = 'MeshToonMaterial';
  21514. this.color = new Color( 0xffffff );
  21515. this.map = null;
  21516. this.gradientMap = null;
  21517. this.lightMap = null;
  21518. this.lightMapIntensity = 1.0;
  21519. this.aoMap = null;
  21520. this.aoMapIntensity = 1.0;
  21521. this.emissive = new Color( 0x000000 );
  21522. this.emissiveIntensity = 1.0;
  21523. this.emissiveMap = null;
  21524. this.bumpMap = null;
  21525. this.bumpScale = 1;
  21526. this.normalMap = null;
  21527. this.normalMapType = TangentSpaceNormalMap;
  21528. this.normalScale = new Vector2( 1, 1 );
  21529. this.displacementMap = null;
  21530. this.displacementScale = 1;
  21531. this.displacementBias = 0;
  21532. this.alphaMap = null;
  21533. this.wireframe = false;
  21534. this.wireframeLinewidth = 1;
  21535. this.wireframeLinecap = 'round';
  21536. this.wireframeLinejoin = 'round';
  21537. this.setValues( parameters );
  21538. }
  21539. copy( source ) {
  21540. super.copy( source );
  21541. this.color.copy( source.color );
  21542. this.map = source.map;
  21543. this.gradientMap = source.gradientMap;
  21544. this.lightMap = source.lightMap;
  21545. this.lightMapIntensity = source.lightMapIntensity;
  21546. this.aoMap = source.aoMap;
  21547. this.aoMapIntensity = source.aoMapIntensity;
  21548. this.emissive.copy( source.emissive );
  21549. this.emissiveMap = source.emissiveMap;
  21550. this.emissiveIntensity = source.emissiveIntensity;
  21551. this.bumpMap = source.bumpMap;
  21552. this.bumpScale = source.bumpScale;
  21553. this.normalMap = source.normalMap;
  21554. this.normalMapType = source.normalMapType;
  21555. this.normalScale.copy( source.normalScale );
  21556. this.displacementMap = source.displacementMap;
  21557. this.displacementScale = source.displacementScale;
  21558. this.displacementBias = source.displacementBias;
  21559. this.alphaMap = source.alphaMap;
  21560. this.wireframe = source.wireframe;
  21561. this.wireframeLinewidth = source.wireframeLinewidth;
  21562. this.wireframeLinecap = source.wireframeLinecap;
  21563. this.wireframeLinejoin = source.wireframeLinejoin;
  21564. return this;
  21565. }
  21566. }
  21567. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  21568. /**
  21569. * parameters = {
  21570. * opacity: <float>,
  21571. *
  21572. * bumpMap: new THREE.Texture( <Image> ),
  21573. * bumpScale: <float>,
  21574. *
  21575. * normalMap: new THREE.Texture( <Image> ),
  21576. * normalMapType: THREE.TangentSpaceNormalMap,
  21577. * normalScale: <Vector2>,
  21578. *
  21579. * displacementMap: new THREE.Texture( <Image> ),
  21580. * displacementScale: <float>,
  21581. * displacementBias: <float>,
  21582. *
  21583. * wireframe: <boolean>,
  21584. * wireframeLinewidth: <float>
  21585. *
  21586. * flatShading: <bool>
  21587. * }
  21588. */
  21589. class MeshNormalMaterial extends Material {
  21590. constructor( parameters ) {
  21591. super();
  21592. this.type = 'MeshNormalMaterial';
  21593. this.bumpMap = null;
  21594. this.bumpScale = 1;
  21595. this.normalMap = null;
  21596. this.normalMapType = TangentSpaceNormalMap;
  21597. this.normalScale = new Vector2( 1, 1 );
  21598. this.displacementMap = null;
  21599. this.displacementScale = 1;
  21600. this.displacementBias = 0;
  21601. this.wireframe = false;
  21602. this.wireframeLinewidth = 1;
  21603. this.fog = false;
  21604. this.flatShading = false;
  21605. this.setValues( parameters );
  21606. }
  21607. copy( source ) {
  21608. super.copy( source );
  21609. this.bumpMap = source.bumpMap;
  21610. this.bumpScale = source.bumpScale;
  21611. this.normalMap = source.normalMap;
  21612. this.normalMapType = source.normalMapType;
  21613. this.normalScale.copy( source.normalScale );
  21614. this.displacementMap = source.displacementMap;
  21615. this.displacementScale = source.displacementScale;
  21616. this.displacementBias = source.displacementBias;
  21617. this.wireframe = source.wireframe;
  21618. this.wireframeLinewidth = source.wireframeLinewidth;
  21619. this.flatShading = source.flatShading;
  21620. return this;
  21621. }
  21622. }
  21623. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  21624. /**
  21625. * parameters = {
  21626. * color: <hex>,
  21627. * opacity: <float>,
  21628. *
  21629. * map: new THREE.Texture( <Image> ),
  21630. *
  21631. * lightMap: new THREE.Texture( <Image> ),
  21632. * lightMapIntensity: <float>
  21633. *
  21634. * aoMap: new THREE.Texture( <Image> ),
  21635. * aoMapIntensity: <float>
  21636. *
  21637. * emissive: <hex>,
  21638. * emissiveIntensity: <float>
  21639. * emissiveMap: new THREE.Texture( <Image> ),
  21640. *
  21641. * specularMap: new THREE.Texture( <Image> ),
  21642. *
  21643. * alphaMap: new THREE.Texture( <Image> ),
  21644. *
  21645. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  21646. * combine: THREE.Multiply,
  21647. * reflectivity: <float>,
  21648. * refractionRatio: <float>,
  21649. *
  21650. * wireframe: <boolean>,
  21651. * wireframeLinewidth: <float>,
  21652. *
  21653. * }
  21654. */
  21655. class MeshLambertMaterial extends Material {
  21656. constructor( parameters ) {
  21657. super();
  21658. this.type = 'MeshLambertMaterial';
  21659. this.color = new Color( 0xffffff ); // diffuse
  21660. this.map = null;
  21661. this.lightMap = null;
  21662. this.lightMapIntensity = 1.0;
  21663. this.aoMap = null;
  21664. this.aoMapIntensity = 1.0;
  21665. this.emissive = new Color( 0x000000 );
  21666. this.emissiveIntensity = 1.0;
  21667. this.emissiveMap = null;
  21668. this.specularMap = null;
  21669. this.alphaMap = null;
  21670. this.envMap = null;
  21671. this.combine = MultiplyOperation;
  21672. this.reflectivity = 1;
  21673. this.refractionRatio = 0.98;
  21674. this.wireframe = false;
  21675. this.wireframeLinewidth = 1;
  21676. this.wireframeLinecap = 'round';
  21677. this.wireframeLinejoin = 'round';
  21678. this.setValues( parameters );
  21679. }
  21680. copy( source ) {
  21681. super.copy( source );
  21682. this.color.copy( source.color );
  21683. this.map = source.map;
  21684. this.lightMap = source.lightMap;
  21685. this.lightMapIntensity = source.lightMapIntensity;
  21686. this.aoMap = source.aoMap;
  21687. this.aoMapIntensity = source.aoMapIntensity;
  21688. this.emissive.copy( source.emissive );
  21689. this.emissiveMap = source.emissiveMap;
  21690. this.emissiveIntensity = source.emissiveIntensity;
  21691. this.specularMap = source.specularMap;
  21692. this.alphaMap = source.alphaMap;
  21693. this.envMap = source.envMap;
  21694. this.combine = source.combine;
  21695. this.reflectivity = source.reflectivity;
  21696. this.refractionRatio = source.refractionRatio;
  21697. this.wireframe = source.wireframe;
  21698. this.wireframeLinewidth = source.wireframeLinewidth;
  21699. this.wireframeLinecap = source.wireframeLinecap;
  21700. this.wireframeLinejoin = source.wireframeLinejoin;
  21701. return this;
  21702. }
  21703. }
  21704. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  21705. /**
  21706. * parameters = {
  21707. * color: <hex>,
  21708. * opacity: <float>,
  21709. *
  21710. * matcap: new THREE.Texture( <Image> ),
  21711. *
  21712. * map: new THREE.Texture( <Image> ),
  21713. *
  21714. * bumpMap: new THREE.Texture( <Image> ),
  21715. * bumpScale: <float>,
  21716. *
  21717. * normalMap: new THREE.Texture( <Image> ),
  21718. * normalMapType: THREE.TangentSpaceNormalMap,
  21719. * normalScale: <Vector2>,
  21720. *
  21721. * displacementMap: new THREE.Texture( <Image> ),
  21722. * displacementScale: <float>,
  21723. * displacementBias: <float>,
  21724. *
  21725. * alphaMap: new THREE.Texture( <Image> ),
  21726. *
  21727. * flatShading: <bool>
  21728. * }
  21729. */
  21730. class MeshMatcapMaterial extends Material {
  21731. constructor( parameters ) {
  21732. super();
  21733. this.defines = { 'MATCAP': '' };
  21734. this.type = 'MeshMatcapMaterial';
  21735. this.color = new Color( 0xffffff ); // diffuse
  21736. this.matcap = null;
  21737. this.map = null;
  21738. this.bumpMap = null;
  21739. this.bumpScale = 1;
  21740. this.normalMap = null;
  21741. this.normalMapType = TangentSpaceNormalMap;
  21742. this.normalScale = new Vector2( 1, 1 );
  21743. this.displacementMap = null;
  21744. this.displacementScale = 1;
  21745. this.displacementBias = 0;
  21746. this.alphaMap = null;
  21747. this.flatShading = false;
  21748. this.setValues( parameters );
  21749. }
  21750. copy( source ) {
  21751. super.copy( source );
  21752. this.defines = { 'MATCAP': '' };
  21753. this.color.copy( source.color );
  21754. this.matcap = source.matcap;
  21755. this.map = source.map;
  21756. this.bumpMap = source.bumpMap;
  21757. this.bumpScale = source.bumpScale;
  21758. this.normalMap = source.normalMap;
  21759. this.normalMapType = source.normalMapType;
  21760. this.normalScale.copy( source.normalScale );
  21761. this.displacementMap = source.displacementMap;
  21762. this.displacementScale = source.displacementScale;
  21763. this.displacementBias = source.displacementBias;
  21764. this.alphaMap = source.alphaMap;
  21765. this.flatShading = source.flatShading;
  21766. return this;
  21767. }
  21768. }
  21769. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  21770. /**
  21771. * parameters = {
  21772. * color: <hex>,
  21773. * opacity: <float>,
  21774. *
  21775. * linewidth: <float>,
  21776. *
  21777. * scale: <float>,
  21778. * dashSize: <float>,
  21779. * gapSize: <float>
  21780. * }
  21781. */
  21782. class LineDashedMaterial extends LineBasicMaterial {
  21783. constructor( parameters ) {
  21784. super();
  21785. this.type = 'LineDashedMaterial';
  21786. this.scale = 1;
  21787. this.dashSize = 3;
  21788. this.gapSize = 1;
  21789. this.setValues( parameters );
  21790. }
  21791. copy( source ) {
  21792. super.copy( source );
  21793. this.scale = source.scale;
  21794. this.dashSize = source.dashSize;
  21795. this.gapSize = source.gapSize;
  21796. return this;
  21797. }
  21798. }
  21799. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  21800. var Materials = /*#__PURE__*/Object.freeze({
  21801. __proto__: null,
  21802. ShadowMaterial: ShadowMaterial,
  21803. SpriteMaterial: SpriteMaterial,
  21804. RawShaderMaterial: RawShaderMaterial,
  21805. ShaderMaterial: ShaderMaterial,
  21806. PointsMaterial: PointsMaterial,
  21807. MeshPhysicalMaterial: MeshPhysicalMaterial,
  21808. MeshStandardMaterial: MeshStandardMaterial,
  21809. MeshPhongMaterial: MeshPhongMaterial,
  21810. MeshToonMaterial: MeshToonMaterial,
  21811. MeshNormalMaterial: MeshNormalMaterial,
  21812. MeshLambertMaterial: MeshLambertMaterial,
  21813. MeshDepthMaterial: MeshDepthMaterial,
  21814. MeshDistanceMaterial: MeshDistanceMaterial,
  21815. MeshBasicMaterial: MeshBasicMaterial,
  21816. MeshMatcapMaterial: MeshMatcapMaterial,
  21817. LineDashedMaterial: LineDashedMaterial,
  21818. LineBasicMaterial: LineBasicMaterial,
  21819. Material: Material
  21820. });
  21821. const AnimationUtils = {
  21822. // same as Array.prototype.slice, but also works on typed arrays
  21823. arraySlice: function ( array, from, to ) {
  21824. if ( AnimationUtils.isTypedArray( array ) ) {
  21825. // in ios9 array.subarray(from, undefined) will return empty array
  21826. // but array.subarray(from) or array.subarray(from, len) is correct
  21827. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  21828. }
  21829. return array.slice( from, to );
  21830. },
  21831. // converts an array to a specific type
  21832. convertArray: function ( array, type, forceClone ) {
  21833. if ( ! array || // let 'undefined' and 'null' pass
  21834. ! forceClone && array.constructor === type ) return array;
  21835. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  21836. return new type( array ); // create typed array
  21837. }
  21838. return Array.prototype.slice.call( array ); // create Array
  21839. },
  21840. isTypedArray: function ( object ) {
  21841. return ArrayBuffer.isView( object ) &&
  21842. ! ( object instanceof DataView );
  21843. },
  21844. // returns an array by which times and values can be sorted
  21845. getKeyframeOrder: function ( times ) {
  21846. function compareTime( i, j ) {
  21847. return times[ i ] - times[ j ];
  21848. }
  21849. const n = times.length;
  21850. const result = new Array( n );
  21851. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  21852. result.sort( compareTime );
  21853. return result;
  21854. },
  21855. // uses the array previously returned by 'getKeyframeOrder' to sort data
  21856. sortedArray: function ( values, stride, order ) {
  21857. const nValues = values.length;
  21858. const result = new values.constructor( nValues );
  21859. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  21860. const srcOffset = order[ i ] * stride;
  21861. for ( let j = 0; j !== stride; ++ j ) {
  21862. result[ dstOffset ++ ] = values[ srcOffset + j ];
  21863. }
  21864. }
  21865. return result;
  21866. },
  21867. // function for parsing AOS keyframe formats
  21868. flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) {
  21869. let i = 1, key = jsonKeys[ 0 ];
  21870. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  21871. key = jsonKeys[ i ++ ];
  21872. }
  21873. if ( key === undefined ) return; // no data
  21874. let value = key[ valuePropertyName ];
  21875. if ( value === undefined ) return; // no data
  21876. if ( Array.isArray( value ) ) {
  21877. do {
  21878. value = key[ valuePropertyName ];
  21879. if ( value !== undefined ) {
  21880. times.push( key.time );
  21881. values.push.apply( values, value ); // push all elements
  21882. }
  21883. key = jsonKeys[ i ++ ];
  21884. } while ( key !== undefined );
  21885. } else if ( value.toArray !== undefined ) {
  21886. // ...assume THREE.Math-ish
  21887. do {
  21888. value = key[ valuePropertyName ];
  21889. if ( value !== undefined ) {
  21890. times.push( key.time );
  21891. value.toArray( values, values.length );
  21892. }
  21893. key = jsonKeys[ i ++ ];
  21894. } while ( key !== undefined );
  21895. } else {
  21896. // otherwise push as-is
  21897. do {
  21898. value = key[ valuePropertyName ];
  21899. if ( value !== undefined ) {
  21900. times.push( key.time );
  21901. values.push( value );
  21902. }
  21903. key = jsonKeys[ i ++ ];
  21904. } while ( key !== undefined );
  21905. }
  21906. },
  21907. subclip: function ( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  21908. const clip = sourceClip.clone();
  21909. clip.name = name;
  21910. const tracks = [];
  21911. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  21912. const track = clip.tracks[ i ];
  21913. const valueSize = track.getValueSize();
  21914. const times = [];
  21915. const values = [];
  21916. for ( let j = 0; j < track.times.length; ++ j ) {
  21917. const frame = track.times[ j ] * fps;
  21918. if ( frame < startFrame || frame >= endFrame ) continue;
  21919. times.push( track.times[ j ] );
  21920. for ( let k = 0; k < valueSize; ++ k ) {
  21921. values.push( track.values[ j * valueSize + k ] );
  21922. }
  21923. }
  21924. if ( times.length === 0 ) continue;
  21925. track.times = AnimationUtils.convertArray( times, track.times.constructor );
  21926. track.values = AnimationUtils.convertArray( values, track.values.constructor );
  21927. tracks.push( track );
  21928. }
  21929. clip.tracks = tracks;
  21930. // find minimum .times value across all tracks in the trimmed clip
  21931. let minStartTime = Infinity;
  21932. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  21933. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  21934. minStartTime = clip.tracks[ i ].times[ 0 ];
  21935. }
  21936. }
  21937. // shift all tracks such that clip begins at t=0
  21938. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  21939. clip.tracks[ i ].shift( - 1 * minStartTime );
  21940. }
  21941. clip.resetDuration();
  21942. return clip;
  21943. },
  21944. makeClipAdditive: function ( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  21945. if ( fps <= 0 ) fps = 30;
  21946. const numTracks = referenceClip.tracks.length;
  21947. const referenceTime = referenceFrame / fps;
  21948. // Make each track's values relative to the values at the reference frame
  21949. for ( let i = 0; i < numTracks; ++ i ) {
  21950. const referenceTrack = referenceClip.tracks[ i ];
  21951. const referenceTrackType = referenceTrack.ValueTypeName;
  21952. // Skip this track if it's non-numeric
  21953. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  21954. // Find the track in the target clip whose name and type matches the reference track
  21955. const targetTrack = targetClip.tracks.find( function ( track ) {
  21956. return track.name === referenceTrack.name
  21957. && track.ValueTypeName === referenceTrackType;
  21958. } );
  21959. if ( targetTrack === undefined ) continue;
  21960. let referenceOffset = 0;
  21961. const referenceValueSize = referenceTrack.getValueSize();
  21962. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  21963. referenceOffset = referenceValueSize / 3;
  21964. }
  21965. let targetOffset = 0;
  21966. const targetValueSize = targetTrack.getValueSize();
  21967. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  21968. targetOffset = targetValueSize / 3;
  21969. }
  21970. const lastIndex = referenceTrack.times.length - 1;
  21971. let referenceValue;
  21972. // Find the value to subtract out of the track
  21973. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  21974. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  21975. const startIndex = referenceOffset;
  21976. const endIndex = referenceValueSize - referenceOffset;
  21977. referenceValue = AnimationUtils.arraySlice( referenceTrack.values, startIndex, endIndex );
  21978. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  21979. // Reference frame is after the last keyframe, so just use the last keyframe
  21980. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  21981. const endIndex = startIndex + referenceValueSize - referenceOffset;
  21982. referenceValue = AnimationUtils.arraySlice( referenceTrack.values, startIndex, endIndex );
  21983. } else {
  21984. // Interpolate to the reference value
  21985. const interpolant = referenceTrack.createInterpolant();
  21986. const startIndex = referenceOffset;
  21987. const endIndex = referenceValueSize - referenceOffset;
  21988. interpolant.evaluate( referenceTime );
  21989. referenceValue = AnimationUtils.arraySlice( interpolant.resultBuffer, startIndex, endIndex );
  21990. }
  21991. // Conjugate the quaternion
  21992. if ( referenceTrackType === 'quaternion' ) {
  21993. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  21994. referenceQuat.toArray( referenceValue );
  21995. }
  21996. // Subtract the reference value from all of the track values
  21997. const numTimes = targetTrack.times.length;
  21998. for ( let j = 0; j < numTimes; ++ j ) {
  21999. const valueStart = j * targetValueSize + targetOffset;
  22000. if ( referenceTrackType === 'quaternion' ) {
  22001. // Multiply the conjugate for quaternion track types
  22002. Quaternion.multiplyQuaternionsFlat(
  22003. targetTrack.values,
  22004. valueStart,
  22005. referenceValue,
  22006. 0,
  22007. targetTrack.values,
  22008. valueStart
  22009. );
  22010. } else {
  22011. const valueEnd = targetValueSize - targetOffset * 2;
  22012. // Subtract each value for all other numeric track types
  22013. for ( let k = 0; k < valueEnd; ++ k ) {
  22014. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  22015. }
  22016. }
  22017. }
  22018. }
  22019. targetClip.blendMode = AdditiveAnimationBlendMode;
  22020. return targetClip;
  22021. }
  22022. };
  22023. /**
  22024. * Abstract base class of interpolants over parametric samples.
  22025. *
  22026. * The parameter domain is one dimensional, typically the time or a path
  22027. * along a curve defined by the data.
  22028. *
  22029. * The sample values can have any dimensionality and derived classes may
  22030. * apply special interpretations to the data.
  22031. *
  22032. * This class provides the interval seek in a Template Method, deferring
  22033. * the actual interpolation to derived classes.
  22034. *
  22035. * Time complexity is O(1) for linear access crossing at most two points
  22036. * and O(log N) for random access, where N is the number of positions.
  22037. *
  22038. * References:
  22039. *
  22040. * http://www.oodesign.com/template-method-pattern.html
  22041. *
  22042. */
  22043. class Interpolant {
  22044. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22045. this.parameterPositions = parameterPositions;
  22046. this._cachedIndex = 0;
  22047. this.resultBuffer = resultBuffer !== undefined ?
  22048. resultBuffer : new sampleValues.constructor( sampleSize );
  22049. this.sampleValues = sampleValues;
  22050. this.valueSize = sampleSize;
  22051. this.settings = null;
  22052. this.DefaultSettings_ = {};
  22053. }
  22054. evaluate( t ) {
  22055. const pp = this.parameterPositions;
  22056. let i1 = this._cachedIndex,
  22057. t1 = pp[ i1 ],
  22058. t0 = pp[ i1 - 1 ];
  22059. validate_interval: {
  22060. seek: {
  22061. let right;
  22062. linear_scan: {
  22063. //- See http://jsperf.com/comparison-to-undefined/3
  22064. //- slower code:
  22065. //-
  22066. //- if ( t >= t1 || t1 === undefined ) {
  22067. forward_scan: if ( ! ( t < t1 ) ) {
  22068. for ( let giveUpAt = i1 + 2; ; ) {
  22069. if ( t1 === undefined ) {
  22070. if ( t < t0 ) break forward_scan;
  22071. // after end
  22072. i1 = pp.length;
  22073. this._cachedIndex = i1;
  22074. return this.afterEnd_( i1 - 1, t, t0 );
  22075. }
  22076. if ( i1 === giveUpAt ) break; // this loop
  22077. t0 = t1;
  22078. t1 = pp[ ++ i1 ];
  22079. if ( t < t1 ) {
  22080. // we have arrived at the sought interval
  22081. break seek;
  22082. }
  22083. }
  22084. // prepare binary search on the right side of the index
  22085. right = pp.length;
  22086. break linear_scan;
  22087. }
  22088. //- slower code:
  22089. //- if ( t < t0 || t0 === undefined ) {
  22090. if ( ! ( t >= t0 ) ) {
  22091. // looping?
  22092. const t1global = pp[ 1 ];
  22093. if ( t < t1global ) {
  22094. i1 = 2; // + 1, using the scan for the details
  22095. t0 = t1global;
  22096. }
  22097. // linear reverse scan
  22098. for ( let giveUpAt = i1 - 2; ; ) {
  22099. if ( t0 === undefined ) {
  22100. // before start
  22101. this._cachedIndex = 0;
  22102. return this.beforeStart_( 0, t, t1 );
  22103. }
  22104. if ( i1 === giveUpAt ) break; // this loop
  22105. t1 = t0;
  22106. t0 = pp[ -- i1 - 1 ];
  22107. if ( t >= t0 ) {
  22108. // we have arrived at the sought interval
  22109. break seek;
  22110. }
  22111. }
  22112. // prepare binary search on the left side of the index
  22113. right = i1;
  22114. i1 = 0;
  22115. break linear_scan;
  22116. }
  22117. // the interval is valid
  22118. break validate_interval;
  22119. } // linear scan
  22120. // binary search
  22121. while ( i1 < right ) {
  22122. const mid = ( i1 + right ) >>> 1;
  22123. if ( t < pp[ mid ] ) {
  22124. right = mid;
  22125. } else {
  22126. i1 = mid + 1;
  22127. }
  22128. }
  22129. t1 = pp[ i1 ];
  22130. t0 = pp[ i1 - 1 ];
  22131. // check boundary cases, again
  22132. if ( t0 === undefined ) {
  22133. this._cachedIndex = 0;
  22134. return this.beforeStart_( 0, t, t1 );
  22135. }
  22136. if ( t1 === undefined ) {
  22137. i1 = pp.length;
  22138. this._cachedIndex = i1;
  22139. return this.afterEnd_( i1 - 1, t0, t );
  22140. }
  22141. } // seek
  22142. this._cachedIndex = i1;
  22143. this.intervalChanged_( i1, t0, t1 );
  22144. } // validate_interval
  22145. return this.interpolate_( i1, t0, t, t1 );
  22146. }
  22147. getSettings_() {
  22148. return this.settings || this.DefaultSettings_;
  22149. }
  22150. copySampleValue_( index ) {
  22151. // copies a sample value to the result buffer
  22152. const result = this.resultBuffer,
  22153. values = this.sampleValues,
  22154. stride = this.valueSize,
  22155. offset = index * stride;
  22156. for ( let i = 0; i !== stride; ++ i ) {
  22157. result[ i ] = values[ offset + i ];
  22158. }
  22159. return result;
  22160. }
  22161. // Template methods for derived classes:
  22162. interpolate_( /* i1, t0, t, t1 */ ) {
  22163. throw new Error( 'call to abstract method' );
  22164. // implementations shall return this.resultBuffer
  22165. }
  22166. intervalChanged_( /* i1, t0, t1 */ ) {
  22167. // empty
  22168. }
  22169. }
  22170. // ALIAS DEFINITIONS
  22171. Interpolant.prototype.beforeStart_ = Interpolant.prototype.copySampleValue_;
  22172. Interpolant.prototype.afterEnd_ = Interpolant.prototype.copySampleValue_;
  22173. /**
  22174. * Fast and simple cubic spline interpolant.
  22175. *
  22176. * It was derived from a Hermitian construction setting the first derivative
  22177. * at each sample position to the linear slope between neighboring positions
  22178. * over their parameter interval.
  22179. */
  22180. class CubicInterpolant extends Interpolant {
  22181. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22182. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  22183. this._weightPrev = - 0;
  22184. this._offsetPrev = - 0;
  22185. this._weightNext = - 0;
  22186. this._offsetNext = - 0;
  22187. this.DefaultSettings_ = {
  22188. endingStart: ZeroCurvatureEnding,
  22189. endingEnd: ZeroCurvatureEnding
  22190. };
  22191. }
  22192. intervalChanged_( i1, t0, t1 ) {
  22193. const pp = this.parameterPositions;
  22194. let iPrev = i1 - 2,
  22195. iNext = i1 + 1,
  22196. tPrev = pp[ iPrev ],
  22197. tNext = pp[ iNext ];
  22198. if ( tPrev === undefined ) {
  22199. switch ( this.getSettings_().endingStart ) {
  22200. case ZeroSlopeEnding:
  22201. // f'(t0) = 0
  22202. iPrev = i1;
  22203. tPrev = 2 * t0 - t1;
  22204. break;
  22205. case WrapAroundEnding:
  22206. // use the other end of the curve
  22207. iPrev = pp.length - 2;
  22208. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  22209. break;
  22210. default: // ZeroCurvatureEnding
  22211. // f''(t0) = 0 a.k.a. Natural Spline
  22212. iPrev = i1;
  22213. tPrev = t1;
  22214. }
  22215. }
  22216. if ( tNext === undefined ) {
  22217. switch ( this.getSettings_().endingEnd ) {
  22218. case ZeroSlopeEnding:
  22219. // f'(tN) = 0
  22220. iNext = i1;
  22221. tNext = 2 * t1 - t0;
  22222. break;
  22223. case WrapAroundEnding:
  22224. // use the other end of the curve
  22225. iNext = 1;
  22226. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  22227. break;
  22228. default: // ZeroCurvatureEnding
  22229. // f''(tN) = 0, a.k.a. Natural Spline
  22230. iNext = i1 - 1;
  22231. tNext = t0;
  22232. }
  22233. }
  22234. const halfDt = ( t1 - t0 ) * 0.5,
  22235. stride = this.valueSize;
  22236. this._weightPrev = halfDt / ( t0 - tPrev );
  22237. this._weightNext = halfDt / ( tNext - t1 );
  22238. this._offsetPrev = iPrev * stride;
  22239. this._offsetNext = iNext * stride;
  22240. }
  22241. interpolate_( i1, t0, t, t1 ) {
  22242. const result = this.resultBuffer,
  22243. values = this.sampleValues,
  22244. stride = this.valueSize,
  22245. o1 = i1 * stride, o0 = o1 - stride,
  22246. oP = this._offsetPrev, oN = this._offsetNext,
  22247. wP = this._weightPrev, wN = this._weightNext,
  22248. p = ( t - t0 ) / ( t1 - t0 ),
  22249. pp = p * p,
  22250. ppp = pp * p;
  22251. // evaluate polynomials
  22252. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  22253. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  22254. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  22255. const sN = wN * ppp - wN * pp;
  22256. // combine data linearly
  22257. for ( let i = 0; i !== stride; ++ i ) {
  22258. result[ i ] =
  22259. sP * values[ oP + i ] +
  22260. s0 * values[ o0 + i ] +
  22261. s1 * values[ o1 + i ] +
  22262. sN * values[ oN + i ];
  22263. }
  22264. return result;
  22265. }
  22266. }
  22267. class LinearInterpolant extends Interpolant {
  22268. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22269. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  22270. }
  22271. interpolate_( i1, t0, t, t1 ) {
  22272. const result = this.resultBuffer,
  22273. values = this.sampleValues,
  22274. stride = this.valueSize,
  22275. offset1 = i1 * stride,
  22276. offset0 = offset1 - stride,
  22277. weight1 = ( t - t0 ) / ( t1 - t0 ),
  22278. weight0 = 1 - weight1;
  22279. for ( let i = 0; i !== stride; ++ i ) {
  22280. result[ i ] =
  22281. values[ offset0 + i ] * weight0 +
  22282. values[ offset1 + i ] * weight1;
  22283. }
  22284. return result;
  22285. }
  22286. }
  22287. /**
  22288. *
  22289. * Interpolant that evaluates to the sample value at the position preceeding
  22290. * the parameter.
  22291. */
  22292. class DiscreteInterpolant extends Interpolant {
  22293. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22294. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  22295. }
  22296. interpolate_( i1 /*, t0, t, t1 */ ) {
  22297. return this.copySampleValue_( i1 - 1 );
  22298. }
  22299. }
  22300. class KeyframeTrack {
  22301. constructor( name, times, values, interpolation ) {
  22302. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  22303. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  22304. this.name = name;
  22305. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  22306. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  22307. this.setInterpolation( interpolation || this.DefaultInterpolation );
  22308. }
  22309. // Serialization (in static context, because of constructor invocation
  22310. // and automatic invocation of .toJSON):
  22311. static toJSON( track ) {
  22312. const trackType = track.constructor;
  22313. let json;
  22314. // derived classes can define a static toJSON method
  22315. if ( trackType.toJSON !== this.toJSON ) {
  22316. json = trackType.toJSON( track );
  22317. } else {
  22318. // by default, we assume the data can be serialized as-is
  22319. json = {
  22320. 'name': track.name,
  22321. 'times': AnimationUtils.convertArray( track.times, Array ),
  22322. 'values': AnimationUtils.convertArray( track.values, Array )
  22323. };
  22324. const interpolation = track.getInterpolation();
  22325. if ( interpolation !== track.DefaultInterpolation ) {
  22326. json.interpolation = interpolation;
  22327. }
  22328. }
  22329. json.type = track.ValueTypeName; // mandatory
  22330. return json;
  22331. }
  22332. InterpolantFactoryMethodDiscrete( result ) {
  22333. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  22334. }
  22335. InterpolantFactoryMethodLinear( result ) {
  22336. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  22337. }
  22338. InterpolantFactoryMethodSmooth( result ) {
  22339. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  22340. }
  22341. setInterpolation( interpolation ) {
  22342. let factoryMethod;
  22343. switch ( interpolation ) {
  22344. case InterpolateDiscrete:
  22345. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  22346. break;
  22347. case InterpolateLinear:
  22348. factoryMethod = this.InterpolantFactoryMethodLinear;
  22349. break;
  22350. case InterpolateSmooth:
  22351. factoryMethod = this.InterpolantFactoryMethodSmooth;
  22352. break;
  22353. }
  22354. if ( factoryMethod === undefined ) {
  22355. const message = 'unsupported interpolation for ' +
  22356. this.ValueTypeName + ' keyframe track named ' + this.name;
  22357. if ( this.createInterpolant === undefined ) {
  22358. // fall back to default, unless the default itself is messed up
  22359. if ( interpolation !== this.DefaultInterpolation ) {
  22360. this.setInterpolation( this.DefaultInterpolation );
  22361. } else {
  22362. throw new Error( message ); // fatal, in this case
  22363. }
  22364. }
  22365. console.warn( 'THREE.KeyframeTrack:', message );
  22366. return this;
  22367. }
  22368. this.createInterpolant = factoryMethod;
  22369. return this;
  22370. }
  22371. getInterpolation() {
  22372. switch ( this.createInterpolant ) {
  22373. case this.InterpolantFactoryMethodDiscrete:
  22374. return InterpolateDiscrete;
  22375. case this.InterpolantFactoryMethodLinear:
  22376. return InterpolateLinear;
  22377. case this.InterpolantFactoryMethodSmooth:
  22378. return InterpolateSmooth;
  22379. }
  22380. }
  22381. getValueSize() {
  22382. return this.values.length / this.times.length;
  22383. }
  22384. // move all keyframes either forwards or backwards in time
  22385. shift( timeOffset ) {
  22386. if ( timeOffset !== 0.0 ) {
  22387. const times = this.times;
  22388. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  22389. times[ i ] += timeOffset;
  22390. }
  22391. }
  22392. return this;
  22393. }
  22394. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  22395. scale( timeScale ) {
  22396. if ( timeScale !== 1.0 ) {
  22397. const times = this.times;
  22398. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  22399. times[ i ] *= timeScale;
  22400. }
  22401. }
  22402. return this;
  22403. }
  22404. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  22405. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  22406. trim( startTime, endTime ) {
  22407. const times = this.times,
  22408. nKeys = times.length;
  22409. let from = 0,
  22410. to = nKeys - 1;
  22411. while ( from !== nKeys && times[ from ] < startTime ) {
  22412. ++ from;
  22413. }
  22414. while ( to !== - 1 && times[ to ] > endTime ) {
  22415. -- to;
  22416. }
  22417. ++ to; // inclusive -> exclusive bound
  22418. if ( from !== 0 || to !== nKeys ) {
  22419. // empty tracks are forbidden, so keep at least one keyframe
  22420. if ( from >= to ) {
  22421. to = Math.max( to, 1 );
  22422. from = to - 1;
  22423. }
  22424. const stride = this.getValueSize();
  22425. this.times = AnimationUtils.arraySlice( times, from, to );
  22426. this.values = AnimationUtils.arraySlice( this.values, from * stride, to * stride );
  22427. }
  22428. return this;
  22429. }
  22430. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  22431. validate() {
  22432. let valid = true;
  22433. const valueSize = this.getValueSize();
  22434. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  22435. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  22436. valid = false;
  22437. }
  22438. const times = this.times,
  22439. values = this.values,
  22440. nKeys = times.length;
  22441. if ( nKeys === 0 ) {
  22442. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  22443. valid = false;
  22444. }
  22445. let prevTime = null;
  22446. for ( let i = 0; i !== nKeys; i ++ ) {
  22447. const currTime = times[ i ];
  22448. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  22449. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  22450. valid = false;
  22451. break;
  22452. }
  22453. if ( prevTime !== null && prevTime > currTime ) {
  22454. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  22455. valid = false;
  22456. break;
  22457. }
  22458. prevTime = currTime;
  22459. }
  22460. if ( values !== undefined ) {
  22461. if ( AnimationUtils.isTypedArray( values ) ) {
  22462. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  22463. const value = values[ i ];
  22464. if ( isNaN( value ) ) {
  22465. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  22466. valid = false;
  22467. break;
  22468. }
  22469. }
  22470. }
  22471. }
  22472. return valid;
  22473. }
  22474. // removes equivalent sequential keys as common in morph target sequences
  22475. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  22476. optimize() {
  22477. // times or values may be shared with other tracks, so overwriting is unsafe
  22478. const times = AnimationUtils.arraySlice( this.times ),
  22479. values = AnimationUtils.arraySlice( this.values ),
  22480. stride = this.getValueSize(),
  22481. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  22482. lastIndex = times.length - 1;
  22483. let writeIndex = 1;
  22484. for ( let i = 1; i < lastIndex; ++ i ) {
  22485. let keep = false;
  22486. const time = times[ i ];
  22487. const timeNext = times[ i + 1 ];
  22488. // remove adjacent keyframes scheduled at the same time
  22489. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  22490. if ( ! smoothInterpolation ) {
  22491. // remove unnecessary keyframes same as their neighbors
  22492. const offset = i * stride,
  22493. offsetP = offset - stride,
  22494. offsetN = offset + stride;
  22495. for ( let j = 0; j !== stride; ++ j ) {
  22496. const value = values[ offset + j ];
  22497. if ( value !== values[ offsetP + j ] ||
  22498. value !== values[ offsetN + j ] ) {
  22499. keep = true;
  22500. break;
  22501. }
  22502. }
  22503. } else {
  22504. keep = true;
  22505. }
  22506. }
  22507. // in-place compaction
  22508. if ( keep ) {
  22509. if ( i !== writeIndex ) {
  22510. times[ writeIndex ] = times[ i ];
  22511. const readOffset = i * stride,
  22512. writeOffset = writeIndex * stride;
  22513. for ( let j = 0; j !== stride; ++ j ) {
  22514. values[ writeOffset + j ] = values[ readOffset + j ];
  22515. }
  22516. }
  22517. ++ writeIndex;
  22518. }
  22519. }
  22520. // flush last keyframe (compaction looks ahead)
  22521. if ( lastIndex > 0 ) {
  22522. times[ writeIndex ] = times[ lastIndex ];
  22523. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  22524. values[ writeOffset + j ] = values[ readOffset + j ];
  22525. }
  22526. ++ writeIndex;
  22527. }
  22528. if ( writeIndex !== times.length ) {
  22529. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  22530. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  22531. } else {
  22532. this.times = times;
  22533. this.values = values;
  22534. }
  22535. return this;
  22536. }
  22537. clone() {
  22538. const times = AnimationUtils.arraySlice( this.times, 0 );
  22539. const values = AnimationUtils.arraySlice( this.values, 0 );
  22540. const TypedKeyframeTrack = this.constructor;
  22541. const track = new TypedKeyframeTrack( this.name, times, values );
  22542. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  22543. track.createInterpolant = this.createInterpolant;
  22544. return track;
  22545. }
  22546. }
  22547. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  22548. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  22549. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  22550. /**
  22551. * A Track of Boolean keyframe values.
  22552. */
  22553. class BooleanKeyframeTrack extends KeyframeTrack {}
  22554. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  22555. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  22556. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  22557. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  22558. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  22559. /**
  22560. * A Track of keyframe values that represent color.
  22561. */
  22562. class ColorKeyframeTrack extends KeyframeTrack {}
  22563. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  22564. /**
  22565. * A Track of numeric keyframe values.
  22566. */
  22567. class NumberKeyframeTrack extends KeyframeTrack {}
  22568. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  22569. /**
  22570. * Spherical linear unit quaternion interpolant.
  22571. */
  22572. class QuaternionLinearInterpolant extends Interpolant {
  22573. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22574. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  22575. }
  22576. interpolate_( i1, t0, t, t1 ) {
  22577. const result = this.resultBuffer,
  22578. values = this.sampleValues,
  22579. stride = this.valueSize,
  22580. alpha = ( t - t0 ) / ( t1 - t0 );
  22581. let offset = i1 * stride;
  22582. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  22583. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  22584. }
  22585. return result;
  22586. }
  22587. }
  22588. /**
  22589. * A Track of quaternion keyframe values.
  22590. */
  22591. class QuaternionKeyframeTrack extends KeyframeTrack {
  22592. InterpolantFactoryMethodLinear( result ) {
  22593. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  22594. }
  22595. }
  22596. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  22597. // ValueBufferType is inherited
  22598. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  22599. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  22600. /**
  22601. * A Track that interpolates Strings
  22602. */
  22603. class StringKeyframeTrack extends KeyframeTrack {}
  22604. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  22605. StringKeyframeTrack.prototype.ValueBufferType = Array;
  22606. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  22607. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  22608. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  22609. /**
  22610. * A Track of vectored keyframe values.
  22611. */
  22612. class VectorKeyframeTrack extends KeyframeTrack {}
  22613. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  22614. class AnimationClip {
  22615. constructor( name, duration = - 1, tracks, blendMode = NormalAnimationBlendMode ) {
  22616. this.name = name;
  22617. this.tracks = tracks;
  22618. this.duration = duration;
  22619. this.blendMode = blendMode;
  22620. this.uuid = generateUUID();
  22621. // this means it should figure out its duration by scanning the tracks
  22622. if ( this.duration < 0 ) {
  22623. this.resetDuration();
  22624. }
  22625. }
  22626. static parse( json ) {
  22627. const tracks = [],
  22628. jsonTracks = json.tracks,
  22629. frameTime = 1.0 / ( json.fps || 1.0 );
  22630. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  22631. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  22632. }
  22633. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  22634. clip.uuid = json.uuid;
  22635. return clip;
  22636. }
  22637. static toJSON( clip ) {
  22638. const tracks = [],
  22639. clipTracks = clip.tracks;
  22640. const json = {
  22641. 'name': clip.name,
  22642. 'duration': clip.duration,
  22643. 'tracks': tracks,
  22644. 'uuid': clip.uuid,
  22645. 'blendMode': clip.blendMode
  22646. };
  22647. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  22648. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  22649. }
  22650. return json;
  22651. }
  22652. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  22653. const numMorphTargets = morphTargetSequence.length;
  22654. const tracks = [];
  22655. for ( let i = 0; i < numMorphTargets; i ++ ) {
  22656. let times = [];
  22657. let values = [];
  22658. times.push(
  22659. ( i + numMorphTargets - 1 ) % numMorphTargets,
  22660. i,
  22661. ( i + 1 ) % numMorphTargets );
  22662. values.push( 0, 1, 0 );
  22663. const order = AnimationUtils.getKeyframeOrder( times );
  22664. times = AnimationUtils.sortedArray( times, 1, order );
  22665. values = AnimationUtils.sortedArray( values, 1, order );
  22666. // if there is a key at the first frame, duplicate it as the
  22667. // last frame as well for perfect loop.
  22668. if ( ! noLoop && times[ 0 ] === 0 ) {
  22669. times.push( numMorphTargets );
  22670. values.push( values[ 0 ] );
  22671. }
  22672. tracks.push(
  22673. new NumberKeyframeTrack(
  22674. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  22675. times, values
  22676. ).scale( 1.0 / fps ) );
  22677. }
  22678. return new this( name, - 1, tracks );
  22679. }
  22680. static findByName( objectOrClipArray, name ) {
  22681. let clipArray = objectOrClipArray;
  22682. if ( ! Array.isArray( objectOrClipArray ) ) {
  22683. const o = objectOrClipArray;
  22684. clipArray = o.geometry && o.geometry.animations || o.animations;
  22685. }
  22686. for ( let i = 0; i < clipArray.length; i ++ ) {
  22687. if ( clipArray[ i ].name === name ) {
  22688. return clipArray[ i ];
  22689. }
  22690. }
  22691. return null;
  22692. }
  22693. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  22694. const animationToMorphTargets = {};
  22695. // tested with https://regex101.com/ on trick sequences
  22696. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  22697. const pattern = /^([\w-]*?)([\d]+)$/;
  22698. // sort morph target names into animation groups based
  22699. // patterns like Walk_001, Walk_002, Run_001, Run_002
  22700. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  22701. const morphTarget = morphTargets[ i ];
  22702. const parts = morphTarget.name.match( pattern );
  22703. if ( parts && parts.length > 1 ) {
  22704. const name = parts[ 1 ];
  22705. let animationMorphTargets = animationToMorphTargets[ name ];
  22706. if ( ! animationMorphTargets ) {
  22707. animationToMorphTargets[ name ] = animationMorphTargets = [];
  22708. }
  22709. animationMorphTargets.push( morphTarget );
  22710. }
  22711. }
  22712. const clips = [];
  22713. for ( const name in animationToMorphTargets ) {
  22714. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  22715. }
  22716. return clips;
  22717. }
  22718. // parse the animation.hierarchy format
  22719. static parseAnimation( animation, bones ) {
  22720. if ( ! animation ) {
  22721. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  22722. return null;
  22723. }
  22724. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  22725. // only return track if there are actually keys.
  22726. if ( animationKeys.length !== 0 ) {
  22727. const times = [];
  22728. const values = [];
  22729. AnimationUtils.flattenJSON( animationKeys, times, values, propertyName );
  22730. // empty keys are filtered out, so check again
  22731. if ( times.length !== 0 ) {
  22732. destTracks.push( new trackType( trackName, times, values ) );
  22733. }
  22734. }
  22735. };
  22736. const tracks = [];
  22737. const clipName = animation.name || 'default';
  22738. const fps = animation.fps || 30;
  22739. const blendMode = animation.blendMode;
  22740. // automatic length determination in AnimationClip.
  22741. let duration = animation.length || - 1;
  22742. const hierarchyTracks = animation.hierarchy || [];
  22743. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  22744. const animationKeys = hierarchyTracks[ h ].keys;
  22745. // skip empty tracks
  22746. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  22747. // process morph targets
  22748. if ( animationKeys[ 0 ].morphTargets ) {
  22749. // figure out all morph targets used in this track
  22750. const morphTargetNames = {};
  22751. let k;
  22752. for ( k = 0; k < animationKeys.length; k ++ ) {
  22753. if ( animationKeys[ k ].morphTargets ) {
  22754. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  22755. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  22756. }
  22757. }
  22758. }
  22759. // create a track for each morph target with all zero
  22760. // morphTargetInfluences except for the keys in which
  22761. // the morphTarget is named.
  22762. for ( const morphTargetName in morphTargetNames ) {
  22763. const times = [];
  22764. const values = [];
  22765. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  22766. const animationKey = animationKeys[ k ];
  22767. times.push( animationKey.time );
  22768. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  22769. }
  22770. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  22771. }
  22772. duration = morphTargetNames.length * ( fps || 1.0 );
  22773. } else {
  22774. // ...assume skeletal animation
  22775. const boneName = '.bones[' + bones[ h ].name + ']';
  22776. addNonemptyTrack(
  22777. VectorKeyframeTrack, boneName + '.position',
  22778. animationKeys, 'pos', tracks );
  22779. addNonemptyTrack(
  22780. QuaternionKeyframeTrack, boneName + '.quaternion',
  22781. animationKeys, 'rot', tracks );
  22782. addNonemptyTrack(
  22783. VectorKeyframeTrack, boneName + '.scale',
  22784. animationKeys, 'scl', tracks );
  22785. }
  22786. }
  22787. if ( tracks.length === 0 ) {
  22788. return null;
  22789. }
  22790. const clip = new this( clipName, duration, tracks, blendMode );
  22791. return clip;
  22792. }
  22793. resetDuration() {
  22794. const tracks = this.tracks;
  22795. let duration = 0;
  22796. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  22797. const track = this.tracks[ i ];
  22798. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  22799. }
  22800. this.duration = duration;
  22801. return this;
  22802. }
  22803. trim() {
  22804. for ( let i = 0; i < this.tracks.length; i ++ ) {
  22805. this.tracks[ i ].trim( 0, this.duration );
  22806. }
  22807. return this;
  22808. }
  22809. validate() {
  22810. let valid = true;
  22811. for ( let i = 0; i < this.tracks.length; i ++ ) {
  22812. valid = valid && this.tracks[ i ].validate();
  22813. }
  22814. return valid;
  22815. }
  22816. optimize() {
  22817. for ( let i = 0; i < this.tracks.length; i ++ ) {
  22818. this.tracks[ i ].optimize();
  22819. }
  22820. return this;
  22821. }
  22822. clone() {
  22823. const tracks = [];
  22824. for ( let i = 0; i < this.tracks.length; i ++ ) {
  22825. tracks.push( this.tracks[ i ].clone() );
  22826. }
  22827. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  22828. }
  22829. toJSON() {
  22830. return this.constructor.toJSON( this );
  22831. }
  22832. }
  22833. function getTrackTypeForValueTypeName( typeName ) {
  22834. switch ( typeName.toLowerCase() ) {
  22835. case 'scalar':
  22836. case 'double':
  22837. case 'float':
  22838. case 'number':
  22839. case 'integer':
  22840. return NumberKeyframeTrack;
  22841. case 'vector':
  22842. case 'vector2':
  22843. case 'vector3':
  22844. case 'vector4':
  22845. return VectorKeyframeTrack;
  22846. case 'color':
  22847. return ColorKeyframeTrack;
  22848. case 'quaternion':
  22849. return QuaternionKeyframeTrack;
  22850. case 'bool':
  22851. case 'boolean':
  22852. return BooleanKeyframeTrack;
  22853. case 'string':
  22854. return StringKeyframeTrack;
  22855. }
  22856. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  22857. }
  22858. function parseKeyframeTrack( json ) {
  22859. if ( json.type === undefined ) {
  22860. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  22861. }
  22862. const trackType = getTrackTypeForValueTypeName( json.type );
  22863. if ( json.times === undefined ) {
  22864. const times = [], values = [];
  22865. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  22866. json.times = times;
  22867. json.values = values;
  22868. }
  22869. // derived classes can define a static parse method
  22870. if ( trackType.parse !== undefined ) {
  22871. return trackType.parse( json );
  22872. } else {
  22873. // by default, we assume a constructor compatible with the base
  22874. return new trackType( json.name, json.times, json.values, json.interpolation );
  22875. }
  22876. }
  22877. const Cache = {
  22878. enabled: false,
  22879. files: {},
  22880. add: function ( key, file ) {
  22881. if ( this.enabled === false ) return;
  22882. // console.log( 'THREE.Cache', 'Adding key:', key );
  22883. this.files[ key ] = file;
  22884. },
  22885. get: function ( key ) {
  22886. if ( this.enabled === false ) return;
  22887. // console.log( 'THREE.Cache', 'Checking key:', key );
  22888. return this.files[ key ];
  22889. },
  22890. remove: function ( key ) {
  22891. delete this.files[ key ];
  22892. },
  22893. clear: function () {
  22894. this.files = {};
  22895. }
  22896. };
  22897. class LoadingManager {
  22898. constructor( onLoad, onProgress, onError ) {
  22899. const scope = this;
  22900. let isLoading = false;
  22901. let itemsLoaded = 0;
  22902. let itemsTotal = 0;
  22903. let urlModifier = undefined;
  22904. const handlers = [];
  22905. // Refer to #5689 for the reason why we don't set .onStart
  22906. // in the constructor
  22907. this.onStart = undefined;
  22908. this.onLoad = onLoad;
  22909. this.onProgress = onProgress;
  22910. this.onError = onError;
  22911. this.itemStart = function ( url ) {
  22912. itemsTotal ++;
  22913. if ( isLoading === false ) {
  22914. if ( scope.onStart !== undefined ) {
  22915. scope.onStart( url, itemsLoaded, itemsTotal );
  22916. }
  22917. }
  22918. isLoading = true;
  22919. };
  22920. this.itemEnd = function ( url ) {
  22921. itemsLoaded ++;
  22922. if ( scope.onProgress !== undefined ) {
  22923. scope.onProgress( url, itemsLoaded, itemsTotal );
  22924. }
  22925. if ( itemsLoaded === itemsTotal ) {
  22926. isLoading = false;
  22927. if ( scope.onLoad !== undefined ) {
  22928. scope.onLoad();
  22929. }
  22930. }
  22931. };
  22932. this.itemError = function ( url ) {
  22933. if ( scope.onError !== undefined ) {
  22934. scope.onError( url );
  22935. }
  22936. };
  22937. this.resolveURL = function ( url ) {
  22938. if ( urlModifier ) {
  22939. return urlModifier( url );
  22940. }
  22941. return url;
  22942. };
  22943. this.setURLModifier = function ( transform ) {
  22944. urlModifier = transform;
  22945. return this;
  22946. };
  22947. this.addHandler = function ( regex, loader ) {
  22948. handlers.push( regex, loader );
  22949. return this;
  22950. };
  22951. this.removeHandler = function ( regex ) {
  22952. const index = handlers.indexOf( regex );
  22953. if ( index !== - 1 ) {
  22954. handlers.splice( index, 2 );
  22955. }
  22956. return this;
  22957. };
  22958. this.getHandler = function ( file ) {
  22959. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  22960. const regex = handlers[ i ];
  22961. const loader = handlers[ i + 1 ];
  22962. if ( regex.global ) regex.lastIndex = 0; // see #17920
  22963. if ( regex.test( file ) ) {
  22964. return loader;
  22965. }
  22966. }
  22967. return null;
  22968. };
  22969. }
  22970. }
  22971. const DefaultLoadingManager = new LoadingManager();
  22972. class Loader {
  22973. constructor( manager ) {
  22974. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  22975. this.crossOrigin = 'anonymous';
  22976. this.withCredentials = false;
  22977. this.path = '';
  22978. this.resourcePath = '';
  22979. this.requestHeader = {};
  22980. }
  22981. load( /* url, onLoad, onProgress, onError */ ) {}
  22982. loadAsync( url, onProgress ) {
  22983. const scope = this;
  22984. return new Promise( function ( resolve, reject ) {
  22985. scope.load( url, resolve, onProgress, reject );
  22986. } );
  22987. }
  22988. parse( /* data */ ) {}
  22989. setCrossOrigin( crossOrigin ) {
  22990. this.crossOrigin = crossOrigin;
  22991. return this;
  22992. }
  22993. setWithCredentials( value ) {
  22994. this.withCredentials = value;
  22995. return this;
  22996. }
  22997. setPath( path ) {
  22998. this.path = path;
  22999. return this;
  23000. }
  23001. setResourcePath( resourcePath ) {
  23002. this.resourcePath = resourcePath;
  23003. return this;
  23004. }
  23005. setRequestHeader( requestHeader ) {
  23006. this.requestHeader = requestHeader;
  23007. return this;
  23008. }
  23009. }
  23010. const loading = {};
  23011. class FileLoader extends Loader {
  23012. constructor( manager ) {
  23013. super( manager );
  23014. }
  23015. load( url, onLoad, onProgress, onError ) {
  23016. if ( url === undefined ) url = '';
  23017. if ( this.path !== undefined ) url = this.path + url;
  23018. url = this.manager.resolveURL( url );
  23019. const cached = Cache.get( url );
  23020. if ( cached !== undefined ) {
  23021. this.manager.itemStart( url );
  23022. setTimeout( () => {
  23023. if ( onLoad ) onLoad( cached );
  23024. this.manager.itemEnd( url );
  23025. }, 0 );
  23026. return cached;
  23027. }
  23028. // Check if request is duplicate
  23029. if ( loading[ url ] !== undefined ) {
  23030. loading[ url ].push( {
  23031. onLoad: onLoad,
  23032. onProgress: onProgress,
  23033. onError: onError
  23034. } );
  23035. return;
  23036. }
  23037. // Initialise array for duplicate requests
  23038. loading[ url ] = [];
  23039. loading[ url ].push( {
  23040. onLoad: onLoad,
  23041. onProgress: onProgress,
  23042. onError: onError,
  23043. } );
  23044. // create request
  23045. const req = new Request( url, {
  23046. headers: new Headers( this.requestHeader ),
  23047. credentials: this.withCredentials ? 'include' : 'same-origin',
  23048. // An abort controller could be added within a future PR
  23049. } );
  23050. // start the fetch
  23051. fetch( req )
  23052. .then( response => {
  23053. if ( response.status === 200 || response.status === 0 ) {
  23054. // Some browsers return HTTP Status 0 when using non-http protocol
  23055. // e.g. 'file://' or 'data://'. Handle as success.
  23056. if ( response.status === 0 ) {
  23057. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  23058. }
  23059. const callbacks = loading[ url ];
  23060. const reader = response.body.getReader();
  23061. const contentLength = response.headers.get( 'Content-Length' );
  23062. const total = contentLength ? parseInt( contentLength ) : 0;
  23063. const lengthComputable = total !== 0;
  23064. let loaded = 0;
  23065. // periodically read data into the new stream tracking while download progress
  23066. return new ReadableStream( {
  23067. start( controller ) {
  23068. readData();
  23069. function readData() {
  23070. reader.read().then( ( { done, value } ) => {
  23071. if ( done ) {
  23072. controller.close();
  23073. } else {
  23074. loaded += value.byteLength;
  23075. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  23076. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  23077. const callback = callbacks[ i ];
  23078. if ( callback.onProgress ) callback.onProgress( event );
  23079. }
  23080. controller.enqueue( value );
  23081. readData();
  23082. }
  23083. } );
  23084. }
  23085. }
  23086. } );
  23087. } else {
  23088. throw Error( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}` );
  23089. }
  23090. } )
  23091. .then( stream => {
  23092. const response = new Response( stream );
  23093. switch ( this.responseType ) {
  23094. case 'arraybuffer':
  23095. return response.arrayBuffer();
  23096. case 'blob':
  23097. return response.blob();
  23098. case 'document':
  23099. return response.text()
  23100. .then( text => {
  23101. const parser = new DOMParser();
  23102. return parser.parseFromString( text, this.mimeType );
  23103. } );
  23104. case 'json':
  23105. return response.json();
  23106. default:
  23107. return response.text();
  23108. }
  23109. } )
  23110. .then( data => {
  23111. // Add to cache only on HTTP success, so that we do not cache
  23112. // error response bodies as proper responses to requests.
  23113. Cache.add( url, data );
  23114. const callbacks = loading[ url ];
  23115. delete loading[ url ];
  23116. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  23117. const callback = callbacks[ i ];
  23118. if ( callback.onLoad ) callback.onLoad( data );
  23119. }
  23120. this.manager.itemEnd( url );
  23121. } )
  23122. .catch( err => {
  23123. // Abort errors and other errors are handled the same
  23124. const callbacks = loading[ url ];
  23125. delete loading[ url ];
  23126. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  23127. const callback = callbacks[ i ];
  23128. if ( callback.onError ) callback.onError( err );
  23129. }
  23130. this.manager.itemError( url );
  23131. this.manager.itemEnd( url );
  23132. } );
  23133. this.manager.itemStart( url );
  23134. }
  23135. setResponseType( value ) {
  23136. this.responseType = value;
  23137. return this;
  23138. }
  23139. setMimeType( value ) {
  23140. this.mimeType = value;
  23141. return this;
  23142. }
  23143. }
  23144. class AnimationLoader extends Loader {
  23145. constructor( manager ) {
  23146. super( manager );
  23147. }
  23148. load( url, onLoad, onProgress, onError ) {
  23149. const scope = this;
  23150. const loader = new FileLoader( this.manager );
  23151. loader.setPath( this.path );
  23152. loader.setRequestHeader( this.requestHeader );
  23153. loader.setWithCredentials( this.withCredentials );
  23154. loader.load( url, function ( text ) {
  23155. try {
  23156. onLoad( scope.parse( JSON.parse( text ) ) );
  23157. } catch ( e ) {
  23158. if ( onError ) {
  23159. onError( e );
  23160. } else {
  23161. console.error( e );
  23162. }
  23163. scope.manager.itemError( url );
  23164. }
  23165. }, onProgress, onError );
  23166. }
  23167. parse( json ) {
  23168. const animations = [];
  23169. for ( let i = 0; i < json.length; i ++ ) {
  23170. const clip = AnimationClip.parse( json[ i ] );
  23171. animations.push( clip );
  23172. }
  23173. return animations;
  23174. }
  23175. }
  23176. /**
  23177. * Abstract Base class to block based textures loader (dds, pvr, ...)
  23178. *
  23179. * Sub classes have to implement the parse() method which will be used in load().
  23180. */
  23181. class CompressedTextureLoader extends Loader {
  23182. constructor( manager ) {
  23183. super( manager );
  23184. }
  23185. load( url, onLoad, onProgress, onError ) {
  23186. const scope = this;
  23187. const images = [];
  23188. const texture = new CompressedTexture();
  23189. const loader = new FileLoader( this.manager );
  23190. loader.setPath( this.path );
  23191. loader.setResponseType( 'arraybuffer' );
  23192. loader.setRequestHeader( this.requestHeader );
  23193. loader.setWithCredentials( scope.withCredentials );
  23194. let loaded = 0;
  23195. function loadTexture( i ) {
  23196. loader.load( url[ i ], function ( buffer ) {
  23197. const texDatas = scope.parse( buffer, true );
  23198. images[ i ] = {
  23199. width: texDatas.width,
  23200. height: texDatas.height,
  23201. format: texDatas.format,
  23202. mipmaps: texDatas.mipmaps
  23203. };
  23204. loaded += 1;
  23205. if ( loaded === 6 ) {
  23206. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  23207. texture.image = images;
  23208. texture.format = texDatas.format;
  23209. texture.needsUpdate = true;
  23210. if ( onLoad ) onLoad( texture );
  23211. }
  23212. }, onProgress, onError );
  23213. }
  23214. if ( Array.isArray( url ) ) {
  23215. for ( let i = 0, il = url.length; i < il; ++ i ) {
  23216. loadTexture( i );
  23217. }
  23218. } else {
  23219. // compressed cubemap texture stored in a single DDS file
  23220. loader.load( url, function ( buffer ) {
  23221. const texDatas = scope.parse( buffer, true );
  23222. if ( texDatas.isCubemap ) {
  23223. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  23224. for ( let f = 0; f < faces; f ++ ) {
  23225. images[ f ] = { mipmaps: [] };
  23226. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  23227. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  23228. images[ f ].format = texDatas.format;
  23229. images[ f ].width = texDatas.width;
  23230. images[ f ].height = texDatas.height;
  23231. }
  23232. }
  23233. texture.image = images;
  23234. } else {
  23235. texture.image.width = texDatas.width;
  23236. texture.image.height = texDatas.height;
  23237. texture.mipmaps = texDatas.mipmaps;
  23238. }
  23239. if ( texDatas.mipmapCount === 1 ) {
  23240. texture.minFilter = LinearFilter;
  23241. }
  23242. texture.format = texDatas.format;
  23243. texture.needsUpdate = true;
  23244. if ( onLoad ) onLoad( texture );
  23245. }, onProgress, onError );
  23246. }
  23247. return texture;
  23248. }
  23249. }
  23250. class ImageLoader extends Loader {
  23251. constructor( manager ) {
  23252. super( manager );
  23253. }
  23254. load( url, onLoad, onProgress, onError ) {
  23255. if ( this.path !== undefined ) url = this.path + url;
  23256. url = this.manager.resolveURL( url );
  23257. const scope = this;
  23258. const cached = Cache.get( url );
  23259. if ( cached !== undefined ) {
  23260. scope.manager.itemStart( url );
  23261. setTimeout( function () {
  23262. if ( onLoad ) onLoad( cached );
  23263. scope.manager.itemEnd( url );
  23264. }, 0 );
  23265. return cached;
  23266. }
  23267. const image = createElementNS( 'img' );
  23268. function onImageLoad() {
  23269. removeEventListeners();
  23270. Cache.add( url, this );
  23271. if ( onLoad ) onLoad( this );
  23272. scope.manager.itemEnd( url );
  23273. }
  23274. function onImageError( event ) {
  23275. removeEventListeners();
  23276. if ( onError ) onError( event );
  23277. scope.manager.itemError( url );
  23278. scope.manager.itemEnd( url );
  23279. }
  23280. function removeEventListeners() {
  23281. image.removeEventListener( 'load', onImageLoad, false );
  23282. image.removeEventListener( 'error', onImageError, false );
  23283. }
  23284. image.addEventListener( 'load', onImageLoad, false );
  23285. image.addEventListener( 'error', onImageError, false );
  23286. if ( url.substr( 0, 5 ) !== 'data:' ) {
  23287. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  23288. }
  23289. scope.manager.itemStart( url );
  23290. image.src = url;
  23291. return image;
  23292. }
  23293. }
  23294. class CubeTextureLoader extends Loader {
  23295. constructor( manager ) {
  23296. super( manager );
  23297. }
  23298. load( urls, onLoad, onProgress, onError ) {
  23299. const texture = new CubeTexture();
  23300. const loader = new ImageLoader( this.manager );
  23301. loader.setCrossOrigin( this.crossOrigin );
  23302. loader.setPath( this.path );
  23303. let loaded = 0;
  23304. function loadTexture( i ) {
  23305. loader.load( urls[ i ], function ( image ) {
  23306. texture.images[ i ] = image;
  23307. loaded ++;
  23308. if ( loaded === 6 ) {
  23309. texture.needsUpdate = true;
  23310. if ( onLoad ) onLoad( texture );
  23311. }
  23312. }, undefined, onError );
  23313. }
  23314. for ( let i = 0; i < urls.length; ++ i ) {
  23315. loadTexture( i );
  23316. }
  23317. return texture;
  23318. }
  23319. }
  23320. /**
  23321. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  23322. *
  23323. * Sub classes have to implement the parse() method which will be used in load().
  23324. */
  23325. class DataTextureLoader extends Loader {
  23326. constructor( manager ) {
  23327. super( manager );
  23328. }
  23329. load( url, onLoad, onProgress, onError ) {
  23330. const scope = this;
  23331. const texture = new DataTexture();
  23332. const loader = new FileLoader( this.manager );
  23333. loader.setResponseType( 'arraybuffer' );
  23334. loader.setRequestHeader( this.requestHeader );
  23335. loader.setPath( this.path );
  23336. loader.setWithCredentials( scope.withCredentials );
  23337. loader.load( url, function ( buffer ) {
  23338. const texData = scope.parse( buffer );
  23339. if ( ! texData ) return;
  23340. if ( texData.image !== undefined ) {
  23341. texture.image = texData.image;
  23342. } else if ( texData.data !== undefined ) {
  23343. texture.image.width = texData.width;
  23344. texture.image.height = texData.height;
  23345. texture.image.data = texData.data;
  23346. }
  23347. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  23348. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  23349. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  23350. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  23351. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  23352. if ( texData.encoding !== undefined ) {
  23353. texture.encoding = texData.encoding;
  23354. }
  23355. if ( texData.flipY !== undefined ) {
  23356. texture.flipY = texData.flipY;
  23357. }
  23358. if ( texData.format !== undefined ) {
  23359. texture.format = texData.format;
  23360. }
  23361. if ( texData.type !== undefined ) {
  23362. texture.type = texData.type;
  23363. }
  23364. if ( texData.mipmaps !== undefined ) {
  23365. texture.mipmaps = texData.mipmaps;
  23366. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  23367. }
  23368. if ( texData.mipmapCount === 1 ) {
  23369. texture.minFilter = LinearFilter;
  23370. }
  23371. if ( texData.generateMipmaps !== undefined ) {
  23372. texture.generateMipmaps = texData.generateMipmaps;
  23373. }
  23374. texture.needsUpdate = true;
  23375. if ( onLoad ) onLoad( texture, texData );
  23376. }, onProgress, onError );
  23377. return texture;
  23378. }
  23379. }
  23380. class TextureLoader extends Loader {
  23381. constructor( manager ) {
  23382. super( manager );
  23383. }
  23384. load( url, onLoad, onProgress, onError ) {
  23385. const texture = new Texture();
  23386. const loader = new ImageLoader( this.manager );
  23387. loader.setCrossOrigin( this.crossOrigin );
  23388. loader.setPath( this.path );
  23389. loader.load( url, function ( image ) {
  23390. texture.image = image;
  23391. texture.needsUpdate = true;
  23392. if ( onLoad !== undefined ) {
  23393. onLoad( texture );
  23394. }
  23395. }, onProgress, onError );
  23396. return texture;
  23397. }
  23398. }
  23399. class Light extends Object3D {
  23400. constructor( color, intensity = 1 ) {
  23401. super();
  23402. this.type = 'Light';
  23403. this.color = new Color( color );
  23404. this.intensity = intensity;
  23405. }
  23406. dispose() {
  23407. // Empty here in base class; some subclasses override.
  23408. }
  23409. copy( source ) {
  23410. super.copy( source );
  23411. this.color.copy( source.color );
  23412. this.intensity = source.intensity;
  23413. return this;
  23414. }
  23415. toJSON( meta ) {
  23416. const data = super.toJSON( meta );
  23417. data.object.color = this.color.getHex();
  23418. data.object.intensity = this.intensity;
  23419. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  23420. if ( this.distance !== undefined ) data.object.distance = this.distance;
  23421. if ( this.angle !== undefined ) data.object.angle = this.angle;
  23422. if ( this.decay !== undefined ) data.object.decay = this.decay;
  23423. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  23424. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  23425. return data;
  23426. }
  23427. }
  23428. Light.prototype.isLight = true;
  23429. class HemisphereLight extends Light {
  23430. constructor( skyColor, groundColor, intensity ) {
  23431. super( skyColor, intensity );
  23432. this.type = 'HemisphereLight';
  23433. this.position.copy( Object3D.DefaultUp );
  23434. this.updateMatrix();
  23435. this.groundColor = new Color( groundColor );
  23436. }
  23437. copy( source ) {
  23438. Light.prototype.copy.call( this, source );
  23439. this.groundColor.copy( source.groundColor );
  23440. return this;
  23441. }
  23442. }
  23443. HemisphereLight.prototype.isHemisphereLight = true;
  23444. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  23445. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  23446. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  23447. class LightShadow {
  23448. constructor( camera ) {
  23449. this.camera = camera;
  23450. this.bias = 0;
  23451. this.normalBias = 0;
  23452. this.radius = 1;
  23453. this.blurSamples = 8;
  23454. this.mapSize = new Vector2( 512, 512 );
  23455. this.map = null;
  23456. this.mapPass = null;
  23457. this.matrix = new Matrix4();
  23458. this.autoUpdate = true;
  23459. this.needsUpdate = false;
  23460. this._frustum = new Frustum();
  23461. this._frameExtents = new Vector2( 1, 1 );
  23462. this._viewportCount = 1;
  23463. this._viewports = [
  23464. new Vector4( 0, 0, 1, 1 )
  23465. ];
  23466. }
  23467. getViewportCount() {
  23468. return this._viewportCount;
  23469. }
  23470. getFrustum() {
  23471. return this._frustum;
  23472. }
  23473. updateMatrices( light ) {
  23474. const shadowCamera = this.camera;
  23475. const shadowMatrix = this.matrix;
  23476. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  23477. shadowCamera.position.copy( _lightPositionWorld$1 );
  23478. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  23479. shadowCamera.lookAt( _lookTarget$1 );
  23480. shadowCamera.updateMatrixWorld();
  23481. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  23482. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  23483. shadowMatrix.set(
  23484. 0.5, 0.0, 0.0, 0.5,
  23485. 0.0, 0.5, 0.0, 0.5,
  23486. 0.0, 0.0, 0.5, 0.5,
  23487. 0.0, 0.0, 0.0, 1.0
  23488. );
  23489. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  23490. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  23491. }
  23492. getViewport( viewportIndex ) {
  23493. return this._viewports[ viewportIndex ];
  23494. }
  23495. getFrameExtents() {
  23496. return this._frameExtents;
  23497. }
  23498. dispose() {
  23499. if ( this.map ) {
  23500. this.map.dispose();
  23501. }
  23502. if ( this.mapPass ) {
  23503. this.mapPass.dispose();
  23504. }
  23505. }
  23506. copy( source ) {
  23507. this.camera = source.camera.clone();
  23508. this.bias = source.bias;
  23509. this.radius = source.radius;
  23510. this.mapSize.copy( source.mapSize );
  23511. return this;
  23512. }
  23513. clone() {
  23514. return new this.constructor().copy( this );
  23515. }
  23516. toJSON() {
  23517. const object = {};
  23518. if ( this.bias !== 0 ) object.bias = this.bias;
  23519. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  23520. if ( this.radius !== 1 ) object.radius = this.radius;
  23521. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  23522. object.camera = this.camera.toJSON( false ).object;
  23523. delete object.camera.matrix;
  23524. return object;
  23525. }
  23526. }
  23527. class SpotLightShadow extends LightShadow {
  23528. constructor() {
  23529. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  23530. this.focus = 1;
  23531. }
  23532. updateMatrices( light ) {
  23533. const camera = this.camera;
  23534. const fov = RAD2DEG * 2 * light.angle * this.focus;
  23535. const aspect = this.mapSize.width / this.mapSize.height;
  23536. const far = light.distance || camera.far;
  23537. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  23538. camera.fov = fov;
  23539. camera.aspect = aspect;
  23540. camera.far = far;
  23541. camera.updateProjectionMatrix();
  23542. }
  23543. super.updateMatrices( light );
  23544. }
  23545. copy( source ) {
  23546. super.copy( source );
  23547. this.focus = source.focus;
  23548. return this;
  23549. }
  23550. }
  23551. SpotLightShadow.prototype.isSpotLightShadow = true;
  23552. class SpotLight extends Light {
  23553. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 1 ) {
  23554. super( color, intensity );
  23555. this.type = 'SpotLight';
  23556. this.position.copy( Object3D.DefaultUp );
  23557. this.updateMatrix();
  23558. this.target = new Object3D();
  23559. this.distance = distance;
  23560. this.angle = angle;
  23561. this.penumbra = penumbra;
  23562. this.decay = decay; // for physically correct lights, should be 2.
  23563. this.shadow = new SpotLightShadow();
  23564. }
  23565. get power() {
  23566. // compute the light's luminous power (in lumens) from its intensity (in candela)
  23567. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  23568. return this.intensity * Math.PI;
  23569. }
  23570. set power( power ) {
  23571. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  23572. this.intensity = power / Math.PI;
  23573. }
  23574. dispose() {
  23575. this.shadow.dispose();
  23576. }
  23577. copy( source ) {
  23578. super.copy( source );
  23579. this.distance = source.distance;
  23580. this.angle = source.angle;
  23581. this.penumbra = source.penumbra;
  23582. this.decay = source.decay;
  23583. this.target = source.target.clone();
  23584. this.shadow = source.shadow.clone();
  23585. return this;
  23586. }
  23587. }
  23588. SpotLight.prototype.isSpotLight = true;
  23589. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  23590. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  23591. const _lookTarget = /*@__PURE__*/ new Vector3();
  23592. class PointLightShadow extends LightShadow {
  23593. constructor() {
  23594. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  23595. this._frameExtents = new Vector2( 4, 2 );
  23596. this._viewportCount = 6;
  23597. this._viewports = [
  23598. // These viewports map a cube-map onto a 2D texture with the
  23599. // following orientation:
  23600. //
  23601. // xzXZ
  23602. // y Y
  23603. //
  23604. // X - Positive x direction
  23605. // x - Negative x direction
  23606. // Y - Positive y direction
  23607. // y - Negative y direction
  23608. // Z - Positive z direction
  23609. // z - Negative z direction
  23610. // positive X
  23611. new Vector4( 2, 1, 1, 1 ),
  23612. // negative X
  23613. new Vector4( 0, 1, 1, 1 ),
  23614. // positive Z
  23615. new Vector4( 3, 1, 1, 1 ),
  23616. // negative Z
  23617. new Vector4( 1, 1, 1, 1 ),
  23618. // positive Y
  23619. new Vector4( 3, 0, 1, 1 ),
  23620. // negative Y
  23621. new Vector4( 1, 0, 1, 1 )
  23622. ];
  23623. this._cubeDirections = [
  23624. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  23625. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  23626. ];
  23627. this._cubeUps = [
  23628. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  23629. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  23630. ];
  23631. }
  23632. updateMatrices( light, viewportIndex = 0 ) {
  23633. const camera = this.camera;
  23634. const shadowMatrix = this.matrix;
  23635. const far = light.distance || camera.far;
  23636. if ( far !== camera.far ) {
  23637. camera.far = far;
  23638. camera.updateProjectionMatrix();
  23639. }
  23640. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  23641. camera.position.copy( _lightPositionWorld );
  23642. _lookTarget.copy( camera.position );
  23643. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  23644. camera.up.copy( this._cubeUps[ viewportIndex ] );
  23645. camera.lookAt( _lookTarget );
  23646. camera.updateMatrixWorld();
  23647. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  23648. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  23649. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  23650. }
  23651. }
  23652. PointLightShadow.prototype.isPointLightShadow = true;
  23653. class PointLight extends Light {
  23654. constructor( color, intensity, distance = 0, decay = 1 ) {
  23655. super( color, intensity );
  23656. this.type = 'PointLight';
  23657. this.distance = distance;
  23658. this.decay = decay; // for physically correct lights, should be 2.
  23659. this.shadow = new PointLightShadow();
  23660. }
  23661. get power() {
  23662. // compute the light's luminous power (in lumens) from its intensity (in candela)
  23663. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  23664. return this.intensity * 4 * Math.PI;
  23665. }
  23666. set power( power ) {
  23667. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  23668. this.intensity = power / ( 4 * Math.PI );
  23669. }
  23670. dispose() {
  23671. this.shadow.dispose();
  23672. }
  23673. copy( source ) {
  23674. super.copy( source );
  23675. this.distance = source.distance;
  23676. this.decay = source.decay;
  23677. this.shadow = source.shadow.clone();
  23678. return this;
  23679. }
  23680. }
  23681. PointLight.prototype.isPointLight = true;
  23682. class DirectionalLightShadow extends LightShadow {
  23683. constructor() {
  23684. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  23685. }
  23686. }
  23687. DirectionalLightShadow.prototype.isDirectionalLightShadow = true;
  23688. class DirectionalLight extends Light {
  23689. constructor( color, intensity ) {
  23690. super( color, intensity );
  23691. this.type = 'DirectionalLight';
  23692. this.position.copy( Object3D.DefaultUp );
  23693. this.updateMatrix();
  23694. this.target = new Object3D();
  23695. this.shadow = new DirectionalLightShadow();
  23696. }
  23697. dispose() {
  23698. this.shadow.dispose();
  23699. }
  23700. copy( source ) {
  23701. super.copy( source );
  23702. this.target = source.target.clone();
  23703. this.shadow = source.shadow.clone();
  23704. return this;
  23705. }
  23706. }
  23707. DirectionalLight.prototype.isDirectionalLight = true;
  23708. class AmbientLight extends Light {
  23709. constructor( color, intensity ) {
  23710. super( color, intensity );
  23711. this.type = 'AmbientLight';
  23712. }
  23713. }
  23714. AmbientLight.prototype.isAmbientLight = true;
  23715. class RectAreaLight extends Light {
  23716. constructor( color, intensity, width = 10, height = 10 ) {
  23717. super( color, intensity );
  23718. this.type = 'RectAreaLight';
  23719. this.width = width;
  23720. this.height = height;
  23721. }
  23722. get power() {
  23723. // compute the light's luminous power (in lumens) from its intensity (in nits)
  23724. return this.intensity * this.width * this.height * Math.PI;
  23725. }
  23726. set power( power ) {
  23727. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  23728. this.intensity = power / ( this.width * this.height * Math.PI );
  23729. }
  23730. copy( source ) {
  23731. super.copy( source );
  23732. this.width = source.width;
  23733. this.height = source.height;
  23734. return this;
  23735. }
  23736. toJSON( meta ) {
  23737. const data = super.toJSON( meta );
  23738. data.object.width = this.width;
  23739. data.object.height = this.height;
  23740. return data;
  23741. }
  23742. }
  23743. RectAreaLight.prototype.isRectAreaLight = true;
  23744. /**
  23745. * Primary reference:
  23746. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  23747. *
  23748. * Secondary reference:
  23749. * https://www.ppsloan.org/publications/StupidSH36.pdf
  23750. */
  23751. // 3-band SH defined by 9 coefficients
  23752. class SphericalHarmonics3 {
  23753. constructor() {
  23754. this.coefficients = [];
  23755. for ( let i = 0; i < 9; i ++ ) {
  23756. this.coefficients.push( new Vector3() );
  23757. }
  23758. }
  23759. set( coefficients ) {
  23760. for ( let i = 0; i < 9; i ++ ) {
  23761. this.coefficients[ i ].copy( coefficients[ i ] );
  23762. }
  23763. return this;
  23764. }
  23765. zero() {
  23766. for ( let i = 0; i < 9; i ++ ) {
  23767. this.coefficients[ i ].set( 0, 0, 0 );
  23768. }
  23769. return this;
  23770. }
  23771. // get the radiance in the direction of the normal
  23772. // target is a Vector3
  23773. getAt( normal, target ) {
  23774. // normal is assumed to be unit length
  23775. const x = normal.x, y = normal.y, z = normal.z;
  23776. const coeff = this.coefficients;
  23777. // band 0
  23778. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  23779. // band 1
  23780. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  23781. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  23782. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  23783. // band 2
  23784. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  23785. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  23786. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  23787. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  23788. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  23789. return target;
  23790. }
  23791. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  23792. // target is a Vector3
  23793. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  23794. getIrradianceAt( normal, target ) {
  23795. // normal is assumed to be unit length
  23796. const x = normal.x, y = normal.y, z = normal.z;
  23797. const coeff = this.coefficients;
  23798. // band 0
  23799. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  23800. // band 1
  23801. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  23802. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  23803. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  23804. // band 2
  23805. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  23806. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  23807. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  23808. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  23809. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  23810. return target;
  23811. }
  23812. add( sh ) {
  23813. for ( let i = 0; i < 9; i ++ ) {
  23814. this.coefficients[ i ].add( sh.coefficients[ i ] );
  23815. }
  23816. return this;
  23817. }
  23818. addScaledSH( sh, s ) {
  23819. for ( let i = 0; i < 9; i ++ ) {
  23820. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  23821. }
  23822. return this;
  23823. }
  23824. scale( s ) {
  23825. for ( let i = 0; i < 9; i ++ ) {
  23826. this.coefficients[ i ].multiplyScalar( s );
  23827. }
  23828. return this;
  23829. }
  23830. lerp( sh, alpha ) {
  23831. for ( let i = 0; i < 9; i ++ ) {
  23832. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  23833. }
  23834. return this;
  23835. }
  23836. equals( sh ) {
  23837. for ( let i = 0; i < 9; i ++ ) {
  23838. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  23839. return false;
  23840. }
  23841. }
  23842. return true;
  23843. }
  23844. copy( sh ) {
  23845. return this.set( sh.coefficients );
  23846. }
  23847. clone() {
  23848. return new this.constructor().copy( this );
  23849. }
  23850. fromArray( array, offset = 0 ) {
  23851. const coefficients = this.coefficients;
  23852. for ( let i = 0; i < 9; i ++ ) {
  23853. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  23854. }
  23855. return this;
  23856. }
  23857. toArray( array = [], offset = 0 ) {
  23858. const coefficients = this.coefficients;
  23859. for ( let i = 0; i < 9; i ++ ) {
  23860. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  23861. }
  23862. return array;
  23863. }
  23864. // evaluate the basis functions
  23865. // shBasis is an Array[ 9 ]
  23866. static getBasisAt( normal, shBasis ) {
  23867. // normal is assumed to be unit length
  23868. const x = normal.x, y = normal.y, z = normal.z;
  23869. // band 0
  23870. shBasis[ 0 ] = 0.282095;
  23871. // band 1
  23872. shBasis[ 1 ] = 0.488603 * y;
  23873. shBasis[ 2 ] = 0.488603 * z;
  23874. shBasis[ 3 ] = 0.488603 * x;
  23875. // band 2
  23876. shBasis[ 4 ] = 1.092548 * x * y;
  23877. shBasis[ 5 ] = 1.092548 * y * z;
  23878. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  23879. shBasis[ 7 ] = 1.092548 * x * z;
  23880. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  23881. }
  23882. }
  23883. SphericalHarmonics3.prototype.isSphericalHarmonics3 = true;
  23884. class LightProbe extends Light {
  23885. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  23886. super( undefined, intensity );
  23887. this.sh = sh;
  23888. }
  23889. copy( source ) {
  23890. super.copy( source );
  23891. this.sh.copy( source.sh );
  23892. return this;
  23893. }
  23894. fromJSON( json ) {
  23895. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  23896. this.sh.fromArray( json.sh );
  23897. return this;
  23898. }
  23899. toJSON( meta ) {
  23900. const data = super.toJSON( meta );
  23901. data.object.sh = this.sh.toArray();
  23902. return data;
  23903. }
  23904. }
  23905. LightProbe.prototype.isLightProbe = true;
  23906. class MaterialLoader extends Loader {
  23907. constructor( manager ) {
  23908. super( manager );
  23909. this.textures = {};
  23910. }
  23911. load( url, onLoad, onProgress, onError ) {
  23912. const scope = this;
  23913. const loader = new FileLoader( scope.manager );
  23914. loader.setPath( scope.path );
  23915. loader.setRequestHeader( scope.requestHeader );
  23916. loader.setWithCredentials( scope.withCredentials );
  23917. loader.load( url, function ( text ) {
  23918. try {
  23919. onLoad( scope.parse( JSON.parse( text ) ) );
  23920. } catch ( e ) {
  23921. if ( onError ) {
  23922. onError( e );
  23923. } else {
  23924. console.error( e );
  23925. }
  23926. scope.manager.itemError( url );
  23927. }
  23928. }, onProgress, onError );
  23929. }
  23930. parse( json ) {
  23931. const textures = this.textures;
  23932. function getTexture( name ) {
  23933. if ( textures[ name ] === undefined ) {
  23934. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  23935. }
  23936. return textures[ name ];
  23937. }
  23938. const material = new Materials[ json.type ]();
  23939. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  23940. if ( json.name !== undefined ) material.name = json.name;
  23941. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  23942. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  23943. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  23944. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  23945. if ( json.sheenTint !== undefined ) material.sheenTint = new Color().setHex( json.sheenTint );
  23946. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  23947. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  23948. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  23949. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  23950. if ( json.specularTint !== undefined && material.specularTint !== undefined ) material.specularTint.setHex( json.specularTint );
  23951. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  23952. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  23953. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  23954. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  23955. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  23956. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  23957. if ( json.attenuationTint !== undefined && material.attenuationTint !== undefined ) material.attenuationTint.setHex( json.attenuationTint );
  23958. if ( json.fog !== undefined ) material.fog = json.fog;
  23959. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  23960. if ( json.blending !== undefined ) material.blending = json.blending;
  23961. if ( json.combine !== undefined ) material.combine = json.combine;
  23962. if ( json.side !== undefined ) material.side = json.side;
  23963. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  23964. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  23965. if ( json.format !== undefined ) material.format = json.format;
  23966. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  23967. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  23968. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  23969. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  23970. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  23971. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  23972. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  23973. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  23974. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  23975. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  23976. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  23977. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  23978. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  23979. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  23980. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  23981. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  23982. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  23983. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  23984. if ( json.linewidth !== 1 ) material.linewidth = json.linewidth;
  23985. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  23986. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  23987. if ( json.scale !== undefined ) material.scale = json.scale;
  23988. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  23989. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  23990. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  23991. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  23992. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  23993. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  23994. if ( json.visible !== undefined ) material.visible = json.visible;
  23995. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  23996. if ( json.userData !== undefined ) material.userData = json.userData;
  23997. if ( json.vertexColors !== undefined ) {
  23998. if ( typeof json.vertexColors === 'number' ) {
  23999. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  24000. } else {
  24001. material.vertexColors = json.vertexColors;
  24002. }
  24003. }
  24004. // Shader Material
  24005. if ( json.uniforms !== undefined ) {
  24006. for ( const name in json.uniforms ) {
  24007. const uniform = json.uniforms[ name ];
  24008. material.uniforms[ name ] = {};
  24009. switch ( uniform.type ) {
  24010. case 't':
  24011. material.uniforms[ name ].value = getTexture( uniform.value );
  24012. break;
  24013. case 'c':
  24014. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  24015. break;
  24016. case 'v2':
  24017. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  24018. break;
  24019. case 'v3':
  24020. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  24021. break;
  24022. case 'v4':
  24023. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  24024. break;
  24025. case 'm3':
  24026. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  24027. break;
  24028. case 'm4':
  24029. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  24030. break;
  24031. default:
  24032. material.uniforms[ name ].value = uniform.value;
  24033. }
  24034. }
  24035. }
  24036. if ( json.defines !== undefined ) material.defines = json.defines;
  24037. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  24038. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  24039. if ( json.extensions !== undefined ) {
  24040. for ( const key in json.extensions ) {
  24041. material.extensions[ key ] = json.extensions[ key ];
  24042. }
  24043. }
  24044. // Deprecated
  24045. if ( json.shading !== undefined ) material.flatShading = json.shading === 1; // THREE.FlatShading
  24046. // for PointsMaterial
  24047. if ( json.size !== undefined ) material.size = json.size;
  24048. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  24049. // maps
  24050. if ( json.map !== undefined ) material.map = getTexture( json.map );
  24051. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  24052. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  24053. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  24054. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  24055. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  24056. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  24057. if ( json.normalScale !== undefined ) {
  24058. let normalScale = json.normalScale;
  24059. if ( Array.isArray( normalScale ) === false ) {
  24060. // Blender exporter used to export a scalar. See #7459
  24061. normalScale = [ normalScale, normalScale ];
  24062. }
  24063. material.normalScale = new Vector2().fromArray( normalScale );
  24064. }
  24065. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  24066. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  24067. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  24068. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  24069. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  24070. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  24071. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  24072. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  24073. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  24074. if ( json.specularTintMap !== undefined ) material.specularTintMap = getTexture( json.specularTintMap );
  24075. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  24076. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  24077. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  24078. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  24079. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  24080. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  24081. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  24082. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  24083. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  24084. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  24085. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  24086. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  24087. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  24088. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  24089. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  24090. return material;
  24091. }
  24092. setTextures( value ) {
  24093. this.textures = value;
  24094. return this;
  24095. }
  24096. }
  24097. class LoaderUtils {
  24098. static decodeText( array ) {
  24099. if ( typeof TextDecoder !== 'undefined' ) {
  24100. return new TextDecoder().decode( array );
  24101. }
  24102. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  24103. // throws a "maximum call stack size exceeded" error for large arrays.
  24104. let s = '';
  24105. for ( let i = 0, il = array.length; i < il; i ++ ) {
  24106. // Implicitly assumes little-endian.
  24107. s += String.fromCharCode( array[ i ] );
  24108. }
  24109. try {
  24110. // merges multi-byte utf-8 characters.
  24111. return decodeURIComponent( escape( s ) );
  24112. } catch ( e ) { // see #16358
  24113. return s;
  24114. }
  24115. }
  24116. static extractUrlBase( url ) {
  24117. const index = url.lastIndexOf( '/' );
  24118. if ( index === - 1 ) return './';
  24119. return url.substr( 0, index + 1 );
  24120. }
  24121. }
  24122. class InstancedBufferGeometry extends BufferGeometry {
  24123. constructor() {
  24124. super();
  24125. this.type = 'InstancedBufferGeometry';
  24126. this.instanceCount = Infinity;
  24127. }
  24128. copy( source ) {
  24129. super.copy( source );
  24130. this.instanceCount = source.instanceCount;
  24131. return this;
  24132. }
  24133. clone() {
  24134. return new this.constructor().copy( this );
  24135. }
  24136. toJSON() {
  24137. const data = super.toJSON( this );
  24138. data.instanceCount = this.instanceCount;
  24139. data.isInstancedBufferGeometry = true;
  24140. return data;
  24141. }
  24142. }
  24143. InstancedBufferGeometry.prototype.isInstancedBufferGeometry = true;
  24144. class BufferGeometryLoader extends Loader {
  24145. constructor( manager ) {
  24146. super( manager );
  24147. }
  24148. load( url, onLoad, onProgress, onError ) {
  24149. const scope = this;
  24150. const loader = new FileLoader( scope.manager );
  24151. loader.setPath( scope.path );
  24152. loader.setRequestHeader( scope.requestHeader );
  24153. loader.setWithCredentials( scope.withCredentials );
  24154. loader.load( url, function ( text ) {
  24155. try {
  24156. onLoad( scope.parse( JSON.parse( text ) ) );
  24157. } catch ( e ) {
  24158. if ( onError ) {
  24159. onError( e );
  24160. } else {
  24161. console.error( e );
  24162. }
  24163. scope.manager.itemError( url );
  24164. }
  24165. }, onProgress, onError );
  24166. }
  24167. parse( json ) {
  24168. const interleavedBufferMap = {};
  24169. const arrayBufferMap = {};
  24170. function getInterleavedBuffer( json, uuid ) {
  24171. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  24172. const interleavedBuffers = json.interleavedBuffers;
  24173. const interleavedBuffer = interleavedBuffers[ uuid ];
  24174. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  24175. const array = getTypedArray( interleavedBuffer.type, buffer );
  24176. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  24177. ib.uuid = interleavedBuffer.uuid;
  24178. interleavedBufferMap[ uuid ] = ib;
  24179. return ib;
  24180. }
  24181. function getArrayBuffer( json, uuid ) {
  24182. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  24183. const arrayBuffers = json.arrayBuffers;
  24184. const arrayBuffer = arrayBuffers[ uuid ];
  24185. const ab = new Uint32Array( arrayBuffer ).buffer;
  24186. arrayBufferMap[ uuid ] = ab;
  24187. return ab;
  24188. }
  24189. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  24190. const index = json.data.index;
  24191. if ( index !== undefined ) {
  24192. const typedArray = getTypedArray( index.type, index.array );
  24193. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  24194. }
  24195. const attributes = json.data.attributes;
  24196. for ( const key in attributes ) {
  24197. const attribute = attributes[ key ];
  24198. let bufferAttribute;
  24199. if ( attribute.isInterleavedBufferAttribute ) {
  24200. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  24201. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  24202. } else {
  24203. const typedArray = getTypedArray( attribute.type, attribute.array );
  24204. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  24205. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  24206. }
  24207. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  24208. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  24209. if ( attribute.updateRange !== undefined ) {
  24210. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  24211. bufferAttribute.updateRange.count = attribute.updateRange.count;
  24212. }
  24213. geometry.setAttribute( key, bufferAttribute );
  24214. }
  24215. const morphAttributes = json.data.morphAttributes;
  24216. if ( morphAttributes ) {
  24217. for ( const key in morphAttributes ) {
  24218. const attributeArray = morphAttributes[ key ];
  24219. const array = [];
  24220. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  24221. const attribute = attributeArray[ i ];
  24222. let bufferAttribute;
  24223. if ( attribute.isInterleavedBufferAttribute ) {
  24224. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  24225. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  24226. } else {
  24227. const typedArray = getTypedArray( attribute.type, attribute.array );
  24228. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  24229. }
  24230. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  24231. array.push( bufferAttribute );
  24232. }
  24233. geometry.morphAttributes[ key ] = array;
  24234. }
  24235. }
  24236. const morphTargetsRelative = json.data.morphTargetsRelative;
  24237. if ( morphTargetsRelative ) {
  24238. geometry.morphTargetsRelative = true;
  24239. }
  24240. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  24241. if ( groups !== undefined ) {
  24242. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  24243. const group = groups[ i ];
  24244. geometry.addGroup( group.start, group.count, group.materialIndex );
  24245. }
  24246. }
  24247. const boundingSphere = json.data.boundingSphere;
  24248. if ( boundingSphere !== undefined ) {
  24249. const center = new Vector3();
  24250. if ( boundingSphere.center !== undefined ) {
  24251. center.fromArray( boundingSphere.center );
  24252. }
  24253. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  24254. }
  24255. if ( json.name ) geometry.name = json.name;
  24256. if ( json.userData ) geometry.userData = json.userData;
  24257. return geometry;
  24258. }
  24259. }
  24260. class ObjectLoader extends Loader {
  24261. constructor( manager ) {
  24262. super( manager );
  24263. }
  24264. load( url, onLoad, onProgress, onError ) {
  24265. const scope = this;
  24266. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  24267. this.resourcePath = this.resourcePath || path;
  24268. const loader = new FileLoader( this.manager );
  24269. loader.setPath( this.path );
  24270. loader.setRequestHeader( this.requestHeader );
  24271. loader.setWithCredentials( this.withCredentials );
  24272. loader.load( url, function ( text ) {
  24273. let json = null;
  24274. try {
  24275. json = JSON.parse( text );
  24276. } catch ( error ) {
  24277. if ( onError !== undefined ) onError( error );
  24278. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  24279. return;
  24280. }
  24281. const metadata = json.metadata;
  24282. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  24283. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  24284. return;
  24285. }
  24286. scope.parse( json, onLoad );
  24287. }, onProgress, onError );
  24288. }
  24289. async loadAsync( url, onProgress ) {
  24290. const scope = this;
  24291. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  24292. this.resourcePath = this.resourcePath || path;
  24293. const loader = new FileLoader( this.manager );
  24294. loader.setPath( this.path );
  24295. loader.setRequestHeader( this.requestHeader );
  24296. loader.setWithCredentials( this.withCredentials );
  24297. const text = await loader.loadAsync( url, onProgress );
  24298. const json = JSON.parse( text );
  24299. const metadata = json.metadata;
  24300. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  24301. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  24302. }
  24303. return await scope.parseAsync( json );
  24304. }
  24305. parse( json, onLoad ) {
  24306. const animations = this.parseAnimations( json.animations );
  24307. const shapes = this.parseShapes( json.shapes );
  24308. const geometries = this.parseGeometries( json.geometries, shapes );
  24309. const images = this.parseImages( json.images, function () {
  24310. if ( onLoad !== undefined ) onLoad( object );
  24311. } );
  24312. const textures = this.parseTextures( json.textures, images );
  24313. const materials = this.parseMaterials( json.materials, textures );
  24314. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  24315. const skeletons = this.parseSkeletons( json.skeletons, object );
  24316. this.bindSkeletons( object, skeletons );
  24317. //
  24318. if ( onLoad !== undefined ) {
  24319. let hasImages = false;
  24320. for ( const uuid in images ) {
  24321. if ( images[ uuid ] instanceof HTMLImageElement ) {
  24322. hasImages = true;
  24323. break;
  24324. }
  24325. }
  24326. if ( hasImages === false ) onLoad( object );
  24327. }
  24328. return object;
  24329. }
  24330. async parseAsync( json ) {
  24331. const animations = this.parseAnimations( json.animations );
  24332. const shapes = this.parseShapes( json.shapes );
  24333. const geometries = this.parseGeometries( json.geometries, shapes );
  24334. const images = await this.parseImagesAsync( json.images );
  24335. const textures = this.parseTextures( json.textures, images );
  24336. const materials = this.parseMaterials( json.materials, textures );
  24337. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  24338. const skeletons = this.parseSkeletons( json.skeletons, object );
  24339. this.bindSkeletons( object, skeletons );
  24340. return object;
  24341. }
  24342. parseShapes( json ) {
  24343. const shapes = {};
  24344. if ( json !== undefined ) {
  24345. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24346. const shape = new Shape().fromJSON( json[ i ] );
  24347. shapes[ shape.uuid ] = shape;
  24348. }
  24349. }
  24350. return shapes;
  24351. }
  24352. parseSkeletons( json, object ) {
  24353. const skeletons = {};
  24354. const bones = {};
  24355. // generate bone lookup table
  24356. object.traverse( function ( child ) {
  24357. if ( child.isBone ) bones[ child.uuid ] = child;
  24358. } );
  24359. // create skeletons
  24360. if ( json !== undefined ) {
  24361. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24362. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  24363. skeletons[ skeleton.uuid ] = skeleton;
  24364. }
  24365. }
  24366. return skeletons;
  24367. }
  24368. parseGeometries( json, shapes ) {
  24369. const geometries = {};
  24370. if ( json !== undefined ) {
  24371. const bufferGeometryLoader = new BufferGeometryLoader();
  24372. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24373. let geometry;
  24374. const data = json[ i ];
  24375. switch ( data.type ) {
  24376. case 'BufferGeometry':
  24377. case 'InstancedBufferGeometry':
  24378. geometry = bufferGeometryLoader.parse( data );
  24379. break;
  24380. case 'Geometry':
  24381. console.error( 'THREE.ObjectLoader: The legacy Geometry type is no longer supported.' );
  24382. break;
  24383. default:
  24384. if ( data.type in Geometries ) {
  24385. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  24386. } else {
  24387. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  24388. }
  24389. }
  24390. geometry.uuid = data.uuid;
  24391. if ( data.name !== undefined ) geometry.name = data.name;
  24392. if ( geometry.isBufferGeometry === true && data.userData !== undefined ) geometry.userData = data.userData;
  24393. geometries[ data.uuid ] = geometry;
  24394. }
  24395. }
  24396. return geometries;
  24397. }
  24398. parseMaterials( json, textures ) {
  24399. const cache = {}; // MultiMaterial
  24400. const materials = {};
  24401. if ( json !== undefined ) {
  24402. const loader = new MaterialLoader();
  24403. loader.setTextures( textures );
  24404. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24405. const data = json[ i ];
  24406. if ( data.type === 'MultiMaterial' ) {
  24407. // Deprecated
  24408. const array = [];
  24409. for ( let j = 0; j < data.materials.length; j ++ ) {
  24410. const material = data.materials[ j ];
  24411. if ( cache[ material.uuid ] === undefined ) {
  24412. cache[ material.uuid ] = loader.parse( material );
  24413. }
  24414. array.push( cache[ material.uuid ] );
  24415. }
  24416. materials[ data.uuid ] = array;
  24417. } else {
  24418. if ( cache[ data.uuid ] === undefined ) {
  24419. cache[ data.uuid ] = loader.parse( data );
  24420. }
  24421. materials[ data.uuid ] = cache[ data.uuid ];
  24422. }
  24423. }
  24424. }
  24425. return materials;
  24426. }
  24427. parseAnimations( json ) {
  24428. const animations = {};
  24429. if ( json !== undefined ) {
  24430. for ( let i = 0; i < json.length; i ++ ) {
  24431. const data = json[ i ];
  24432. const clip = AnimationClip.parse( data );
  24433. animations[ clip.uuid ] = clip;
  24434. }
  24435. }
  24436. return animations;
  24437. }
  24438. parseImages( json, onLoad ) {
  24439. const scope = this;
  24440. const images = {};
  24441. let loader;
  24442. function loadImage( url ) {
  24443. scope.manager.itemStart( url );
  24444. return loader.load( url, function () {
  24445. scope.manager.itemEnd( url );
  24446. }, undefined, function () {
  24447. scope.manager.itemError( url );
  24448. scope.manager.itemEnd( url );
  24449. } );
  24450. }
  24451. function deserializeImage( image ) {
  24452. if ( typeof image === 'string' ) {
  24453. const url = image;
  24454. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  24455. return loadImage( path );
  24456. } else {
  24457. if ( image.data ) {
  24458. return {
  24459. data: getTypedArray( image.type, image.data ),
  24460. width: image.width,
  24461. height: image.height
  24462. };
  24463. } else {
  24464. return null;
  24465. }
  24466. }
  24467. }
  24468. if ( json !== undefined && json.length > 0 ) {
  24469. const manager = new LoadingManager( onLoad );
  24470. loader = new ImageLoader( manager );
  24471. loader.setCrossOrigin( this.crossOrigin );
  24472. for ( let i = 0, il = json.length; i < il; i ++ ) {
  24473. const image = json[ i ];
  24474. const url = image.url;
  24475. if ( Array.isArray( url ) ) {
  24476. // load array of images e.g CubeTexture
  24477. images[ image.uuid ] = [];
  24478. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  24479. const currentUrl = url[ j ];
  24480. const deserializedImage = deserializeImage( currentUrl );
  24481. if ( deserializedImage !== null ) {
  24482. if ( deserializedImage instanceof HTMLImageElement ) {
  24483. images[ image.uuid ].push( deserializedImage );
  24484. } else {
  24485. // special case: handle array of data textures for cube textures
  24486. images[ image.uuid ].push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  24487. }
  24488. }
  24489. }
  24490. } else {
  24491. // load single image
  24492. const deserializedImage = deserializeImage( image.url );
  24493. if ( deserializedImage !== null ) {
  24494. images[ image.uuid ] = deserializedImage;
  24495. }
  24496. }
  24497. }
  24498. }
  24499. return images;
  24500. }
  24501. async parseImagesAsync( json ) {
  24502. const scope = this;
  24503. const images = {};
  24504. let loader;
  24505. async function deserializeImage( image ) {
  24506. if ( typeof image === 'string' ) {
  24507. const url = image;
  24508. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  24509. return await loader.loadAsync( path );
  24510. } else {
  24511. if ( image.data ) {
  24512. return {
  24513. data: getTypedArray( image.type, image.data ),
  24514. width: image.width,
  24515. height: image.height
  24516. };
  24517. } else {
  24518. return null;
  24519. }
  24520. }
  24521. }
  24522. if ( json !== undefined && json.length > 0 ) {
  24523. loader = new ImageLoader( this.manager );
  24524. loader.setCrossOrigin( this.crossOrigin );
  24525. for ( let i = 0, il = json.length; i < il; i ++ ) {
  24526. const image = json[ i ];
  24527. const url = image.url;
  24528. if ( Array.isArray( url ) ) {
  24529. // load array of images e.g CubeTexture
  24530. images[ image.uuid ] = [];
  24531. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  24532. const currentUrl = url[ j ];
  24533. const deserializedImage = await deserializeImage( currentUrl );
  24534. if ( deserializedImage !== null ) {
  24535. if ( deserializedImage instanceof HTMLImageElement ) {
  24536. images[ image.uuid ].push( deserializedImage );
  24537. } else {
  24538. // special case: handle array of data textures for cube textures
  24539. images[ image.uuid ].push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  24540. }
  24541. }
  24542. }
  24543. } else {
  24544. // load single image
  24545. const deserializedImage = await deserializeImage( image.url );
  24546. if ( deserializedImage !== null ) {
  24547. images[ image.uuid ] = deserializedImage;
  24548. }
  24549. }
  24550. }
  24551. }
  24552. return images;
  24553. }
  24554. parseTextures( json, images ) {
  24555. function parseConstant( value, type ) {
  24556. if ( typeof value === 'number' ) return value;
  24557. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  24558. return type[ value ];
  24559. }
  24560. const textures = {};
  24561. if ( json !== undefined ) {
  24562. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24563. const data = json[ i ];
  24564. if ( data.image === undefined ) {
  24565. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  24566. }
  24567. if ( images[ data.image ] === undefined ) {
  24568. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  24569. }
  24570. let texture;
  24571. const image = images[ data.image ];
  24572. if ( Array.isArray( image ) ) {
  24573. texture = new CubeTexture( image );
  24574. if ( image.length === 6 ) texture.needsUpdate = true;
  24575. } else {
  24576. if ( image && image.data ) {
  24577. texture = new DataTexture( image.data, image.width, image.height );
  24578. } else {
  24579. texture = new Texture( image );
  24580. }
  24581. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  24582. }
  24583. texture.uuid = data.uuid;
  24584. if ( data.name !== undefined ) texture.name = data.name;
  24585. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  24586. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  24587. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  24588. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  24589. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  24590. if ( data.wrap !== undefined ) {
  24591. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  24592. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  24593. }
  24594. if ( data.format !== undefined ) texture.format = data.format;
  24595. if ( data.type !== undefined ) texture.type = data.type;
  24596. if ( data.encoding !== undefined ) texture.encoding = data.encoding;
  24597. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  24598. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  24599. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  24600. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  24601. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  24602. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  24603. textures[ data.uuid ] = texture;
  24604. }
  24605. }
  24606. return textures;
  24607. }
  24608. parseObject( data, geometries, materials, textures, animations ) {
  24609. let object;
  24610. function getGeometry( name ) {
  24611. if ( geometries[ name ] === undefined ) {
  24612. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  24613. }
  24614. return geometries[ name ];
  24615. }
  24616. function getMaterial( name ) {
  24617. if ( name === undefined ) return undefined;
  24618. if ( Array.isArray( name ) ) {
  24619. const array = [];
  24620. for ( let i = 0, l = name.length; i < l; i ++ ) {
  24621. const uuid = name[ i ];
  24622. if ( materials[ uuid ] === undefined ) {
  24623. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  24624. }
  24625. array.push( materials[ uuid ] );
  24626. }
  24627. return array;
  24628. }
  24629. if ( materials[ name ] === undefined ) {
  24630. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  24631. }
  24632. return materials[ name ];
  24633. }
  24634. function getTexture( uuid ) {
  24635. if ( textures[ uuid ] === undefined ) {
  24636. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  24637. }
  24638. return textures[ uuid ];
  24639. }
  24640. let geometry, material;
  24641. switch ( data.type ) {
  24642. case 'Scene':
  24643. object = new Scene();
  24644. if ( data.background !== undefined ) {
  24645. if ( Number.isInteger( data.background ) ) {
  24646. object.background = new Color( data.background );
  24647. } else {
  24648. object.background = getTexture( data.background );
  24649. }
  24650. }
  24651. if ( data.environment !== undefined ) {
  24652. object.environment = getTexture( data.environment );
  24653. }
  24654. if ( data.fog !== undefined ) {
  24655. if ( data.fog.type === 'Fog' ) {
  24656. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  24657. } else if ( data.fog.type === 'FogExp2' ) {
  24658. object.fog = new FogExp2( data.fog.color, data.fog.density );
  24659. }
  24660. }
  24661. break;
  24662. case 'PerspectiveCamera':
  24663. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  24664. if ( data.focus !== undefined ) object.focus = data.focus;
  24665. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  24666. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  24667. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  24668. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  24669. break;
  24670. case 'OrthographicCamera':
  24671. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  24672. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  24673. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  24674. break;
  24675. case 'AmbientLight':
  24676. object = new AmbientLight( data.color, data.intensity );
  24677. break;
  24678. case 'DirectionalLight':
  24679. object = new DirectionalLight( data.color, data.intensity );
  24680. break;
  24681. case 'PointLight':
  24682. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  24683. break;
  24684. case 'RectAreaLight':
  24685. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  24686. break;
  24687. case 'SpotLight':
  24688. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  24689. break;
  24690. case 'HemisphereLight':
  24691. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  24692. break;
  24693. case 'LightProbe':
  24694. object = new LightProbe().fromJSON( data );
  24695. break;
  24696. case 'SkinnedMesh':
  24697. geometry = getGeometry( data.geometry );
  24698. material = getMaterial( data.material );
  24699. object = new SkinnedMesh( geometry, material );
  24700. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  24701. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  24702. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  24703. break;
  24704. case 'Mesh':
  24705. geometry = getGeometry( data.geometry );
  24706. material = getMaterial( data.material );
  24707. object = new Mesh( geometry, material );
  24708. break;
  24709. case 'InstancedMesh':
  24710. geometry = getGeometry( data.geometry );
  24711. material = getMaterial( data.material );
  24712. const count = data.count;
  24713. const instanceMatrix = data.instanceMatrix;
  24714. const instanceColor = data.instanceColor;
  24715. object = new InstancedMesh( geometry, material, count );
  24716. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  24717. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  24718. break;
  24719. case 'LOD':
  24720. object = new LOD();
  24721. break;
  24722. case 'Line':
  24723. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  24724. break;
  24725. case 'LineLoop':
  24726. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  24727. break;
  24728. case 'LineSegments':
  24729. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  24730. break;
  24731. case 'PointCloud':
  24732. case 'Points':
  24733. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  24734. break;
  24735. case 'Sprite':
  24736. object = new Sprite( getMaterial( data.material ) );
  24737. break;
  24738. case 'Group':
  24739. object = new Group();
  24740. break;
  24741. case 'Bone':
  24742. object = new Bone();
  24743. break;
  24744. default:
  24745. object = new Object3D();
  24746. }
  24747. object.uuid = data.uuid;
  24748. if ( data.name !== undefined ) object.name = data.name;
  24749. if ( data.matrix !== undefined ) {
  24750. object.matrix.fromArray( data.matrix );
  24751. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  24752. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  24753. } else {
  24754. if ( data.position !== undefined ) object.position.fromArray( data.position );
  24755. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  24756. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  24757. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  24758. }
  24759. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  24760. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  24761. if ( data.shadow ) {
  24762. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  24763. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  24764. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  24765. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  24766. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  24767. }
  24768. if ( data.visible !== undefined ) object.visible = data.visible;
  24769. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  24770. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  24771. if ( data.userData !== undefined ) object.userData = data.userData;
  24772. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  24773. if ( data.children !== undefined ) {
  24774. const children = data.children;
  24775. for ( let i = 0; i < children.length; i ++ ) {
  24776. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  24777. }
  24778. }
  24779. if ( data.animations !== undefined ) {
  24780. const objectAnimations = data.animations;
  24781. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  24782. const uuid = objectAnimations[ i ];
  24783. object.animations.push( animations[ uuid ] );
  24784. }
  24785. }
  24786. if ( data.type === 'LOD' ) {
  24787. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  24788. const levels = data.levels;
  24789. for ( let l = 0; l < levels.length; l ++ ) {
  24790. const level = levels[ l ];
  24791. const child = object.getObjectByProperty( 'uuid', level.object );
  24792. if ( child !== undefined ) {
  24793. object.addLevel( child, level.distance );
  24794. }
  24795. }
  24796. }
  24797. return object;
  24798. }
  24799. bindSkeletons( object, skeletons ) {
  24800. if ( Object.keys( skeletons ).length === 0 ) return;
  24801. object.traverse( function ( child ) {
  24802. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  24803. const skeleton = skeletons[ child.skeleton ];
  24804. if ( skeleton === undefined ) {
  24805. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  24806. } else {
  24807. child.bind( skeleton, child.bindMatrix );
  24808. }
  24809. }
  24810. } );
  24811. }
  24812. /* DEPRECATED */
  24813. setTexturePath( value ) {
  24814. console.warn( 'THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().' );
  24815. return this.setResourcePath( value );
  24816. }
  24817. }
  24818. const TEXTURE_MAPPING = {
  24819. UVMapping: UVMapping,
  24820. CubeReflectionMapping: CubeReflectionMapping,
  24821. CubeRefractionMapping: CubeRefractionMapping,
  24822. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  24823. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  24824. CubeUVReflectionMapping: CubeUVReflectionMapping,
  24825. CubeUVRefractionMapping: CubeUVRefractionMapping
  24826. };
  24827. const TEXTURE_WRAPPING = {
  24828. RepeatWrapping: RepeatWrapping,
  24829. ClampToEdgeWrapping: ClampToEdgeWrapping,
  24830. MirroredRepeatWrapping: MirroredRepeatWrapping
  24831. };
  24832. const TEXTURE_FILTER = {
  24833. NearestFilter: NearestFilter,
  24834. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  24835. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  24836. LinearFilter: LinearFilter,
  24837. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  24838. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  24839. };
  24840. class ImageBitmapLoader extends Loader {
  24841. constructor( manager ) {
  24842. super( manager );
  24843. if ( typeof createImageBitmap === 'undefined' ) {
  24844. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  24845. }
  24846. if ( typeof fetch === 'undefined' ) {
  24847. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  24848. }
  24849. this.options = { premultiplyAlpha: 'none' };
  24850. }
  24851. setOptions( options ) {
  24852. this.options = options;
  24853. return this;
  24854. }
  24855. load( url, onLoad, onProgress, onError ) {
  24856. if ( url === undefined ) url = '';
  24857. if ( this.path !== undefined ) url = this.path + url;
  24858. url = this.manager.resolveURL( url );
  24859. const scope = this;
  24860. const cached = Cache.get( url );
  24861. if ( cached !== undefined ) {
  24862. scope.manager.itemStart( url );
  24863. setTimeout( function () {
  24864. if ( onLoad ) onLoad( cached );
  24865. scope.manager.itemEnd( url );
  24866. }, 0 );
  24867. return cached;
  24868. }
  24869. const fetchOptions = {};
  24870. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  24871. fetchOptions.headers = this.requestHeader;
  24872. fetch( url, fetchOptions ).then( function ( res ) {
  24873. return res.blob();
  24874. } ).then( function ( blob ) {
  24875. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  24876. } ).then( function ( imageBitmap ) {
  24877. Cache.add( url, imageBitmap );
  24878. if ( onLoad ) onLoad( imageBitmap );
  24879. scope.manager.itemEnd( url );
  24880. } ).catch( function ( e ) {
  24881. if ( onError ) onError( e );
  24882. scope.manager.itemError( url );
  24883. scope.manager.itemEnd( url );
  24884. } );
  24885. scope.manager.itemStart( url );
  24886. }
  24887. }
  24888. ImageBitmapLoader.prototype.isImageBitmapLoader = true;
  24889. let _context;
  24890. const AudioContext = {
  24891. getContext: function () {
  24892. if ( _context === undefined ) {
  24893. _context = new ( window.AudioContext || window.webkitAudioContext )();
  24894. }
  24895. return _context;
  24896. },
  24897. setContext: function ( value ) {
  24898. _context = value;
  24899. }
  24900. };
  24901. class AudioLoader extends Loader {
  24902. constructor( manager ) {
  24903. super( manager );
  24904. }
  24905. load( url, onLoad, onProgress, onError ) {
  24906. const scope = this;
  24907. const loader = new FileLoader( this.manager );
  24908. loader.setResponseType( 'arraybuffer' );
  24909. loader.setPath( this.path );
  24910. loader.setRequestHeader( this.requestHeader );
  24911. loader.setWithCredentials( this.withCredentials );
  24912. loader.load( url, function ( buffer ) {
  24913. try {
  24914. // Create a copy of the buffer. The `decodeAudioData` method
  24915. // detaches the buffer when complete, preventing reuse.
  24916. const bufferCopy = buffer.slice( 0 );
  24917. const context = AudioContext.getContext();
  24918. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  24919. onLoad( audioBuffer );
  24920. } );
  24921. } catch ( e ) {
  24922. if ( onError ) {
  24923. onError( e );
  24924. } else {
  24925. console.error( e );
  24926. }
  24927. scope.manager.itemError( url );
  24928. }
  24929. }, onProgress, onError );
  24930. }
  24931. }
  24932. class HemisphereLightProbe extends LightProbe {
  24933. constructor( skyColor, groundColor, intensity = 1 ) {
  24934. super( undefined, intensity );
  24935. const color1 = new Color().set( skyColor );
  24936. const color2 = new Color().set( groundColor );
  24937. const sky = new Vector3( color1.r, color1.g, color1.b );
  24938. const ground = new Vector3( color2.r, color2.g, color2.b );
  24939. // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  24940. const c0 = Math.sqrt( Math.PI );
  24941. const c1 = c0 * Math.sqrt( 0.75 );
  24942. this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 );
  24943. this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 );
  24944. }
  24945. }
  24946. HemisphereLightProbe.prototype.isHemisphereLightProbe = true;
  24947. class AmbientLightProbe extends LightProbe {
  24948. constructor( color, intensity = 1 ) {
  24949. super( undefined, intensity );
  24950. const color1 = new Color().set( color );
  24951. // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  24952. this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) );
  24953. }
  24954. }
  24955. AmbientLightProbe.prototype.isAmbientLightProbe = true;
  24956. const _eyeRight = /*@__PURE__*/ new Matrix4();
  24957. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  24958. class StereoCamera {
  24959. constructor() {
  24960. this.type = 'StereoCamera';
  24961. this.aspect = 1;
  24962. this.eyeSep = 0.064;
  24963. this.cameraL = new PerspectiveCamera();
  24964. this.cameraL.layers.enable( 1 );
  24965. this.cameraL.matrixAutoUpdate = false;
  24966. this.cameraR = new PerspectiveCamera();
  24967. this.cameraR.layers.enable( 2 );
  24968. this.cameraR.matrixAutoUpdate = false;
  24969. this._cache = {
  24970. focus: null,
  24971. fov: null,
  24972. aspect: null,
  24973. near: null,
  24974. far: null,
  24975. zoom: null,
  24976. eyeSep: null
  24977. };
  24978. }
  24979. update( camera ) {
  24980. const cache = this._cache;
  24981. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  24982. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  24983. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  24984. if ( needsUpdate ) {
  24985. cache.focus = camera.focus;
  24986. cache.fov = camera.fov;
  24987. cache.aspect = camera.aspect * this.aspect;
  24988. cache.near = camera.near;
  24989. cache.far = camera.far;
  24990. cache.zoom = camera.zoom;
  24991. cache.eyeSep = this.eyeSep;
  24992. // Off-axis stereoscopic effect based on
  24993. // http://paulbourke.net/stereographics/stereorender/
  24994. const projectionMatrix = camera.projectionMatrix.clone();
  24995. const eyeSepHalf = cache.eyeSep / 2;
  24996. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  24997. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  24998. let xmin, xmax;
  24999. // translate xOffset
  25000. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  25001. _eyeRight.elements[ 12 ] = eyeSepHalf;
  25002. // for left eye
  25003. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  25004. xmax = ymax * cache.aspect + eyeSepOnProjection;
  25005. projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  25006. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  25007. this.cameraL.projectionMatrix.copy( projectionMatrix );
  25008. // for right eye
  25009. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  25010. xmax = ymax * cache.aspect - eyeSepOnProjection;
  25011. projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  25012. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  25013. this.cameraR.projectionMatrix.copy( projectionMatrix );
  25014. }
  25015. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  25016. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  25017. }
  25018. }
  25019. class Clock {
  25020. constructor( autoStart = true ) {
  25021. this.autoStart = autoStart;
  25022. this.startTime = 0;
  25023. this.oldTime = 0;
  25024. this.elapsedTime = 0;
  25025. this.running = false;
  25026. }
  25027. start() {
  25028. this.startTime = now();
  25029. this.oldTime = this.startTime;
  25030. this.elapsedTime = 0;
  25031. this.running = true;
  25032. }
  25033. stop() {
  25034. this.getElapsedTime();
  25035. this.running = false;
  25036. this.autoStart = false;
  25037. }
  25038. getElapsedTime() {
  25039. this.getDelta();
  25040. return this.elapsedTime;
  25041. }
  25042. getDelta() {
  25043. let diff = 0;
  25044. if ( this.autoStart && ! this.running ) {
  25045. this.start();
  25046. return 0;
  25047. }
  25048. if ( this.running ) {
  25049. const newTime = now();
  25050. diff = ( newTime - this.oldTime ) / 1000;
  25051. this.oldTime = newTime;
  25052. this.elapsedTime += diff;
  25053. }
  25054. return diff;
  25055. }
  25056. }
  25057. function now() {
  25058. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  25059. }
  25060. const _position$1 = /*@__PURE__*/ new Vector3();
  25061. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  25062. const _scale$1 = /*@__PURE__*/ new Vector3();
  25063. const _orientation$1 = /*@__PURE__*/ new Vector3();
  25064. class AudioListener extends Object3D {
  25065. constructor() {
  25066. super();
  25067. this.type = 'AudioListener';
  25068. this.context = AudioContext.getContext();
  25069. this.gain = this.context.createGain();
  25070. this.gain.connect( this.context.destination );
  25071. this.filter = null;
  25072. this.timeDelta = 0;
  25073. // private
  25074. this._clock = new Clock();
  25075. }
  25076. getInput() {
  25077. return this.gain;
  25078. }
  25079. removeFilter() {
  25080. if ( this.filter !== null ) {
  25081. this.gain.disconnect( this.filter );
  25082. this.filter.disconnect( this.context.destination );
  25083. this.gain.connect( this.context.destination );
  25084. this.filter = null;
  25085. }
  25086. return this;
  25087. }
  25088. getFilter() {
  25089. return this.filter;
  25090. }
  25091. setFilter( value ) {
  25092. if ( this.filter !== null ) {
  25093. this.gain.disconnect( this.filter );
  25094. this.filter.disconnect( this.context.destination );
  25095. } else {
  25096. this.gain.disconnect( this.context.destination );
  25097. }
  25098. this.filter = value;
  25099. this.gain.connect( this.filter );
  25100. this.filter.connect( this.context.destination );
  25101. return this;
  25102. }
  25103. getMasterVolume() {
  25104. return this.gain.gain.value;
  25105. }
  25106. setMasterVolume( value ) {
  25107. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  25108. return this;
  25109. }
  25110. updateMatrixWorld( force ) {
  25111. super.updateMatrixWorld( force );
  25112. const listener = this.context.listener;
  25113. const up = this.up;
  25114. this.timeDelta = this._clock.getDelta();
  25115. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  25116. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  25117. if ( listener.positionX ) {
  25118. // code path for Chrome (see #14393)
  25119. const endTime = this.context.currentTime + this.timeDelta;
  25120. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  25121. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  25122. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  25123. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  25124. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  25125. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  25126. listener.upX.linearRampToValueAtTime( up.x, endTime );
  25127. listener.upY.linearRampToValueAtTime( up.y, endTime );
  25128. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  25129. } else {
  25130. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  25131. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  25132. }
  25133. }
  25134. }
  25135. class Audio extends Object3D {
  25136. constructor( listener ) {
  25137. super();
  25138. this.type = 'Audio';
  25139. this.listener = listener;
  25140. this.context = listener.context;
  25141. this.gain = this.context.createGain();
  25142. this.gain.connect( listener.getInput() );
  25143. this.autoplay = false;
  25144. this.buffer = null;
  25145. this.detune = 0;
  25146. this.loop = false;
  25147. this.loopStart = 0;
  25148. this.loopEnd = 0;
  25149. this.offset = 0;
  25150. this.duration = undefined;
  25151. this.playbackRate = 1;
  25152. this.isPlaying = false;
  25153. this.hasPlaybackControl = true;
  25154. this.source = null;
  25155. this.sourceType = 'empty';
  25156. this._startedAt = 0;
  25157. this._progress = 0;
  25158. this._connected = false;
  25159. this.filters = [];
  25160. }
  25161. getOutput() {
  25162. return this.gain;
  25163. }
  25164. setNodeSource( audioNode ) {
  25165. this.hasPlaybackControl = false;
  25166. this.sourceType = 'audioNode';
  25167. this.source = audioNode;
  25168. this.connect();
  25169. return this;
  25170. }
  25171. setMediaElementSource( mediaElement ) {
  25172. this.hasPlaybackControl = false;
  25173. this.sourceType = 'mediaNode';
  25174. this.source = this.context.createMediaElementSource( mediaElement );
  25175. this.connect();
  25176. return this;
  25177. }
  25178. setMediaStreamSource( mediaStream ) {
  25179. this.hasPlaybackControl = false;
  25180. this.sourceType = 'mediaStreamNode';
  25181. this.source = this.context.createMediaStreamSource( mediaStream );
  25182. this.connect();
  25183. return this;
  25184. }
  25185. setBuffer( audioBuffer ) {
  25186. this.buffer = audioBuffer;
  25187. this.sourceType = 'buffer';
  25188. if ( this.autoplay ) this.play();
  25189. return this;
  25190. }
  25191. play( delay = 0 ) {
  25192. if ( this.isPlaying === true ) {
  25193. console.warn( 'THREE.Audio: Audio is already playing.' );
  25194. return;
  25195. }
  25196. if ( this.hasPlaybackControl === false ) {
  25197. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25198. return;
  25199. }
  25200. this._startedAt = this.context.currentTime + delay;
  25201. const source = this.context.createBufferSource();
  25202. source.buffer = this.buffer;
  25203. source.loop = this.loop;
  25204. source.loopStart = this.loopStart;
  25205. source.loopEnd = this.loopEnd;
  25206. source.onended = this.onEnded.bind( this );
  25207. source.start( this._startedAt, this._progress + this.offset, this.duration );
  25208. this.isPlaying = true;
  25209. this.source = source;
  25210. this.setDetune( this.detune );
  25211. this.setPlaybackRate( this.playbackRate );
  25212. return this.connect();
  25213. }
  25214. pause() {
  25215. if ( this.hasPlaybackControl === false ) {
  25216. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25217. return;
  25218. }
  25219. if ( this.isPlaying === true ) {
  25220. // update current progress
  25221. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  25222. if ( this.loop === true ) {
  25223. // ensure _progress does not exceed duration with looped audios
  25224. this._progress = this._progress % ( this.duration || this.buffer.duration );
  25225. }
  25226. this.source.stop();
  25227. this.source.onended = null;
  25228. this.isPlaying = false;
  25229. }
  25230. return this;
  25231. }
  25232. stop() {
  25233. if ( this.hasPlaybackControl === false ) {
  25234. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25235. return;
  25236. }
  25237. this._progress = 0;
  25238. this.source.stop();
  25239. this.source.onended = null;
  25240. this.isPlaying = false;
  25241. return this;
  25242. }
  25243. connect() {
  25244. if ( this.filters.length > 0 ) {
  25245. this.source.connect( this.filters[ 0 ] );
  25246. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  25247. this.filters[ i - 1 ].connect( this.filters[ i ] );
  25248. }
  25249. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  25250. } else {
  25251. this.source.connect( this.getOutput() );
  25252. }
  25253. this._connected = true;
  25254. return this;
  25255. }
  25256. disconnect() {
  25257. if ( this.filters.length > 0 ) {
  25258. this.source.disconnect( this.filters[ 0 ] );
  25259. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  25260. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  25261. }
  25262. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  25263. } else {
  25264. this.source.disconnect( this.getOutput() );
  25265. }
  25266. this._connected = false;
  25267. return this;
  25268. }
  25269. getFilters() {
  25270. return this.filters;
  25271. }
  25272. setFilters( value ) {
  25273. if ( ! value ) value = [];
  25274. if ( this._connected === true ) {
  25275. this.disconnect();
  25276. this.filters = value.slice();
  25277. this.connect();
  25278. } else {
  25279. this.filters = value.slice();
  25280. }
  25281. return this;
  25282. }
  25283. setDetune( value ) {
  25284. this.detune = value;
  25285. if ( this.source.detune === undefined ) return; // only set detune when available
  25286. if ( this.isPlaying === true ) {
  25287. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  25288. }
  25289. return this;
  25290. }
  25291. getDetune() {
  25292. return this.detune;
  25293. }
  25294. getFilter() {
  25295. return this.getFilters()[ 0 ];
  25296. }
  25297. setFilter( filter ) {
  25298. return this.setFilters( filter ? [ filter ] : [] );
  25299. }
  25300. setPlaybackRate( value ) {
  25301. if ( this.hasPlaybackControl === false ) {
  25302. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25303. return;
  25304. }
  25305. this.playbackRate = value;
  25306. if ( this.isPlaying === true ) {
  25307. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  25308. }
  25309. return this;
  25310. }
  25311. getPlaybackRate() {
  25312. return this.playbackRate;
  25313. }
  25314. onEnded() {
  25315. this.isPlaying = false;
  25316. }
  25317. getLoop() {
  25318. if ( this.hasPlaybackControl === false ) {
  25319. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25320. return false;
  25321. }
  25322. return this.loop;
  25323. }
  25324. setLoop( value ) {
  25325. if ( this.hasPlaybackControl === false ) {
  25326. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25327. return;
  25328. }
  25329. this.loop = value;
  25330. if ( this.isPlaying === true ) {
  25331. this.source.loop = this.loop;
  25332. }
  25333. return this;
  25334. }
  25335. setLoopStart( value ) {
  25336. this.loopStart = value;
  25337. return this;
  25338. }
  25339. setLoopEnd( value ) {
  25340. this.loopEnd = value;
  25341. return this;
  25342. }
  25343. getVolume() {
  25344. return this.gain.gain.value;
  25345. }
  25346. setVolume( value ) {
  25347. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  25348. return this;
  25349. }
  25350. }
  25351. const _position = /*@__PURE__*/ new Vector3();
  25352. const _quaternion = /*@__PURE__*/ new Quaternion();
  25353. const _scale = /*@__PURE__*/ new Vector3();
  25354. const _orientation = /*@__PURE__*/ new Vector3();
  25355. class PositionalAudio extends Audio {
  25356. constructor( listener ) {
  25357. super( listener );
  25358. this.panner = this.context.createPanner();
  25359. this.panner.panningModel = 'HRTF';
  25360. this.panner.connect( this.gain );
  25361. }
  25362. getOutput() {
  25363. return this.panner;
  25364. }
  25365. getRefDistance() {
  25366. return this.panner.refDistance;
  25367. }
  25368. setRefDistance( value ) {
  25369. this.panner.refDistance = value;
  25370. return this;
  25371. }
  25372. getRolloffFactor() {
  25373. return this.panner.rolloffFactor;
  25374. }
  25375. setRolloffFactor( value ) {
  25376. this.panner.rolloffFactor = value;
  25377. return this;
  25378. }
  25379. getDistanceModel() {
  25380. return this.panner.distanceModel;
  25381. }
  25382. setDistanceModel( value ) {
  25383. this.panner.distanceModel = value;
  25384. return this;
  25385. }
  25386. getMaxDistance() {
  25387. return this.panner.maxDistance;
  25388. }
  25389. setMaxDistance( value ) {
  25390. this.panner.maxDistance = value;
  25391. return this;
  25392. }
  25393. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  25394. this.panner.coneInnerAngle = coneInnerAngle;
  25395. this.panner.coneOuterAngle = coneOuterAngle;
  25396. this.panner.coneOuterGain = coneOuterGain;
  25397. return this;
  25398. }
  25399. updateMatrixWorld( force ) {
  25400. super.updateMatrixWorld( force );
  25401. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  25402. this.matrixWorld.decompose( _position, _quaternion, _scale );
  25403. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  25404. const panner = this.panner;
  25405. if ( panner.positionX ) {
  25406. // code path for Chrome and Firefox (see #14393)
  25407. const endTime = this.context.currentTime + this.listener.timeDelta;
  25408. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  25409. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  25410. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  25411. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  25412. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  25413. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  25414. } else {
  25415. panner.setPosition( _position.x, _position.y, _position.z );
  25416. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  25417. }
  25418. }
  25419. }
  25420. class AudioAnalyser {
  25421. constructor( audio, fftSize = 2048 ) {
  25422. this.analyser = audio.context.createAnalyser();
  25423. this.analyser.fftSize = fftSize;
  25424. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  25425. audio.getOutput().connect( this.analyser );
  25426. }
  25427. getFrequencyData() {
  25428. this.analyser.getByteFrequencyData( this.data );
  25429. return this.data;
  25430. }
  25431. getAverageFrequency() {
  25432. let value = 0;
  25433. const data = this.getFrequencyData();
  25434. for ( let i = 0; i < data.length; i ++ ) {
  25435. value += data[ i ];
  25436. }
  25437. return value / data.length;
  25438. }
  25439. }
  25440. class PropertyMixer {
  25441. constructor( binding, typeName, valueSize ) {
  25442. this.binding = binding;
  25443. this.valueSize = valueSize;
  25444. let mixFunction,
  25445. mixFunctionAdditive,
  25446. setIdentity;
  25447. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  25448. //
  25449. // interpolators can use .buffer as their .result
  25450. // the data then goes to 'incoming'
  25451. //
  25452. // 'accu0' and 'accu1' are used frame-interleaved for
  25453. // the cumulative result and are compared to detect
  25454. // changes
  25455. //
  25456. // 'orig' stores the original state of the property
  25457. //
  25458. // 'add' is used for additive cumulative results
  25459. //
  25460. // 'work' is optional and is only present for quaternion types. It is used
  25461. // to store intermediate quaternion multiplication results
  25462. switch ( typeName ) {
  25463. case 'quaternion':
  25464. mixFunction = this._slerp;
  25465. mixFunctionAdditive = this._slerpAdditive;
  25466. setIdentity = this._setAdditiveIdentityQuaternion;
  25467. this.buffer = new Float64Array( valueSize * 6 );
  25468. this._workIndex = 5;
  25469. break;
  25470. case 'string':
  25471. case 'bool':
  25472. mixFunction = this._select;
  25473. // Use the regular mix function and for additive on these types,
  25474. // additive is not relevant for non-numeric types
  25475. mixFunctionAdditive = this._select;
  25476. setIdentity = this._setAdditiveIdentityOther;
  25477. this.buffer = new Array( valueSize * 5 );
  25478. break;
  25479. default:
  25480. mixFunction = this._lerp;
  25481. mixFunctionAdditive = this._lerpAdditive;
  25482. setIdentity = this._setAdditiveIdentityNumeric;
  25483. this.buffer = new Float64Array( valueSize * 5 );
  25484. }
  25485. this._mixBufferRegion = mixFunction;
  25486. this._mixBufferRegionAdditive = mixFunctionAdditive;
  25487. this._setIdentity = setIdentity;
  25488. this._origIndex = 3;
  25489. this._addIndex = 4;
  25490. this.cumulativeWeight = 0;
  25491. this.cumulativeWeightAdditive = 0;
  25492. this.useCount = 0;
  25493. this.referenceCount = 0;
  25494. }
  25495. // accumulate data in the 'incoming' region into 'accu<i>'
  25496. accumulate( accuIndex, weight ) {
  25497. // note: happily accumulating nothing when weight = 0, the caller knows
  25498. // the weight and shouldn't have made the call in the first place
  25499. const buffer = this.buffer,
  25500. stride = this.valueSize,
  25501. offset = accuIndex * stride + stride;
  25502. let currentWeight = this.cumulativeWeight;
  25503. if ( currentWeight === 0 ) {
  25504. // accuN := incoming * weight
  25505. for ( let i = 0; i !== stride; ++ i ) {
  25506. buffer[ offset + i ] = buffer[ i ];
  25507. }
  25508. currentWeight = weight;
  25509. } else {
  25510. // accuN := accuN + incoming * weight
  25511. currentWeight += weight;
  25512. const mix = weight / currentWeight;
  25513. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  25514. }
  25515. this.cumulativeWeight = currentWeight;
  25516. }
  25517. // accumulate data in the 'incoming' region into 'add'
  25518. accumulateAdditive( weight ) {
  25519. const buffer = this.buffer,
  25520. stride = this.valueSize,
  25521. offset = stride * this._addIndex;
  25522. if ( this.cumulativeWeightAdditive === 0 ) {
  25523. // add = identity
  25524. this._setIdentity();
  25525. }
  25526. // add := add + incoming * weight
  25527. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  25528. this.cumulativeWeightAdditive += weight;
  25529. }
  25530. // apply the state of 'accu<i>' to the binding when accus differ
  25531. apply( accuIndex ) {
  25532. const stride = this.valueSize,
  25533. buffer = this.buffer,
  25534. offset = accuIndex * stride + stride,
  25535. weight = this.cumulativeWeight,
  25536. weightAdditive = this.cumulativeWeightAdditive,
  25537. binding = this.binding;
  25538. this.cumulativeWeight = 0;
  25539. this.cumulativeWeightAdditive = 0;
  25540. if ( weight < 1 ) {
  25541. // accuN := accuN + original * ( 1 - cumulativeWeight )
  25542. const originalValueOffset = stride * this._origIndex;
  25543. this._mixBufferRegion(
  25544. buffer, offset, originalValueOffset, 1 - weight, stride );
  25545. }
  25546. if ( weightAdditive > 0 ) {
  25547. // accuN := accuN + additive accuN
  25548. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  25549. }
  25550. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  25551. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  25552. // value has changed -> update scene graph
  25553. binding.setValue( buffer, offset );
  25554. break;
  25555. }
  25556. }
  25557. }
  25558. // remember the state of the bound property and copy it to both accus
  25559. saveOriginalState() {
  25560. const binding = this.binding;
  25561. const buffer = this.buffer,
  25562. stride = this.valueSize,
  25563. originalValueOffset = stride * this._origIndex;
  25564. binding.getValue( buffer, originalValueOffset );
  25565. // accu[0..1] := orig -- initially detect changes against the original
  25566. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  25567. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  25568. }
  25569. // Add to identity for additive
  25570. this._setIdentity();
  25571. this.cumulativeWeight = 0;
  25572. this.cumulativeWeightAdditive = 0;
  25573. }
  25574. // apply the state previously taken via 'saveOriginalState' to the binding
  25575. restoreOriginalState() {
  25576. const originalValueOffset = this.valueSize * 3;
  25577. this.binding.setValue( this.buffer, originalValueOffset );
  25578. }
  25579. _setAdditiveIdentityNumeric() {
  25580. const startIndex = this._addIndex * this.valueSize;
  25581. const endIndex = startIndex + this.valueSize;
  25582. for ( let i = startIndex; i < endIndex; i ++ ) {
  25583. this.buffer[ i ] = 0;
  25584. }
  25585. }
  25586. _setAdditiveIdentityQuaternion() {
  25587. this._setAdditiveIdentityNumeric();
  25588. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  25589. }
  25590. _setAdditiveIdentityOther() {
  25591. const startIndex = this._origIndex * this.valueSize;
  25592. const targetIndex = this._addIndex * this.valueSize;
  25593. for ( let i = 0; i < this.valueSize; i ++ ) {
  25594. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  25595. }
  25596. }
  25597. // mix functions
  25598. _select( buffer, dstOffset, srcOffset, t, stride ) {
  25599. if ( t >= 0.5 ) {
  25600. for ( let i = 0; i !== stride; ++ i ) {
  25601. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  25602. }
  25603. }
  25604. }
  25605. _slerp( buffer, dstOffset, srcOffset, t ) {
  25606. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  25607. }
  25608. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  25609. const workOffset = this._workIndex * stride;
  25610. // Store result in intermediate buffer offset
  25611. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  25612. // Slerp to the intermediate result
  25613. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  25614. }
  25615. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  25616. const s = 1 - t;
  25617. for ( let i = 0; i !== stride; ++ i ) {
  25618. const j = dstOffset + i;
  25619. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  25620. }
  25621. }
  25622. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  25623. for ( let i = 0; i !== stride; ++ i ) {
  25624. const j = dstOffset + i;
  25625. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  25626. }
  25627. }
  25628. }
  25629. // Characters [].:/ are reserved for track binding syntax.
  25630. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  25631. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  25632. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  25633. // only latin characters, and the unicode \p{L} is not yet supported. So
  25634. // instead, we exclude reserved characters and match everything else.
  25635. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  25636. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  25637. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  25638. // be matched to parse the rest of the track name.
  25639. const _directoryRe = /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  25640. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  25641. const _nodeRe = /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  25642. // Object on target node, and accessor. May not contain reserved
  25643. // characters. Accessor may contain any character except closing bracket.
  25644. const _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  25645. // Property and accessor. May not contain reserved characters. Accessor may
  25646. // contain any non-bracket characters.
  25647. const _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  25648. const _trackRe = new RegExp( ''
  25649. + '^'
  25650. + _directoryRe
  25651. + _nodeRe
  25652. + _objectRe
  25653. + _propertyRe
  25654. + '$'
  25655. );
  25656. const _supportedObjectNames = [ 'material', 'materials', 'bones' ];
  25657. class Composite {
  25658. constructor( targetGroup, path, optionalParsedPath ) {
  25659. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  25660. this._targetGroup = targetGroup;
  25661. this._bindings = targetGroup.subscribe_( path, parsedPath );
  25662. }
  25663. getValue( array, offset ) {
  25664. this.bind(); // bind all binding
  25665. const firstValidIndex = this._targetGroup.nCachedObjects_,
  25666. binding = this._bindings[ firstValidIndex ];
  25667. // and only call .getValue on the first
  25668. if ( binding !== undefined ) binding.getValue( array, offset );
  25669. }
  25670. setValue( array, offset ) {
  25671. const bindings = this._bindings;
  25672. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  25673. bindings[ i ].setValue( array, offset );
  25674. }
  25675. }
  25676. bind() {
  25677. const bindings = this._bindings;
  25678. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  25679. bindings[ i ].bind();
  25680. }
  25681. }
  25682. unbind() {
  25683. const bindings = this._bindings;
  25684. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  25685. bindings[ i ].unbind();
  25686. }
  25687. }
  25688. }
  25689. // Note: This class uses a State pattern on a per-method basis:
  25690. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  25691. // prototype version of these methods with one that represents
  25692. // the bound state. When the property is not found, the methods
  25693. // become no-ops.
  25694. class PropertyBinding {
  25695. constructor( rootNode, path, parsedPath ) {
  25696. this.path = path;
  25697. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  25698. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
  25699. this.rootNode = rootNode;
  25700. // initial state of these methods that calls 'bind'
  25701. this.getValue = this._getValue_unbound;
  25702. this.setValue = this._setValue_unbound;
  25703. }
  25704. static create( root, path, parsedPath ) {
  25705. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  25706. return new PropertyBinding( root, path, parsedPath );
  25707. } else {
  25708. return new PropertyBinding.Composite( root, path, parsedPath );
  25709. }
  25710. }
  25711. /**
  25712. * Replaces spaces with underscores and removes unsupported characters from
  25713. * node names, to ensure compatibility with parseTrackName().
  25714. *
  25715. * @param {string} name Node name to be sanitized.
  25716. * @return {string}
  25717. */
  25718. static sanitizeNodeName( name ) {
  25719. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  25720. }
  25721. static parseTrackName( trackName ) {
  25722. const matches = _trackRe.exec( trackName );
  25723. if ( ! matches ) {
  25724. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  25725. }
  25726. const results = {
  25727. // directoryName: matches[ 1 ], // (tschw) currently unused
  25728. nodeName: matches[ 2 ],
  25729. objectName: matches[ 3 ],
  25730. objectIndex: matches[ 4 ],
  25731. propertyName: matches[ 5 ], // required
  25732. propertyIndex: matches[ 6 ]
  25733. };
  25734. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  25735. if ( lastDot !== undefined && lastDot !== - 1 ) {
  25736. const objectName = results.nodeName.substring( lastDot + 1 );
  25737. // Object names must be checked against an allowlist. Otherwise, there
  25738. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  25739. // 'bar' could be the objectName, or part of a nodeName (which can
  25740. // include '.' characters).
  25741. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  25742. results.nodeName = results.nodeName.substring( 0, lastDot );
  25743. results.objectName = objectName;
  25744. }
  25745. }
  25746. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  25747. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  25748. }
  25749. return results;
  25750. }
  25751. static findNode( root, nodeName ) {
  25752. if ( ! nodeName || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  25753. return root;
  25754. }
  25755. // search into skeleton bones.
  25756. if ( root.skeleton ) {
  25757. const bone = root.skeleton.getBoneByName( nodeName );
  25758. if ( bone !== undefined ) {
  25759. return bone;
  25760. }
  25761. }
  25762. // search into node subtree.
  25763. if ( root.children ) {
  25764. const searchNodeSubtree = function ( children ) {
  25765. for ( let i = 0; i < children.length; i ++ ) {
  25766. const childNode = children[ i ];
  25767. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  25768. return childNode;
  25769. }
  25770. const result = searchNodeSubtree( childNode.children );
  25771. if ( result ) return result;
  25772. }
  25773. return null;
  25774. };
  25775. const subTreeNode = searchNodeSubtree( root.children );
  25776. if ( subTreeNode ) {
  25777. return subTreeNode;
  25778. }
  25779. }
  25780. return null;
  25781. }
  25782. // these are used to "bind" a nonexistent property
  25783. _getValue_unavailable() {}
  25784. _setValue_unavailable() {}
  25785. // Getters
  25786. _getValue_direct( buffer, offset ) {
  25787. buffer[ offset ] = this.targetObject[ this.propertyName ];
  25788. }
  25789. _getValue_array( buffer, offset ) {
  25790. const source = this.resolvedProperty;
  25791. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  25792. buffer[ offset ++ ] = source[ i ];
  25793. }
  25794. }
  25795. _getValue_arrayElement( buffer, offset ) {
  25796. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  25797. }
  25798. _getValue_toArray( buffer, offset ) {
  25799. this.resolvedProperty.toArray( buffer, offset );
  25800. }
  25801. // Direct
  25802. _setValue_direct( buffer, offset ) {
  25803. this.targetObject[ this.propertyName ] = buffer[ offset ];
  25804. }
  25805. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  25806. this.targetObject[ this.propertyName ] = buffer[ offset ];
  25807. this.targetObject.needsUpdate = true;
  25808. }
  25809. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  25810. this.targetObject[ this.propertyName ] = buffer[ offset ];
  25811. this.targetObject.matrixWorldNeedsUpdate = true;
  25812. }
  25813. // EntireArray
  25814. _setValue_array( buffer, offset ) {
  25815. const dest = this.resolvedProperty;
  25816. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  25817. dest[ i ] = buffer[ offset ++ ];
  25818. }
  25819. }
  25820. _setValue_array_setNeedsUpdate( buffer, offset ) {
  25821. const dest = this.resolvedProperty;
  25822. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  25823. dest[ i ] = buffer[ offset ++ ];
  25824. }
  25825. this.targetObject.needsUpdate = true;
  25826. }
  25827. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  25828. const dest = this.resolvedProperty;
  25829. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  25830. dest[ i ] = buffer[ offset ++ ];
  25831. }
  25832. this.targetObject.matrixWorldNeedsUpdate = true;
  25833. }
  25834. // ArrayElement
  25835. _setValue_arrayElement( buffer, offset ) {
  25836. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  25837. }
  25838. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  25839. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  25840. this.targetObject.needsUpdate = true;
  25841. }
  25842. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  25843. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  25844. this.targetObject.matrixWorldNeedsUpdate = true;
  25845. }
  25846. // HasToFromArray
  25847. _setValue_fromArray( buffer, offset ) {
  25848. this.resolvedProperty.fromArray( buffer, offset );
  25849. }
  25850. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  25851. this.resolvedProperty.fromArray( buffer, offset );
  25852. this.targetObject.needsUpdate = true;
  25853. }
  25854. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  25855. this.resolvedProperty.fromArray( buffer, offset );
  25856. this.targetObject.matrixWorldNeedsUpdate = true;
  25857. }
  25858. _getValue_unbound( targetArray, offset ) {
  25859. this.bind();
  25860. this.getValue( targetArray, offset );
  25861. }
  25862. _setValue_unbound( sourceArray, offset ) {
  25863. this.bind();
  25864. this.setValue( sourceArray, offset );
  25865. }
  25866. // create getter / setter pair for a property in the scene graph
  25867. bind() {
  25868. let targetObject = this.node;
  25869. const parsedPath = this.parsedPath;
  25870. const objectName = parsedPath.objectName;
  25871. const propertyName = parsedPath.propertyName;
  25872. let propertyIndex = parsedPath.propertyIndex;
  25873. if ( ! targetObject ) {
  25874. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode;
  25875. this.node = targetObject;
  25876. }
  25877. // set fail state so we can just 'return' on error
  25878. this.getValue = this._getValue_unavailable;
  25879. this.setValue = this._setValue_unavailable;
  25880. // ensure there is a value node
  25881. if ( ! targetObject ) {
  25882. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  25883. return;
  25884. }
  25885. if ( objectName ) {
  25886. let objectIndex = parsedPath.objectIndex;
  25887. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  25888. switch ( objectName ) {
  25889. case 'materials':
  25890. if ( ! targetObject.material ) {
  25891. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  25892. return;
  25893. }
  25894. if ( ! targetObject.material.materials ) {
  25895. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  25896. return;
  25897. }
  25898. targetObject = targetObject.material.materials;
  25899. break;
  25900. case 'bones':
  25901. if ( ! targetObject.skeleton ) {
  25902. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  25903. return;
  25904. }
  25905. // potential future optimization: skip this if propertyIndex is already an integer
  25906. // and convert the integer string to a true integer.
  25907. targetObject = targetObject.skeleton.bones;
  25908. // support resolving morphTarget names into indices.
  25909. for ( let i = 0; i < targetObject.length; i ++ ) {
  25910. if ( targetObject[ i ].name === objectIndex ) {
  25911. objectIndex = i;
  25912. break;
  25913. }
  25914. }
  25915. break;
  25916. default:
  25917. if ( targetObject[ objectName ] === undefined ) {
  25918. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  25919. return;
  25920. }
  25921. targetObject = targetObject[ objectName ];
  25922. }
  25923. if ( objectIndex !== undefined ) {
  25924. if ( targetObject[ objectIndex ] === undefined ) {
  25925. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  25926. return;
  25927. }
  25928. targetObject = targetObject[ objectIndex ];
  25929. }
  25930. }
  25931. // resolve property
  25932. const nodeProperty = targetObject[ propertyName ];
  25933. if ( nodeProperty === undefined ) {
  25934. const nodeName = parsedPath.nodeName;
  25935. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  25936. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  25937. return;
  25938. }
  25939. // determine versioning scheme
  25940. let versioning = this.Versioning.None;
  25941. this.targetObject = targetObject;
  25942. if ( targetObject.needsUpdate !== undefined ) { // material
  25943. versioning = this.Versioning.NeedsUpdate;
  25944. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  25945. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  25946. }
  25947. // determine how the property gets bound
  25948. let bindingType = this.BindingType.Direct;
  25949. if ( propertyIndex !== undefined ) {
  25950. // access a sub element of the property array (only primitives are supported right now)
  25951. if ( propertyName === 'morphTargetInfluences' ) {
  25952. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  25953. // support resolving morphTarget names into indices.
  25954. if ( ! targetObject.geometry ) {
  25955. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  25956. return;
  25957. }
  25958. if ( targetObject.geometry.isBufferGeometry ) {
  25959. if ( ! targetObject.geometry.morphAttributes ) {
  25960. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  25961. return;
  25962. }
  25963. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  25964. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  25965. }
  25966. } else {
  25967. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this );
  25968. return;
  25969. }
  25970. }
  25971. bindingType = this.BindingType.ArrayElement;
  25972. this.resolvedProperty = nodeProperty;
  25973. this.propertyIndex = propertyIndex;
  25974. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  25975. // must use copy for Object3D.Euler/Quaternion
  25976. bindingType = this.BindingType.HasFromToArray;
  25977. this.resolvedProperty = nodeProperty;
  25978. } else if ( Array.isArray( nodeProperty ) ) {
  25979. bindingType = this.BindingType.EntireArray;
  25980. this.resolvedProperty = nodeProperty;
  25981. } else {
  25982. this.propertyName = propertyName;
  25983. }
  25984. // select getter / setter
  25985. this.getValue = this.GetterByBindingType[ bindingType ];
  25986. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  25987. }
  25988. unbind() {
  25989. this.node = null;
  25990. // back to the prototype version of getValue / setValue
  25991. // note: avoiding to mutate the shape of 'this' via 'delete'
  25992. this.getValue = this._getValue_unbound;
  25993. this.setValue = this._setValue_unbound;
  25994. }
  25995. }
  25996. PropertyBinding.Composite = Composite;
  25997. PropertyBinding.prototype.BindingType = {
  25998. Direct: 0,
  25999. EntireArray: 1,
  26000. ArrayElement: 2,
  26001. HasFromToArray: 3
  26002. };
  26003. PropertyBinding.prototype.Versioning = {
  26004. None: 0,
  26005. NeedsUpdate: 1,
  26006. MatrixWorldNeedsUpdate: 2
  26007. };
  26008. PropertyBinding.prototype.GetterByBindingType = [
  26009. PropertyBinding.prototype._getValue_direct,
  26010. PropertyBinding.prototype._getValue_array,
  26011. PropertyBinding.prototype._getValue_arrayElement,
  26012. PropertyBinding.prototype._getValue_toArray,
  26013. ];
  26014. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  26015. [
  26016. // Direct
  26017. PropertyBinding.prototype._setValue_direct,
  26018. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  26019. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  26020. ], [
  26021. // EntireArray
  26022. PropertyBinding.prototype._setValue_array,
  26023. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  26024. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  26025. ], [
  26026. // ArrayElement
  26027. PropertyBinding.prototype._setValue_arrayElement,
  26028. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  26029. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  26030. ], [
  26031. // HasToFromArray
  26032. PropertyBinding.prototype._setValue_fromArray,
  26033. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  26034. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  26035. ]
  26036. ];
  26037. /**
  26038. *
  26039. * A group of objects that receives a shared animation state.
  26040. *
  26041. * Usage:
  26042. *
  26043. * - Add objects you would otherwise pass as 'root' to the
  26044. * constructor or the .clipAction method of AnimationMixer.
  26045. *
  26046. * - Instead pass this object as 'root'.
  26047. *
  26048. * - You can also add and remove objects later when the mixer
  26049. * is running.
  26050. *
  26051. * Note:
  26052. *
  26053. * Objects of this class appear as one object to the mixer,
  26054. * so cache control of the individual objects must be done
  26055. * on the group.
  26056. *
  26057. * Limitation:
  26058. *
  26059. * - The animated properties must be compatible among the
  26060. * all objects in the group.
  26061. *
  26062. * - A single property can either be controlled through a
  26063. * target group or directly, but not both.
  26064. */
  26065. class AnimationObjectGroup {
  26066. constructor() {
  26067. this.uuid = generateUUID();
  26068. // cached objects followed by the active ones
  26069. this._objects = Array.prototype.slice.call( arguments );
  26070. this.nCachedObjects_ = 0; // threshold
  26071. // note: read by PropertyBinding.Composite
  26072. const indices = {};
  26073. this._indicesByUUID = indices; // for bookkeeping
  26074. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26075. indices[ arguments[ i ].uuid ] = i;
  26076. }
  26077. this._paths = []; // inside: string
  26078. this._parsedPaths = []; // inside: { we don't care, here }
  26079. this._bindings = []; // inside: Array< PropertyBinding >
  26080. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  26081. const scope = this;
  26082. this.stats = {
  26083. objects: {
  26084. get total() {
  26085. return scope._objects.length;
  26086. },
  26087. get inUse() {
  26088. return this.total - scope.nCachedObjects_;
  26089. }
  26090. },
  26091. get bindingsPerObject() {
  26092. return scope._bindings.length;
  26093. }
  26094. };
  26095. }
  26096. add() {
  26097. const objects = this._objects,
  26098. indicesByUUID = this._indicesByUUID,
  26099. paths = this._paths,
  26100. parsedPaths = this._parsedPaths,
  26101. bindings = this._bindings,
  26102. nBindings = bindings.length;
  26103. let knownObject = undefined,
  26104. nObjects = objects.length,
  26105. nCachedObjects = this.nCachedObjects_;
  26106. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26107. const object = arguments[ i ],
  26108. uuid = object.uuid;
  26109. let index = indicesByUUID[ uuid ];
  26110. if ( index === undefined ) {
  26111. // unknown object -> add it to the ACTIVE region
  26112. index = nObjects ++;
  26113. indicesByUUID[ uuid ] = index;
  26114. objects.push( object );
  26115. // accounting is done, now do the same for all bindings
  26116. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26117. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  26118. }
  26119. } else if ( index < nCachedObjects ) {
  26120. knownObject = objects[ index ];
  26121. // move existing object to the ACTIVE region
  26122. const firstActiveIndex = -- nCachedObjects,
  26123. lastCachedObject = objects[ firstActiveIndex ];
  26124. indicesByUUID[ lastCachedObject.uuid ] = index;
  26125. objects[ index ] = lastCachedObject;
  26126. indicesByUUID[ uuid ] = firstActiveIndex;
  26127. objects[ firstActiveIndex ] = object;
  26128. // accounting is done, now do the same for all bindings
  26129. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26130. const bindingsForPath = bindings[ j ],
  26131. lastCached = bindingsForPath[ firstActiveIndex ];
  26132. let binding = bindingsForPath[ index ];
  26133. bindingsForPath[ index ] = lastCached;
  26134. if ( binding === undefined ) {
  26135. // since we do not bother to create new bindings
  26136. // for objects that are cached, the binding may
  26137. // or may not exist
  26138. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  26139. }
  26140. bindingsForPath[ firstActiveIndex ] = binding;
  26141. }
  26142. } else if ( objects[ index ] !== knownObject ) {
  26143. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  26144. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  26145. } // else the object is already where we want it to be
  26146. } // for arguments
  26147. this.nCachedObjects_ = nCachedObjects;
  26148. }
  26149. remove() {
  26150. const objects = this._objects,
  26151. indicesByUUID = this._indicesByUUID,
  26152. bindings = this._bindings,
  26153. nBindings = bindings.length;
  26154. let nCachedObjects = this.nCachedObjects_;
  26155. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26156. const object = arguments[ i ],
  26157. uuid = object.uuid,
  26158. index = indicesByUUID[ uuid ];
  26159. if ( index !== undefined && index >= nCachedObjects ) {
  26160. // move existing object into the CACHED region
  26161. const lastCachedIndex = nCachedObjects ++,
  26162. firstActiveObject = objects[ lastCachedIndex ];
  26163. indicesByUUID[ firstActiveObject.uuid ] = index;
  26164. objects[ index ] = firstActiveObject;
  26165. indicesByUUID[ uuid ] = lastCachedIndex;
  26166. objects[ lastCachedIndex ] = object;
  26167. // accounting is done, now do the same for all bindings
  26168. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26169. const bindingsForPath = bindings[ j ],
  26170. firstActive = bindingsForPath[ lastCachedIndex ],
  26171. binding = bindingsForPath[ index ];
  26172. bindingsForPath[ index ] = firstActive;
  26173. bindingsForPath[ lastCachedIndex ] = binding;
  26174. }
  26175. }
  26176. } // for arguments
  26177. this.nCachedObjects_ = nCachedObjects;
  26178. }
  26179. // remove & forget
  26180. uncache() {
  26181. const objects = this._objects,
  26182. indicesByUUID = this._indicesByUUID,
  26183. bindings = this._bindings,
  26184. nBindings = bindings.length;
  26185. let nCachedObjects = this.nCachedObjects_,
  26186. nObjects = objects.length;
  26187. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26188. const object = arguments[ i ],
  26189. uuid = object.uuid,
  26190. index = indicesByUUID[ uuid ];
  26191. if ( index !== undefined ) {
  26192. delete indicesByUUID[ uuid ];
  26193. if ( index < nCachedObjects ) {
  26194. // object is cached, shrink the CACHED region
  26195. const firstActiveIndex = -- nCachedObjects,
  26196. lastCachedObject = objects[ firstActiveIndex ],
  26197. lastIndex = -- nObjects,
  26198. lastObject = objects[ lastIndex ];
  26199. // last cached object takes this object's place
  26200. indicesByUUID[ lastCachedObject.uuid ] = index;
  26201. objects[ index ] = lastCachedObject;
  26202. // last object goes to the activated slot and pop
  26203. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  26204. objects[ firstActiveIndex ] = lastObject;
  26205. objects.pop();
  26206. // accounting is done, now do the same for all bindings
  26207. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26208. const bindingsForPath = bindings[ j ],
  26209. lastCached = bindingsForPath[ firstActiveIndex ],
  26210. last = bindingsForPath[ lastIndex ];
  26211. bindingsForPath[ index ] = lastCached;
  26212. bindingsForPath[ firstActiveIndex ] = last;
  26213. bindingsForPath.pop();
  26214. }
  26215. } else {
  26216. // object is active, just swap with the last and pop
  26217. const lastIndex = -- nObjects,
  26218. lastObject = objects[ lastIndex ];
  26219. if ( lastIndex > 0 ) {
  26220. indicesByUUID[ lastObject.uuid ] = index;
  26221. }
  26222. objects[ index ] = lastObject;
  26223. objects.pop();
  26224. // accounting is done, now do the same for all bindings
  26225. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26226. const bindingsForPath = bindings[ j ];
  26227. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  26228. bindingsForPath.pop();
  26229. }
  26230. } // cached or active
  26231. } // if object is known
  26232. } // for arguments
  26233. this.nCachedObjects_ = nCachedObjects;
  26234. }
  26235. // Internal interface used by befriended PropertyBinding.Composite:
  26236. subscribe_( path, parsedPath ) {
  26237. // returns an array of bindings for the given path that is changed
  26238. // according to the contained objects in the group
  26239. const indicesByPath = this._bindingsIndicesByPath;
  26240. let index = indicesByPath[ path ];
  26241. const bindings = this._bindings;
  26242. if ( index !== undefined ) return bindings[ index ];
  26243. const paths = this._paths,
  26244. parsedPaths = this._parsedPaths,
  26245. objects = this._objects,
  26246. nObjects = objects.length,
  26247. nCachedObjects = this.nCachedObjects_,
  26248. bindingsForPath = new Array( nObjects );
  26249. index = bindings.length;
  26250. indicesByPath[ path ] = index;
  26251. paths.push( path );
  26252. parsedPaths.push( parsedPath );
  26253. bindings.push( bindingsForPath );
  26254. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  26255. const object = objects[ i ];
  26256. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  26257. }
  26258. return bindingsForPath;
  26259. }
  26260. unsubscribe_( path ) {
  26261. // tells the group to forget about a property path and no longer
  26262. // update the array previously obtained with 'subscribe_'
  26263. const indicesByPath = this._bindingsIndicesByPath,
  26264. index = indicesByPath[ path ];
  26265. if ( index !== undefined ) {
  26266. const paths = this._paths,
  26267. parsedPaths = this._parsedPaths,
  26268. bindings = this._bindings,
  26269. lastBindingsIndex = bindings.length - 1,
  26270. lastBindings = bindings[ lastBindingsIndex ],
  26271. lastBindingsPath = path[ lastBindingsIndex ];
  26272. indicesByPath[ lastBindingsPath ] = index;
  26273. bindings[ index ] = lastBindings;
  26274. bindings.pop();
  26275. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  26276. parsedPaths.pop();
  26277. paths[ index ] = paths[ lastBindingsIndex ];
  26278. paths.pop();
  26279. }
  26280. }
  26281. }
  26282. AnimationObjectGroup.prototype.isAnimationObjectGroup = true;
  26283. class AnimationAction {
  26284. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  26285. this._mixer = mixer;
  26286. this._clip = clip;
  26287. this._localRoot = localRoot;
  26288. this.blendMode = blendMode;
  26289. const tracks = clip.tracks,
  26290. nTracks = tracks.length,
  26291. interpolants = new Array( nTracks );
  26292. const interpolantSettings = {
  26293. endingStart: ZeroCurvatureEnding,
  26294. endingEnd: ZeroCurvatureEnding
  26295. };
  26296. for ( let i = 0; i !== nTracks; ++ i ) {
  26297. const interpolant = tracks[ i ].createInterpolant( null );
  26298. interpolants[ i ] = interpolant;
  26299. interpolant.settings = interpolantSettings;
  26300. }
  26301. this._interpolantSettings = interpolantSettings;
  26302. this._interpolants = interpolants; // bound by the mixer
  26303. // inside: PropertyMixer (managed by the mixer)
  26304. this._propertyBindings = new Array( nTracks );
  26305. this._cacheIndex = null; // for the memory manager
  26306. this._byClipCacheIndex = null; // for the memory manager
  26307. this._timeScaleInterpolant = null;
  26308. this._weightInterpolant = null;
  26309. this.loop = LoopRepeat;
  26310. this._loopCount = - 1;
  26311. // global mixer time when the action is to be started
  26312. // it's set back to 'null' upon start of the action
  26313. this._startTime = null;
  26314. // scaled local time of the action
  26315. // gets clamped or wrapped to 0..clip.duration according to loop
  26316. this.time = 0;
  26317. this.timeScale = 1;
  26318. this._effectiveTimeScale = 1;
  26319. this.weight = 1;
  26320. this._effectiveWeight = 1;
  26321. this.repetitions = Infinity; // no. of repetitions when looping
  26322. this.paused = false; // true -> zero effective time scale
  26323. this.enabled = true; // false -> zero effective weight
  26324. this.clampWhenFinished = false;// keep feeding the last frame?
  26325. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  26326. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  26327. }
  26328. // State & Scheduling
  26329. play() {
  26330. this._mixer._activateAction( this );
  26331. return this;
  26332. }
  26333. stop() {
  26334. this._mixer._deactivateAction( this );
  26335. return this.reset();
  26336. }
  26337. reset() {
  26338. this.paused = false;
  26339. this.enabled = true;
  26340. this.time = 0; // restart clip
  26341. this._loopCount = - 1;// forget previous loops
  26342. this._startTime = null;// forget scheduling
  26343. return this.stopFading().stopWarping();
  26344. }
  26345. isRunning() {
  26346. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  26347. this._startTime === null && this._mixer._isActiveAction( this );
  26348. }
  26349. // return true when play has been called
  26350. isScheduled() {
  26351. return this._mixer._isActiveAction( this );
  26352. }
  26353. startAt( time ) {
  26354. this._startTime = time;
  26355. return this;
  26356. }
  26357. setLoop( mode, repetitions ) {
  26358. this.loop = mode;
  26359. this.repetitions = repetitions;
  26360. return this;
  26361. }
  26362. // Weight
  26363. // set the weight stopping any scheduled fading
  26364. // although .enabled = false yields an effective weight of zero, this
  26365. // method does *not* change .enabled, because it would be confusing
  26366. setEffectiveWeight( weight ) {
  26367. this.weight = weight;
  26368. // note: same logic as when updated at runtime
  26369. this._effectiveWeight = this.enabled ? weight : 0;
  26370. return this.stopFading();
  26371. }
  26372. // return the weight considering fading and .enabled
  26373. getEffectiveWeight() {
  26374. return this._effectiveWeight;
  26375. }
  26376. fadeIn( duration ) {
  26377. return this._scheduleFading( duration, 0, 1 );
  26378. }
  26379. fadeOut( duration ) {
  26380. return this._scheduleFading( duration, 1, 0 );
  26381. }
  26382. crossFadeFrom( fadeOutAction, duration, warp ) {
  26383. fadeOutAction.fadeOut( duration );
  26384. this.fadeIn( duration );
  26385. if ( warp ) {
  26386. const fadeInDuration = this._clip.duration,
  26387. fadeOutDuration = fadeOutAction._clip.duration,
  26388. startEndRatio = fadeOutDuration / fadeInDuration,
  26389. endStartRatio = fadeInDuration / fadeOutDuration;
  26390. fadeOutAction.warp( 1.0, startEndRatio, duration );
  26391. this.warp( endStartRatio, 1.0, duration );
  26392. }
  26393. return this;
  26394. }
  26395. crossFadeTo( fadeInAction, duration, warp ) {
  26396. return fadeInAction.crossFadeFrom( this, duration, warp );
  26397. }
  26398. stopFading() {
  26399. const weightInterpolant = this._weightInterpolant;
  26400. if ( weightInterpolant !== null ) {
  26401. this._weightInterpolant = null;
  26402. this._mixer._takeBackControlInterpolant( weightInterpolant );
  26403. }
  26404. return this;
  26405. }
  26406. // Time Scale Control
  26407. // set the time scale stopping any scheduled warping
  26408. // although .paused = true yields an effective time scale of zero, this
  26409. // method does *not* change .paused, because it would be confusing
  26410. setEffectiveTimeScale( timeScale ) {
  26411. this.timeScale = timeScale;
  26412. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  26413. return this.stopWarping();
  26414. }
  26415. // return the time scale considering warping and .paused
  26416. getEffectiveTimeScale() {
  26417. return this._effectiveTimeScale;
  26418. }
  26419. setDuration( duration ) {
  26420. this.timeScale = this._clip.duration / duration;
  26421. return this.stopWarping();
  26422. }
  26423. syncWith( action ) {
  26424. this.time = action.time;
  26425. this.timeScale = action.timeScale;
  26426. return this.stopWarping();
  26427. }
  26428. halt( duration ) {
  26429. return this.warp( this._effectiveTimeScale, 0, duration );
  26430. }
  26431. warp( startTimeScale, endTimeScale, duration ) {
  26432. const mixer = this._mixer,
  26433. now = mixer.time,
  26434. timeScale = this.timeScale;
  26435. let interpolant = this._timeScaleInterpolant;
  26436. if ( interpolant === null ) {
  26437. interpolant = mixer._lendControlInterpolant();
  26438. this._timeScaleInterpolant = interpolant;
  26439. }
  26440. const times = interpolant.parameterPositions,
  26441. values = interpolant.sampleValues;
  26442. times[ 0 ] = now;
  26443. times[ 1 ] = now + duration;
  26444. values[ 0 ] = startTimeScale / timeScale;
  26445. values[ 1 ] = endTimeScale / timeScale;
  26446. return this;
  26447. }
  26448. stopWarping() {
  26449. const timeScaleInterpolant = this._timeScaleInterpolant;
  26450. if ( timeScaleInterpolant !== null ) {
  26451. this._timeScaleInterpolant = null;
  26452. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  26453. }
  26454. return this;
  26455. }
  26456. // Object Accessors
  26457. getMixer() {
  26458. return this._mixer;
  26459. }
  26460. getClip() {
  26461. return this._clip;
  26462. }
  26463. getRoot() {
  26464. return this._localRoot || this._mixer._root;
  26465. }
  26466. // Interna
  26467. _update( time, deltaTime, timeDirection, accuIndex ) {
  26468. // called by the mixer
  26469. if ( ! this.enabled ) {
  26470. // call ._updateWeight() to update ._effectiveWeight
  26471. this._updateWeight( time );
  26472. return;
  26473. }
  26474. const startTime = this._startTime;
  26475. if ( startTime !== null ) {
  26476. // check for scheduled start of action
  26477. const timeRunning = ( time - startTime ) * timeDirection;
  26478. if ( timeRunning < 0 || timeDirection === 0 ) {
  26479. return; // yet to come / don't decide when delta = 0
  26480. }
  26481. // start
  26482. this._startTime = null; // unschedule
  26483. deltaTime = timeDirection * timeRunning;
  26484. }
  26485. // apply time scale and advance time
  26486. deltaTime *= this._updateTimeScale( time );
  26487. const clipTime = this._updateTime( deltaTime );
  26488. // note: _updateTime may disable the action resulting in
  26489. // an effective weight of 0
  26490. const weight = this._updateWeight( time );
  26491. if ( weight > 0 ) {
  26492. const interpolants = this._interpolants;
  26493. const propertyMixers = this._propertyBindings;
  26494. switch ( this.blendMode ) {
  26495. case AdditiveAnimationBlendMode:
  26496. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  26497. interpolants[ j ].evaluate( clipTime );
  26498. propertyMixers[ j ].accumulateAdditive( weight );
  26499. }
  26500. break;
  26501. case NormalAnimationBlendMode:
  26502. default:
  26503. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  26504. interpolants[ j ].evaluate( clipTime );
  26505. propertyMixers[ j ].accumulate( accuIndex, weight );
  26506. }
  26507. }
  26508. }
  26509. }
  26510. _updateWeight( time ) {
  26511. let weight = 0;
  26512. if ( this.enabled ) {
  26513. weight = this.weight;
  26514. const interpolant = this._weightInterpolant;
  26515. if ( interpolant !== null ) {
  26516. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  26517. weight *= interpolantValue;
  26518. if ( time > interpolant.parameterPositions[ 1 ] ) {
  26519. this.stopFading();
  26520. if ( interpolantValue === 0 ) {
  26521. // faded out, disable
  26522. this.enabled = false;
  26523. }
  26524. }
  26525. }
  26526. }
  26527. this._effectiveWeight = weight;
  26528. return weight;
  26529. }
  26530. _updateTimeScale( time ) {
  26531. let timeScale = 0;
  26532. if ( ! this.paused ) {
  26533. timeScale = this.timeScale;
  26534. const interpolant = this._timeScaleInterpolant;
  26535. if ( interpolant !== null ) {
  26536. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  26537. timeScale *= interpolantValue;
  26538. if ( time > interpolant.parameterPositions[ 1 ] ) {
  26539. this.stopWarping();
  26540. if ( timeScale === 0 ) {
  26541. // motion has halted, pause
  26542. this.paused = true;
  26543. } else {
  26544. // warp done - apply final time scale
  26545. this.timeScale = timeScale;
  26546. }
  26547. }
  26548. }
  26549. }
  26550. this._effectiveTimeScale = timeScale;
  26551. return timeScale;
  26552. }
  26553. _updateTime( deltaTime ) {
  26554. const duration = this._clip.duration;
  26555. const loop = this.loop;
  26556. let time = this.time + deltaTime;
  26557. let loopCount = this._loopCount;
  26558. const pingPong = ( loop === LoopPingPong );
  26559. if ( deltaTime === 0 ) {
  26560. if ( loopCount === - 1 ) return time;
  26561. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  26562. }
  26563. if ( loop === LoopOnce ) {
  26564. if ( loopCount === - 1 ) {
  26565. // just started
  26566. this._loopCount = 0;
  26567. this._setEndings( true, true, false );
  26568. }
  26569. handle_stop: {
  26570. if ( time >= duration ) {
  26571. time = duration;
  26572. } else if ( time < 0 ) {
  26573. time = 0;
  26574. } else {
  26575. this.time = time;
  26576. break handle_stop;
  26577. }
  26578. if ( this.clampWhenFinished ) this.paused = true;
  26579. else this.enabled = false;
  26580. this.time = time;
  26581. this._mixer.dispatchEvent( {
  26582. type: 'finished', action: this,
  26583. direction: deltaTime < 0 ? - 1 : 1
  26584. } );
  26585. }
  26586. } else { // repetitive Repeat or PingPong
  26587. if ( loopCount === - 1 ) {
  26588. // just started
  26589. if ( deltaTime >= 0 ) {
  26590. loopCount = 0;
  26591. this._setEndings( true, this.repetitions === 0, pingPong );
  26592. } else {
  26593. // when looping in reverse direction, the initial
  26594. // transition through zero counts as a repetition,
  26595. // so leave loopCount at -1
  26596. this._setEndings( this.repetitions === 0, true, pingPong );
  26597. }
  26598. }
  26599. if ( time >= duration || time < 0 ) {
  26600. // wrap around
  26601. const loopDelta = Math.floor( time / duration ); // signed
  26602. time -= duration * loopDelta;
  26603. loopCount += Math.abs( loopDelta );
  26604. const pending = this.repetitions - loopCount;
  26605. if ( pending <= 0 ) {
  26606. // have to stop (switch state, clamp time, fire event)
  26607. if ( this.clampWhenFinished ) this.paused = true;
  26608. else this.enabled = false;
  26609. time = deltaTime > 0 ? duration : 0;
  26610. this.time = time;
  26611. this._mixer.dispatchEvent( {
  26612. type: 'finished', action: this,
  26613. direction: deltaTime > 0 ? 1 : - 1
  26614. } );
  26615. } else {
  26616. // keep running
  26617. if ( pending === 1 ) {
  26618. // entering the last round
  26619. const atStart = deltaTime < 0;
  26620. this._setEndings( atStart, ! atStart, pingPong );
  26621. } else {
  26622. this._setEndings( false, false, pingPong );
  26623. }
  26624. this._loopCount = loopCount;
  26625. this.time = time;
  26626. this._mixer.dispatchEvent( {
  26627. type: 'loop', action: this, loopDelta: loopDelta
  26628. } );
  26629. }
  26630. } else {
  26631. this.time = time;
  26632. }
  26633. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  26634. // invert time for the "pong round"
  26635. return duration - time;
  26636. }
  26637. }
  26638. return time;
  26639. }
  26640. _setEndings( atStart, atEnd, pingPong ) {
  26641. const settings = this._interpolantSettings;
  26642. if ( pingPong ) {
  26643. settings.endingStart = ZeroSlopeEnding;
  26644. settings.endingEnd = ZeroSlopeEnding;
  26645. } else {
  26646. // assuming for LoopOnce atStart == atEnd == true
  26647. if ( atStart ) {
  26648. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26649. } else {
  26650. settings.endingStart = WrapAroundEnding;
  26651. }
  26652. if ( atEnd ) {
  26653. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26654. } else {
  26655. settings.endingEnd = WrapAroundEnding;
  26656. }
  26657. }
  26658. }
  26659. _scheduleFading( duration, weightNow, weightThen ) {
  26660. const mixer = this._mixer, now = mixer.time;
  26661. let interpolant = this._weightInterpolant;
  26662. if ( interpolant === null ) {
  26663. interpolant = mixer._lendControlInterpolant();
  26664. this._weightInterpolant = interpolant;
  26665. }
  26666. const times = interpolant.parameterPositions,
  26667. values = interpolant.sampleValues;
  26668. times[ 0 ] = now;
  26669. values[ 0 ] = weightNow;
  26670. times[ 1 ] = now + duration;
  26671. values[ 1 ] = weightThen;
  26672. return this;
  26673. }
  26674. }
  26675. class AnimationMixer extends EventDispatcher {
  26676. constructor( root ) {
  26677. super();
  26678. this._root = root;
  26679. this._initMemoryManager();
  26680. this._accuIndex = 0;
  26681. this.time = 0;
  26682. this.timeScale = 1.0;
  26683. }
  26684. _bindAction( action, prototypeAction ) {
  26685. const root = action._localRoot || this._root,
  26686. tracks = action._clip.tracks,
  26687. nTracks = tracks.length,
  26688. bindings = action._propertyBindings,
  26689. interpolants = action._interpolants,
  26690. rootUuid = root.uuid,
  26691. bindingsByRoot = this._bindingsByRootAndName;
  26692. let bindingsByName = bindingsByRoot[ rootUuid ];
  26693. if ( bindingsByName === undefined ) {
  26694. bindingsByName = {};
  26695. bindingsByRoot[ rootUuid ] = bindingsByName;
  26696. }
  26697. for ( let i = 0; i !== nTracks; ++ i ) {
  26698. const track = tracks[ i ],
  26699. trackName = track.name;
  26700. let binding = bindingsByName[ trackName ];
  26701. if ( binding !== undefined ) {
  26702. bindings[ i ] = binding;
  26703. } else {
  26704. binding = bindings[ i ];
  26705. if ( binding !== undefined ) {
  26706. // existing binding, make sure the cache knows
  26707. if ( binding._cacheIndex === null ) {
  26708. ++ binding.referenceCount;
  26709. this._addInactiveBinding( binding, rootUuid, trackName );
  26710. }
  26711. continue;
  26712. }
  26713. const path = prototypeAction && prototypeAction.
  26714. _propertyBindings[ i ].binding.parsedPath;
  26715. binding = new PropertyMixer(
  26716. PropertyBinding.create( root, trackName, path ),
  26717. track.ValueTypeName, track.getValueSize() );
  26718. ++ binding.referenceCount;
  26719. this._addInactiveBinding( binding, rootUuid, trackName );
  26720. bindings[ i ] = binding;
  26721. }
  26722. interpolants[ i ].resultBuffer = binding.buffer;
  26723. }
  26724. }
  26725. _activateAction( action ) {
  26726. if ( ! this._isActiveAction( action ) ) {
  26727. if ( action._cacheIndex === null ) {
  26728. // this action has been forgotten by the cache, but the user
  26729. // appears to be still using it -> rebind
  26730. const rootUuid = ( action._localRoot || this._root ).uuid,
  26731. clipUuid = action._clip.uuid,
  26732. actionsForClip = this._actionsByClip[ clipUuid ];
  26733. this._bindAction( action,
  26734. actionsForClip && actionsForClip.knownActions[ 0 ] );
  26735. this._addInactiveAction( action, clipUuid, rootUuid );
  26736. }
  26737. const bindings = action._propertyBindings;
  26738. // increment reference counts / sort out state
  26739. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  26740. const binding = bindings[ i ];
  26741. if ( binding.useCount ++ === 0 ) {
  26742. this._lendBinding( binding );
  26743. binding.saveOriginalState();
  26744. }
  26745. }
  26746. this._lendAction( action );
  26747. }
  26748. }
  26749. _deactivateAction( action ) {
  26750. if ( this._isActiveAction( action ) ) {
  26751. const bindings = action._propertyBindings;
  26752. // decrement reference counts / sort out state
  26753. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  26754. const binding = bindings[ i ];
  26755. if ( -- binding.useCount === 0 ) {
  26756. binding.restoreOriginalState();
  26757. this._takeBackBinding( binding );
  26758. }
  26759. }
  26760. this._takeBackAction( action );
  26761. }
  26762. }
  26763. // Memory manager
  26764. _initMemoryManager() {
  26765. this._actions = []; // 'nActiveActions' followed by inactive ones
  26766. this._nActiveActions = 0;
  26767. this._actionsByClip = {};
  26768. // inside:
  26769. // {
  26770. // knownActions: Array< AnimationAction > - used as prototypes
  26771. // actionByRoot: AnimationAction - lookup
  26772. // }
  26773. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  26774. this._nActiveBindings = 0;
  26775. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  26776. this._controlInterpolants = []; // same game as above
  26777. this._nActiveControlInterpolants = 0;
  26778. const scope = this;
  26779. this.stats = {
  26780. actions: {
  26781. get total() {
  26782. return scope._actions.length;
  26783. },
  26784. get inUse() {
  26785. return scope._nActiveActions;
  26786. }
  26787. },
  26788. bindings: {
  26789. get total() {
  26790. return scope._bindings.length;
  26791. },
  26792. get inUse() {
  26793. return scope._nActiveBindings;
  26794. }
  26795. },
  26796. controlInterpolants: {
  26797. get total() {
  26798. return scope._controlInterpolants.length;
  26799. },
  26800. get inUse() {
  26801. return scope._nActiveControlInterpolants;
  26802. }
  26803. }
  26804. };
  26805. }
  26806. // Memory management for AnimationAction objects
  26807. _isActiveAction( action ) {
  26808. const index = action._cacheIndex;
  26809. return index !== null && index < this._nActiveActions;
  26810. }
  26811. _addInactiveAction( action, clipUuid, rootUuid ) {
  26812. const actions = this._actions,
  26813. actionsByClip = this._actionsByClip;
  26814. let actionsForClip = actionsByClip[ clipUuid ];
  26815. if ( actionsForClip === undefined ) {
  26816. actionsForClip = {
  26817. knownActions: [ action ],
  26818. actionByRoot: {}
  26819. };
  26820. action._byClipCacheIndex = 0;
  26821. actionsByClip[ clipUuid ] = actionsForClip;
  26822. } else {
  26823. const knownActions = actionsForClip.knownActions;
  26824. action._byClipCacheIndex = knownActions.length;
  26825. knownActions.push( action );
  26826. }
  26827. action._cacheIndex = actions.length;
  26828. actions.push( action );
  26829. actionsForClip.actionByRoot[ rootUuid ] = action;
  26830. }
  26831. _removeInactiveAction( action ) {
  26832. const actions = this._actions,
  26833. lastInactiveAction = actions[ actions.length - 1 ],
  26834. cacheIndex = action._cacheIndex;
  26835. lastInactiveAction._cacheIndex = cacheIndex;
  26836. actions[ cacheIndex ] = lastInactiveAction;
  26837. actions.pop();
  26838. action._cacheIndex = null;
  26839. const clipUuid = action._clip.uuid,
  26840. actionsByClip = this._actionsByClip,
  26841. actionsForClip = actionsByClip[ clipUuid ],
  26842. knownActionsForClip = actionsForClip.knownActions,
  26843. lastKnownAction =
  26844. knownActionsForClip[ knownActionsForClip.length - 1 ],
  26845. byClipCacheIndex = action._byClipCacheIndex;
  26846. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  26847. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  26848. knownActionsForClip.pop();
  26849. action._byClipCacheIndex = null;
  26850. const actionByRoot = actionsForClip.actionByRoot,
  26851. rootUuid = ( action._localRoot || this._root ).uuid;
  26852. delete actionByRoot[ rootUuid ];
  26853. if ( knownActionsForClip.length === 0 ) {
  26854. delete actionsByClip[ clipUuid ];
  26855. }
  26856. this._removeInactiveBindingsForAction( action );
  26857. }
  26858. _removeInactiveBindingsForAction( action ) {
  26859. const bindings = action._propertyBindings;
  26860. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  26861. const binding = bindings[ i ];
  26862. if ( -- binding.referenceCount === 0 ) {
  26863. this._removeInactiveBinding( binding );
  26864. }
  26865. }
  26866. }
  26867. _lendAction( action ) {
  26868. // [ active actions | inactive actions ]
  26869. // [ active actions >| inactive actions ]
  26870. // s a
  26871. // <-swap->
  26872. // a s
  26873. const actions = this._actions,
  26874. prevIndex = action._cacheIndex,
  26875. lastActiveIndex = this._nActiveActions ++,
  26876. firstInactiveAction = actions[ lastActiveIndex ];
  26877. action._cacheIndex = lastActiveIndex;
  26878. actions[ lastActiveIndex ] = action;
  26879. firstInactiveAction._cacheIndex = prevIndex;
  26880. actions[ prevIndex ] = firstInactiveAction;
  26881. }
  26882. _takeBackAction( action ) {
  26883. // [ active actions | inactive actions ]
  26884. // [ active actions |< inactive actions ]
  26885. // a s
  26886. // <-swap->
  26887. // s a
  26888. const actions = this._actions,
  26889. prevIndex = action._cacheIndex,
  26890. firstInactiveIndex = -- this._nActiveActions,
  26891. lastActiveAction = actions[ firstInactiveIndex ];
  26892. action._cacheIndex = firstInactiveIndex;
  26893. actions[ firstInactiveIndex ] = action;
  26894. lastActiveAction._cacheIndex = prevIndex;
  26895. actions[ prevIndex ] = lastActiveAction;
  26896. }
  26897. // Memory management for PropertyMixer objects
  26898. _addInactiveBinding( binding, rootUuid, trackName ) {
  26899. const bindingsByRoot = this._bindingsByRootAndName,
  26900. bindings = this._bindings;
  26901. let bindingByName = bindingsByRoot[ rootUuid ];
  26902. if ( bindingByName === undefined ) {
  26903. bindingByName = {};
  26904. bindingsByRoot[ rootUuid ] = bindingByName;
  26905. }
  26906. bindingByName[ trackName ] = binding;
  26907. binding._cacheIndex = bindings.length;
  26908. bindings.push( binding );
  26909. }
  26910. _removeInactiveBinding( binding ) {
  26911. const bindings = this._bindings,
  26912. propBinding = binding.binding,
  26913. rootUuid = propBinding.rootNode.uuid,
  26914. trackName = propBinding.path,
  26915. bindingsByRoot = this._bindingsByRootAndName,
  26916. bindingByName = bindingsByRoot[ rootUuid ],
  26917. lastInactiveBinding = bindings[ bindings.length - 1 ],
  26918. cacheIndex = binding._cacheIndex;
  26919. lastInactiveBinding._cacheIndex = cacheIndex;
  26920. bindings[ cacheIndex ] = lastInactiveBinding;
  26921. bindings.pop();
  26922. delete bindingByName[ trackName ];
  26923. if ( Object.keys( bindingByName ).length === 0 ) {
  26924. delete bindingsByRoot[ rootUuid ];
  26925. }
  26926. }
  26927. _lendBinding( binding ) {
  26928. const bindings = this._bindings,
  26929. prevIndex = binding._cacheIndex,
  26930. lastActiveIndex = this._nActiveBindings ++,
  26931. firstInactiveBinding = bindings[ lastActiveIndex ];
  26932. binding._cacheIndex = lastActiveIndex;
  26933. bindings[ lastActiveIndex ] = binding;
  26934. firstInactiveBinding._cacheIndex = prevIndex;
  26935. bindings[ prevIndex ] = firstInactiveBinding;
  26936. }
  26937. _takeBackBinding( binding ) {
  26938. const bindings = this._bindings,
  26939. prevIndex = binding._cacheIndex,
  26940. firstInactiveIndex = -- this._nActiveBindings,
  26941. lastActiveBinding = bindings[ firstInactiveIndex ];
  26942. binding._cacheIndex = firstInactiveIndex;
  26943. bindings[ firstInactiveIndex ] = binding;
  26944. lastActiveBinding._cacheIndex = prevIndex;
  26945. bindings[ prevIndex ] = lastActiveBinding;
  26946. }
  26947. // Memory management of Interpolants for weight and time scale
  26948. _lendControlInterpolant() {
  26949. const interpolants = this._controlInterpolants,
  26950. lastActiveIndex = this._nActiveControlInterpolants ++;
  26951. let interpolant = interpolants[ lastActiveIndex ];
  26952. if ( interpolant === undefined ) {
  26953. interpolant = new LinearInterpolant(
  26954. new Float32Array( 2 ), new Float32Array( 2 ),
  26955. 1, this._controlInterpolantsResultBuffer );
  26956. interpolant.__cacheIndex = lastActiveIndex;
  26957. interpolants[ lastActiveIndex ] = interpolant;
  26958. }
  26959. return interpolant;
  26960. }
  26961. _takeBackControlInterpolant( interpolant ) {
  26962. const interpolants = this._controlInterpolants,
  26963. prevIndex = interpolant.__cacheIndex,
  26964. firstInactiveIndex = -- this._nActiveControlInterpolants,
  26965. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  26966. interpolant.__cacheIndex = firstInactiveIndex;
  26967. interpolants[ firstInactiveIndex ] = interpolant;
  26968. lastActiveInterpolant.__cacheIndex = prevIndex;
  26969. interpolants[ prevIndex ] = lastActiveInterpolant;
  26970. }
  26971. // return an action for a clip optionally using a custom root target
  26972. // object (this method allocates a lot of dynamic memory in case a
  26973. // previously unknown clip/root combination is specified)
  26974. clipAction( clip, optionalRoot, blendMode ) {
  26975. const root = optionalRoot || this._root,
  26976. rootUuid = root.uuid;
  26977. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  26978. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  26979. const actionsForClip = this._actionsByClip[ clipUuid ];
  26980. let prototypeAction = null;
  26981. if ( blendMode === undefined ) {
  26982. if ( clipObject !== null ) {
  26983. blendMode = clipObject.blendMode;
  26984. } else {
  26985. blendMode = NormalAnimationBlendMode;
  26986. }
  26987. }
  26988. if ( actionsForClip !== undefined ) {
  26989. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  26990. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  26991. return existingAction;
  26992. }
  26993. // we know the clip, so we don't have to parse all
  26994. // the bindings again but can just copy
  26995. prototypeAction = actionsForClip.knownActions[ 0 ];
  26996. // also, take the clip from the prototype action
  26997. if ( clipObject === null )
  26998. clipObject = prototypeAction._clip;
  26999. }
  27000. // clip must be known when specified via string
  27001. if ( clipObject === null ) return null;
  27002. // allocate all resources required to run it
  27003. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  27004. this._bindAction( newAction, prototypeAction );
  27005. // and make the action known to the memory manager
  27006. this._addInactiveAction( newAction, clipUuid, rootUuid );
  27007. return newAction;
  27008. }
  27009. // get an existing action
  27010. existingAction( clip, optionalRoot ) {
  27011. const root = optionalRoot || this._root,
  27012. rootUuid = root.uuid,
  27013. clipObject = typeof clip === 'string' ?
  27014. AnimationClip.findByName( root, clip ) : clip,
  27015. clipUuid = clipObject ? clipObject.uuid : clip,
  27016. actionsForClip = this._actionsByClip[ clipUuid ];
  27017. if ( actionsForClip !== undefined ) {
  27018. return actionsForClip.actionByRoot[ rootUuid ] || null;
  27019. }
  27020. return null;
  27021. }
  27022. // deactivates all previously scheduled actions
  27023. stopAllAction() {
  27024. const actions = this._actions,
  27025. nActions = this._nActiveActions;
  27026. for ( let i = nActions - 1; i >= 0; -- i ) {
  27027. actions[ i ].stop();
  27028. }
  27029. return this;
  27030. }
  27031. // advance the time and update apply the animation
  27032. update( deltaTime ) {
  27033. deltaTime *= this.timeScale;
  27034. const actions = this._actions,
  27035. nActions = this._nActiveActions,
  27036. time = this.time += deltaTime,
  27037. timeDirection = Math.sign( deltaTime ),
  27038. accuIndex = this._accuIndex ^= 1;
  27039. // run active actions
  27040. for ( let i = 0; i !== nActions; ++ i ) {
  27041. const action = actions[ i ];
  27042. action._update( time, deltaTime, timeDirection, accuIndex );
  27043. }
  27044. // update scene graph
  27045. const bindings = this._bindings,
  27046. nBindings = this._nActiveBindings;
  27047. for ( let i = 0; i !== nBindings; ++ i ) {
  27048. bindings[ i ].apply( accuIndex );
  27049. }
  27050. return this;
  27051. }
  27052. // Allows you to seek to a specific time in an animation.
  27053. setTime( timeInSeconds ) {
  27054. this.time = 0; // Zero out time attribute for AnimationMixer object;
  27055. for ( let i = 0; i < this._actions.length; i ++ ) {
  27056. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  27057. }
  27058. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  27059. }
  27060. // return this mixer's root target object
  27061. getRoot() {
  27062. return this._root;
  27063. }
  27064. // free all resources specific to a particular clip
  27065. uncacheClip( clip ) {
  27066. const actions = this._actions,
  27067. clipUuid = clip.uuid,
  27068. actionsByClip = this._actionsByClip,
  27069. actionsForClip = actionsByClip[ clipUuid ];
  27070. if ( actionsForClip !== undefined ) {
  27071. // note: just calling _removeInactiveAction would mess up the
  27072. // iteration state and also require updating the state we can
  27073. // just throw away
  27074. const actionsToRemove = actionsForClip.knownActions;
  27075. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  27076. const action = actionsToRemove[ i ];
  27077. this._deactivateAction( action );
  27078. const cacheIndex = action._cacheIndex,
  27079. lastInactiveAction = actions[ actions.length - 1 ];
  27080. action._cacheIndex = null;
  27081. action._byClipCacheIndex = null;
  27082. lastInactiveAction._cacheIndex = cacheIndex;
  27083. actions[ cacheIndex ] = lastInactiveAction;
  27084. actions.pop();
  27085. this._removeInactiveBindingsForAction( action );
  27086. }
  27087. delete actionsByClip[ clipUuid ];
  27088. }
  27089. }
  27090. // free all resources specific to a particular root target object
  27091. uncacheRoot( root ) {
  27092. const rootUuid = root.uuid,
  27093. actionsByClip = this._actionsByClip;
  27094. for ( const clipUuid in actionsByClip ) {
  27095. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  27096. action = actionByRoot[ rootUuid ];
  27097. if ( action !== undefined ) {
  27098. this._deactivateAction( action );
  27099. this._removeInactiveAction( action );
  27100. }
  27101. }
  27102. const bindingsByRoot = this._bindingsByRootAndName,
  27103. bindingByName = bindingsByRoot[ rootUuid ];
  27104. if ( bindingByName !== undefined ) {
  27105. for ( const trackName in bindingByName ) {
  27106. const binding = bindingByName[ trackName ];
  27107. binding.restoreOriginalState();
  27108. this._removeInactiveBinding( binding );
  27109. }
  27110. }
  27111. }
  27112. // remove a targeted clip from the cache
  27113. uncacheAction( clip, optionalRoot ) {
  27114. const action = this.existingAction( clip, optionalRoot );
  27115. if ( action !== null ) {
  27116. this._deactivateAction( action );
  27117. this._removeInactiveAction( action );
  27118. }
  27119. }
  27120. }
  27121. AnimationMixer.prototype._controlInterpolantsResultBuffer = new Float32Array( 1 );
  27122. class Uniform {
  27123. constructor( value ) {
  27124. if ( typeof value === 'string' ) {
  27125. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  27126. value = arguments[ 1 ];
  27127. }
  27128. this.value = value;
  27129. }
  27130. clone() {
  27131. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  27132. }
  27133. }
  27134. class InstancedInterleavedBuffer extends InterleavedBuffer {
  27135. constructor( array, stride, meshPerAttribute = 1 ) {
  27136. super( array, stride );
  27137. this.meshPerAttribute = meshPerAttribute;
  27138. }
  27139. copy( source ) {
  27140. super.copy( source );
  27141. this.meshPerAttribute = source.meshPerAttribute;
  27142. return this;
  27143. }
  27144. clone( data ) {
  27145. const ib = super.clone( data );
  27146. ib.meshPerAttribute = this.meshPerAttribute;
  27147. return ib;
  27148. }
  27149. toJSON( data ) {
  27150. const json = super.toJSON( data );
  27151. json.isInstancedInterleavedBuffer = true;
  27152. json.meshPerAttribute = this.meshPerAttribute;
  27153. return json;
  27154. }
  27155. }
  27156. InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true;
  27157. class GLBufferAttribute {
  27158. constructor( buffer, type, itemSize, elementSize, count ) {
  27159. this.buffer = buffer;
  27160. this.type = type;
  27161. this.itemSize = itemSize;
  27162. this.elementSize = elementSize;
  27163. this.count = count;
  27164. this.version = 0;
  27165. }
  27166. set needsUpdate( value ) {
  27167. if ( value === true ) this.version ++;
  27168. }
  27169. setBuffer( buffer ) {
  27170. this.buffer = buffer;
  27171. return this;
  27172. }
  27173. setType( type, elementSize ) {
  27174. this.type = type;
  27175. this.elementSize = elementSize;
  27176. return this;
  27177. }
  27178. setItemSize( itemSize ) {
  27179. this.itemSize = itemSize;
  27180. return this;
  27181. }
  27182. setCount( count ) {
  27183. this.count = count;
  27184. return this;
  27185. }
  27186. }
  27187. GLBufferAttribute.prototype.isGLBufferAttribute = true;
  27188. class Raycaster {
  27189. constructor( origin, direction, near = 0, far = Infinity ) {
  27190. this.ray = new Ray( origin, direction );
  27191. // direction is assumed to be normalized (for accurate distance calculations)
  27192. this.near = near;
  27193. this.far = far;
  27194. this.camera = null;
  27195. this.layers = new Layers();
  27196. this.params = {
  27197. Mesh: {},
  27198. Line: { threshold: 1 },
  27199. LOD: {},
  27200. Points: { threshold: 1 },
  27201. Sprite: {}
  27202. };
  27203. }
  27204. set( origin, direction ) {
  27205. // direction is assumed to be normalized (for accurate distance calculations)
  27206. this.ray.set( origin, direction );
  27207. }
  27208. setFromCamera( coords, camera ) {
  27209. if ( camera && camera.isPerspectiveCamera ) {
  27210. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  27211. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  27212. this.camera = camera;
  27213. } else if ( camera && camera.isOrthographicCamera ) {
  27214. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  27215. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  27216. this.camera = camera;
  27217. } else {
  27218. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  27219. }
  27220. }
  27221. intersectObject( object, recursive = true, intersects = [] ) {
  27222. intersectObject( object, this, intersects, recursive );
  27223. intersects.sort( ascSort );
  27224. return intersects;
  27225. }
  27226. intersectObjects( objects, recursive = true, intersects = [] ) {
  27227. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  27228. intersectObject( objects[ i ], this, intersects, recursive );
  27229. }
  27230. intersects.sort( ascSort );
  27231. return intersects;
  27232. }
  27233. }
  27234. function ascSort( a, b ) {
  27235. return a.distance - b.distance;
  27236. }
  27237. function intersectObject( object, raycaster, intersects, recursive ) {
  27238. if ( object.layers.test( raycaster.layers ) ) {
  27239. object.raycast( raycaster, intersects );
  27240. }
  27241. if ( recursive === true ) {
  27242. const children = object.children;
  27243. for ( let i = 0, l = children.length; i < l; i ++ ) {
  27244. intersectObject( children[ i ], raycaster, intersects, true );
  27245. }
  27246. }
  27247. }
  27248. /**
  27249. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  27250. *
  27251. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  27252. * The azimuthal angle (theta) is measured from the positive z-axis.
  27253. */
  27254. class Spherical {
  27255. constructor( radius = 1, phi = 0, theta = 0 ) {
  27256. this.radius = radius;
  27257. this.phi = phi; // polar angle
  27258. this.theta = theta; // azimuthal angle
  27259. return this;
  27260. }
  27261. set( radius, phi, theta ) {
  27262. this.radius = radius;
  27263. this.phi = phi;
  27264. this.theta = theta;
  27265. return this;
  27266. }
  27267. copy( other ) {
  27268. this.radius = other.radius;
  27269. this.phi = other.phi;
  27270. this.theta = other.theta;
  27271. return this;
  27272. }
  27273. // restrict phi to be betwee EPS and PI-EPS
  27274. makeSafe() {
  27275. const EPS = 0.000001;
  27276. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  27277. return this;
  27278. }
  27279. setFromVector3( v ) {
  27280. return this.setFromCartesianCoords( v.x, v.y, v.z );
  27281. }
  27282. setFromCartesianCoords( x, y, z ) {
  27283. this.radius = Math.sqrt( x * x + y * y + z * z );
  27284. if ( this.radius === 0 ) {
  27285. this.theta = 0;
  27286. this.phi = 0;
  27287. } else {
  27288. this.theta = Math.atan2( x, z );
  27289. this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) );
  27290. }
  27291. return this;
  27292. }
  27293. clone() {
  27294. return new this.constructor().copy( this );
  27295. }
  27296. }
  27297. /**
  27298. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  27299. */
  27300. class Cylindrical {
  27301. constructor( radius = 1, theta = 0, y = 0 ) {
  27302. this.radius = radius; // distance from the origin to a point in the x-z plane
  27303. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  27304. this.y = y; // height above the x-z plane
  27305. return this;
  27306. }
  27307. set( radius, theta, y ) {
  27308. this.radius = radius;
  27309. this.theta = theta;
  27310. this.y = y;
  27311. return this;
  27312. }
  27313. copy( other ) {
  27314. this.radius = other.radius;
  27315. this.theta = other.theta;
  27316. this.y = other.y;
  27317. return this;
  27318. }
  27319. setFromVector3( v ) {
  27320. return this.setFromCartesianCoords( v.x, v.y, v.z );
  27321. }
  27322. setFromCartesianCoords( x, y, z ) {
  27323. this.radius = Math.sqrt( x * x + z * z );
  27324. this.theta = Math.atan2( x, z );
  27325. this.y = y;
  27326. return this;
  27327. }
  27328. clone() {
  27329. return new this.constructor().copy( this );
  27330. }
  27331. }
  27332. const _vector$4 = /*@__PURE__*/ new Vector2();
  27333. class Box2 {
  27334. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  27335. this.min = min;
  27336. this.max = max;
  27337. }
  27338. set( min, max ) {
  27339. this.min.copy( min );
  27340. this.max.copy( max );
  27341. return this;
  27342. }
  27343. setFromPoints( points ) {
  27344. this.makeEmpty();
  27345. for ( let i = 0, il = points.length; i < il; i ++ ) {
  27346. this.expandByPoint( points[ i ] );
  27347. }
  27348. return this;
  27349. }
  27350. setFromCenterAndSize( center, size ) {
  27351. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  27352. this.min.copy( center ).sub( halfSize );
  27353. this.max.copy( center ).add( halfSize );
  27354. return this;
  27355. }
  27356. clone() {
  27357. return new this.constructor().copy( this );
  27358. }
  27359. copy( box ) {
  27360. this.min.copy( box.min );
  27361. this.max.copy( box.max );
  27362. return this;
  27363. }
  27364. makeEmpty() {
  27365. this.min.x = this.min.y = + Infinity;
  27366. this.max.x = this.max.y = - Infinity;
  27367. return this;
  27368. }
  27369. isEmpty() {
  27370. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  27371. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  27372. }
  27373. getCenter( target ) {
  27374. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  27375. }
  27376. getSize( target ) {
  27377. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  27378. }
  27379. expandByPoint( point ) {
  27380. this.min.min( point );
  27381. this.max.max( point );
  27382. return this;
  27383. }
  27384. expandByVector( vector ) {
  27385. this.min.sub( vector );
  27386. this.max.add( vector );
  27387. return this;
  27388. }
  27389. expandByScalar( scalar ) {
  27390. this.min.addScalar( - scalar );
  27391. this.max.addScalar( scalar );
  27392. return this;
  27393. }
  27394. containsPoint( point ) {
  27395. return point.x < this.min.x || point.x > this.max.x ||
  27396. point.y < this.min.y || point.y > this.max.y ? false : true;
  27397. }
  27398. containsBox( box ) {
  27399. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  27400. this.min.y <= box.min.y && box.max.y <= this.max.y;
  27401. }
  27402. getParameter( point, target ) {
  27403. // This can potentially have a divide by zero if the box
  27404. // has a size dimension of 0.
  27405. return target.set(
  27406. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  27407. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  27408. );
  27409. }
  27410. intersectsBox( box ) {
  27411. // using 4 splitting planes to rule out intersections
  27412. return box.max.x < this.min.x || box.min.x > this.max.x ||
  27413. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  27414. }
  27415. clampPoint( point, target ) {
  27416. return target.copy( point ).clamp( this.min, this.max );
  27417. }
  27418. distanceToPoint( point ) {
  27419. const clampedPoint = _vector$4.copy( point ).clamp( this.min, this.max );
  27420. return clampedPoint.sub( point ).length();
  27421. }
  27422. intersect( box ) {
  27423. this.min.max( box.min );
  27424. this.max.min( box.max );
  27425. return this;
  27426. }
  27427. union( box ) {
  27428. this.min.min( box.min );
  27429. this.max.max( box.max );
  27430. return this;
  27431. }
  27432. translate( offset ) {
  27433. this.min.add( offset );
  27434. this.max.add( offset );
  27435. return this;
  27436. }
  27437. equals( box ) {
  27438. return box.min.equals( this.min ) && box.max.equals( this.max );
  27439. }
  27440. }
  27441. Box2.prototype.isBox2 = true;
  27442. const _startP = /*@__PURE__*/ new Vector3();
  27443. const _startEnd = /*@__PURE__*/ new Vector3();
  27444. class Line3 {
  27445. constructor( start = new Vector3(), end = new Vector3() ) {
  27446. this.start = start;
  27447. this.end = end;
  27448. }
  27449. set( start, end ) {
  27450. this.start.copy( start );
  27451. this.end.copy( end );
  27452. return this;
  27453. }
  27454. copy( line ) {
  27455. this.start.copy( line.start );
  27456. this.end.copy( line.end );
  27457. return this;
  27458. }
  27459. getCenter( target ) {
  27460. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  27461. }
  27462. delta( target ) {
  27463. return target.subVectors( this.end, this.start );
  27464. }
  27465. distanceSq() {
  27466. return this.start.distanceToSquared( this.end );
  27467. }
  27468. distance() {
  27469. return this.start.distanceTo( this.end );
  27470. }
  27471. at( t, target ) {
  27472. return this.delta( target ).multiplyScalar( t ).add( this.start );
  27473. }
  27474. closestPointToPointParameter( point, clampToLine ) {
  27475. _startP.subVectors( point, this.start );
  27476. _startEnd.subVectors( this.end, this.start );
  27477. const startEnd2 = _startEnd.dot( _startEnd );
  27478. const startEnd_startP = _startEnd.dot( _startP );
  27479. let t = startEnd_startP / startEnd2;
  27480. if ( clampToLine ) {
  27481. t = clamp( t, 0, 1 );
  27482. }
  27483. return t;
  27484. }
  27485. closestPointToPoint( point, clampToLine, target ) {
  27486. const t = this.closestPointToPointParameter( point, clampToLine );
  27487. return this.delta( target ).multiplyScalar( t ).add( this.start );
  27488. }
  27489. applyMatrix4( matrix ) {
  27490. this.start.applyMatrix4( matrix );
  27491. this.end.applyMatrix4( matrix );
  27492. return this;
  27493. }
  27494. equals( line ) {
  27495. return line.start.equals( this.start ) && line.end.equals( this.end );
  27496. }
  27497. clone() {
  27498. return new this.constructor().copy( this );
  27499. }
  27500. }
  27501. const _vector$3 = /*@__PURE__*/ new Vector3();
  27502. class SpotLightHelper extends Object3D {
  27503. constructor( light, color ) {
  27504. super();
  27505. this.light = light;
  27506. this.light.updateMatrixWorld();
  27507. this.matrix = light.matrixWorld;
  27508. this.matrixAutoUpdate = false;
  27509. this.color = color;
  27510. const geometry = new BufferGeometry();
  27511. const positions = [
  27512. 0, 0, 0, 0, 0, 1,
  27513. 0, 0, 0, 1, 0, 1,
  27514. 0, 0, 0, - 1, 0, 1,
  27515. 0, 0, 0, 0, 1, 1,
  27516. 0, 0, 0, 0, - 1, 1
  27517. ];
  27518. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  27519. const p1 = ( i / l ) * Math.PI * 2;
  27520. const p2 = ( j / l ) * Math.PI * 2;
  27521. positions.push(
  27522. Math.cos( p1 ), Math.sin( p1 ), 1,
  27523. Math.cos( p2 ), Math.sin( p2 ), 1
  27524. );
  27525. }
  27526. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  27527. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  27528. this.cone = new LineSegments( geometry, material );
  27529. this.add( this.cone );
  27530. this.update();
  27531. }
  27532. dispose() {
  27533. this.cone.geometry.dispose();
  27534. this.cone.material.dispose();
  27535. }
  27536. update() {
  27537. this.light.updateMatrixWorld();
  27538. const coneLength = this.light.distance ? this.light.distance : 1000;
  27539. const coneWidth = coneLength * Math.tan( this.light.angle );
  27540. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  27541. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  27542. this.cone.lookAt( _vector$3 );
  27543. if ( this.color !== undefined ) {
  27544. this.cone.material.color.set( this.color );
  27545. } else {
  27546. this.cone.material.color.copy( this.light.color );
  27547. }
  27548. }
  27549. }
  27550. const _vector$2 = /*@__PURE__*/ new Vector3();
  27551. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  27552. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  27553. class SkeletonHelper extends LineSegments {
  27554. constructor( object ) {
  27555. const bones = getBoneList( object );
  27556. const geometry = new BufferGeometry();
  27557. const vertices = [];
  27558. const colors = [];
  27559. const color1 = new Color( 0, 0, 1 );
  27560. const color2 = new Color( 0, 1, 0 );
  27561. for ( let i = 0; i < bones.length; i ++ ) {
  27562. const bone = bones[ i ];
  27563. if ( bone.parent && bone.parent.isBone ) {
  27564. vertices.push( 0, 0, 0 );
  27565. vertices.push( 0, 0, 0 );
  27566. colors.push( color1.r, color1.g, color1.b );
  27567. colors.push( color2.r, color2.g, color2.b );
  27568. }
  27569. }
  27570. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27571. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  27572. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  27573. super( geometry, material );
  27574. this.type = 'SkeletonHelper';
  27575. this.isSkeletonHelper = true;
  27576. this.root = object;
  27577. this.bones = bones;
  27578. this.matrix = object.matrixWorld;
  27579. this.matrixAutoUpdate = false;
  27580. }
  27581. updateMatrixWorld( force ) {
  27582. const bones = this.bones;
  27583. const geometry = this.geometry;
  27584. const position = geometry.getAttribute( 'position' );
  27585. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  27586. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  27587. const bone = bones[ i ];
  27588. if ( bone.parent && bone.parent.isBone ) {
  27589. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  27590. _vector$2.setFromMatrixPosition( _boneMatrix );
  27591. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  27592. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  27593. _vector$2.setFromMatrixPosition( _boneMatrix );
  27594. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  27595. j += 2;
  27596. }
  27597. }
  27598. geometry.getAttribute( 'position' ).needsUpdate = true;
  27599. super.updateMatrixWorld( force );
  27600. }
  27601. }
  27602. function getBoneList( object ) {
  27603. const boneList = [];
  27604. if ( object && object.isBone ) {
  27605. boneList.push( object );
  27606. }
  27607. for ( let i = 0; i < object.children.length; i ++ ) {
  27608. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  27609. }
  27610. return boneList;
  27611. }
  27612. class PointLightHelper extends Mesh {
  27613. constructor( light, sphereSize, color ) {
  27614. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  27615. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  27616. super( geometry, material );
  27617. this.light = light;
  27618. this.light.updateMatrixWorld();
  27619. this.color = color;
  27620. this.type = 'PointLightHelper';
  27621. this.matrix = this.light.matrixWorld;
  27622. this.matrixAutoUpdate = false;
  27623. this.update();
  27624. /*
  27625. // TODO: delete this comment?
  27626. const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  27627. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  27628. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  27629. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  27630. const d = light.distance;
  27631. if ( d === 0.0 ) {
  27632. this.lightDistance.visible = false;
  27633. } else {
  27634. this.lightDistance.scale.set( d, d, d );
  27635. }
  27636. this.add( this.lightDistance );
  27637. */
  27638. }
  27639. dispose() {
  27640. this.geometry.dispose();
  27641. this.material.dispose();
  27642. }
  27643. update() {
  27644. if ( this.color !== undefined ) {
  27645. this.material.color.set( this.color );
  27646. } else {
  27647. this.material.color.copy( this.light.color );
  27648. }
  27649. /*
  27650. const d = this.light.distance;
  27651. if ( d === 0.0 ) {
  27652. this.lightDistance.visible = false;
  27653. } else {
  27654. this.lightDistance.visible = true;
  27655. this.lightDistance.scale.set( d, d, d );
  27656. }
  27657. */
  27658. }
  27659. }
  27660. const _vector$1 = /*@__PURE__*/ new Vector3();
  27661. const _color1 = /*@__PURE__*/ new Color();
  27662. const _color2 = /*@__PURE__*/ new Color();
  27663. class HemisphereLightHelper extends Object3D {
  27664. constructor( light, size, color ) {
  27665. super();
  27666. this.light = light;
  27667. this.light.updateMatrixWorld();
  27668. this.matrix = light.matrixWorld;
  27669. this.matrixAutoUpdate = false;
  27670. this.color = color;
  27671. const geometry = new OctahedronGeometry( size );
  27672. geometry.rotateY( Math.PI * 0.5 );
  27673. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  27674. if ( this.color === undefined ) this.material.vertexColors = true;
  27675. const position = geometry.getAttribute( 'position' );
  27676. const colors = new Float32Array( position.count * 3 );
  27677. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  27678. this.add( new Mesh( geometry, this.material ) );
  27679. this.update();
  27680. }
  27681. dispose() {
  27682. this.children[ 0 ].geometry.dispose();
  27683. this.children[ 0 ].material.dispose();
  27684. }
  27685. update() {
  27686. const mesh = this.children[ 0 ];
  27687. if ( this.color !== undefined ) {
  27688. this.material.color.set( this.color );
  27689. } else {
  27690. const colors = mesh.geometry.getAttribute( 'color' );
  27691. _color1.copy( this.light.color );
  27692. _color2.copy( this.light.groundColor );
  27693. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  27694. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  27695. colors.setXYZ( i, color.r, color.g, color.b );
  27696. }
  27697. colors.needsUpdate = true;
  27698. }
  27699. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  27700. }
  27701. }
  27702. class GridHelper extends LineSegments {
  27703. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  27704. color1 = new Color( color1 );
  27705. color2 = new Color( color2 );
  27706. const center = divisions / 2;
  27707. const step = size / divisions;
  27708. const halfSize = size / 2;
  27709. const vertices = [], colors = [];
  27710. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  27711. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  27712. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  27713. const color = i === center ? color1 : color2;
  27714. color.toArray( colors, j ); j += 3;
  27715. color.toArray( colors, j ); j += 3;
  27716. color.toArray( colors, j ); j += 3;
  27717. color.toArray( colors, j ); j += 3;
  27718. }
  27719. const geometry = new BufferGeometry();
  27720. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27721. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  27722. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  27723. super( geometry, material );
  27724. this.type = 'GridHelper';
  27725. }
  27726. }
  27727. class PolarGridHelper extends LineSegments {
  27728. constructor( radius = 10, radials = 16, circles = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  27729. color1 = new Color( color1 );
  27730. color2 = new Color( color2 );
  27731. const vertices = [];
  27732. const colors = [];
  27733. // create the radials
  27734. for ( let i = 0; i <= radials; i ++ ) {
  27735. const v = ( i / radials ) * ( Math.PI * 2 );
  27736. const x = Math.sin( v ) * radius;
  27737. const z = Math.cos( v ) * radius;
  27738. vertices.push( 0, 0, 0 );
  27739. vertices.push( x, 0, z );
  27740. const color = ( i & 1 ) ? color1 : color2;
  27741. colors.push( color.r, color.g, color.b );
  27742. colors.push( color.r, color.g, color.b );
  27743. }
  27744. // create the circles
  27745. for ( let i = 0; i <= circles; i ++ ) {
  27746. const color = ( i & 1 ) ? color1 : color2;
  27747. const r = radius - ( radius / circles * i );
  27748. for ( let j = 0; j < divisions; j ++ ) {
  27749. // first vertex
  27750. let v = ( j / divisions ) * ( Math.PI * 2 );
  27751. let x = Math.sin( v ) * r;
  27752. let z = Math.cos( v ) * r;
  27753. vertices.push( x, 0, z );
  27754. colors.push( color.r, color.g, color.b );
  27755. // second vertex
  27756. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  27757. x = Math.sin( v ) * r;
  27758. z = Math.cos( v ) * r;
  27759. vertices.push( x, 0, z );
  27760. colors.push( color.r, color.g, color.b );
  27761. }
  27762. }
  27763. const geometry = new BufferGeometry();
  27764. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27765. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  27766. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  27767. super( geometry, material );
  27768. this.type = 'PolarGridHelper';
  27769. }
  27770. }
  27771. const _v1 = /*@__PURE__*/ new Vector3();
  27772. const _v2 = /*@__PURE__*/ new Vector3();
  27773. const _v3 = /*@__PURE__*/ new Vector3();
  27774. class DirectionalLightHelper extends Object3D {
  27775. constructor( light, size, color ) {
  27776. super();
  27777. this.light = light;
  27778. this.light.updateMatrixWorld();
  27779. this.matrix = light.matrixWorld;
  27780. this.matrixAutoUpdate = false;
  27781. this.color = color;
  27782. if ( size === undefined ) size = 1;
  27783. let geometry = new BufferGeometry();
  27784. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  27785. - size, size, 0,
  27786. size, size, 0,
  27787. size, - size, 0,
  27788. - size, - size, 0,
  27789. - size, size, 0
  27790. ], 3 ) );
  27791. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  27792. this.lightPlane = new Line( geometry, material );
  27793. this.add( this.lightPlane );
  27794. geometry = new BufferGeometry();
  27795. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  27796. this.targetLine = new Line( geometry, material );
  27797. this.add( this.targetLine );
  27798. this.update();
  27799. }
  27800. dispose() {
  27801. this.lightPlane.geometry.dispose();
  27802. this.lightPlane.material.dispose();
  27803. this.targetLine.geometry.dispose();
  27804. this.targetLine.material.dispose();
  27805. }
  27806. update() {
  27807. _v1.setFromMatrixPosition( this.light.matrixWorld );
  27808. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  27809. _v3.subVectors( _v2, _v1 );
  27810. this.lightPlane.lookAt( _v2 );
  27811. if ( this.color !== undefined ) {
  27812. this.lightPlane.material.color.set( this.color );
  27813. this.targetLine.material.color.set( this.color );
  27814. } else {
  27815. this.lightPlane.material.color.copy( this.light.color );
  27816. this.targetLine.material.color.copy( this.light.color );
  27817. }
  27818. this.targetLine.lookAt( _v2 );
  27819. this.targetLine.scale.z = _v3.length();
  27820. }
  27821. }
  27822. const _vector = /*@__PURE__*/ new Vector3();
  27823. const _camera = /*@__PURE__*/ new Camera();
  27824. /**
  27825. * - shows frustum, line of sight and up of the camera
  27826. * - suitable for fast updates
  27827. * - based on frustum visualization in lightgl.js shadowmap example
  27828. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  27829. */
  27830. class CameraHelper extends LineSegments {
  27831. constructor( camera ) {
  27832. const geometry = new BufferGeometry();
  27833. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  27834. const vertices = [];
  27835. const colors = [];
  27836. const pointMap = {};
  27837. // colors
  27838. const colorFrustum = new Color( 0xffaa00 );
  27839. const colorCone = new Color( 0xff0000 );
  27840. const colorUp = new Color( 0x00aaff );
  27841. const colorTarget = new Color( 0xffffff );
  27842. const colorCross = new Color( 0x333333 );
  27843. // near
  27844. addLine( 'n1', 'n2', colorFrustum );
  27845. addLine( 'n2', 'n4', colorFrustum );
  27846. addLine( 'n4', 'n3', colorFrustum );
  27847. addLine( 'n3', 'n1', colorFrustum );
  27848. // far
  27849. addLine( 'f1', 'f2', colorFrustum );
  27850. addLine( 'f2', 'f4', colorFrustum );
  27851. addLine( 'f4', 'f3', colorFrustum );
  27852. addLine( 'f3', 'f1', colorFrustum );
  27853. // sides
  27854. addLine( 'n1', 'f1', colorFrustum );
  27855. addLine( 'n2', 'f2', colorFrustum );
  27856. addLine( 'n3', 'f3', colorFrustum );
  27857. addLine( 'n4', 'f4', colorFrustum );
  27858. // cone
  27859. addLine( 'p', 'n1', colorCone );
  27860. addLine( 'p', 'n2', colorCone );
  27861. addLine( 'p', 'n3', colorCone );
  27862. addLine( 'p', 'n4', colorCone );
  27863. // up
  27864. addLine( 'u1', 'u2', colorUp );
  27865. addLine( 'u2', 'u3', colorUp );
  27866. addLine( 'u3', 'u1', colorUp );
  27867. // target
  27868. addLine( 'c', 't', colorTarget );
  27869. addLine( 'p', 'c', colorCross );
  27870. // cross
  27871. addLine( 'cn1', 'cn2', colorCross );
  27872. addLine( 'cn3', 'cn4', colorCross );
  27873. addLine( 'cf1', 'cf2', colorCross );
  27874. addLine( 'cf3', 'cf4', colorCross );
  27875. function addLine( a, b, color ) {
  27876. addPoint( a, color );
  27877. addPoint( b, color );
  27878. }
  27879. function addPoint( id, color ) {
  27880. vertices.push( 0, 0, 0 );
  27881. colors.push( color.r, color.g, color.b );
  27882. if ( pointMap[ id ] === undefined ) {
  27883. pointMap[ id ] = [];
  27884. }
  27885. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  27886. }
  27887. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27888. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  27889. super( geometry, material );
  27890. this.type = 'CameraHelper';
  27891. this.camera = camera;
  27892. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  27893. this.matrix = camera.matrixWorld;
  27894. this.matrixAutoUpdate = false;
  27895. this.pointMap = pointMap;
  27896. this.update();
  27897. }
  27898. update() {
  27899. const geometry = this.geometry;
  27900. const pointMap = this.pointMap;
  27901. const w = 1, h = 1;
  27902. // we need just camera projection matrix inverse
  27903. // world matrix must be identity
  27904. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  27905. // center / target
  27906. setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
  27907. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  27908. // near
  27909. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
  27910. setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
  27911. setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
  27912. setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
  27913. // far
  27914. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  27915. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  27916. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  27917. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  27918. // up
  27919. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
  27920. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
  27921. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
  27922. // cross
  27923. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  27924. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  27925. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  27926. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  27927. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
  27928. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
  27929. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
  27930. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
  27931. geometry.getAttribute( 'position' ).needsUpdate = true;
  27932. }
  27933. dispose() {
  27934. this.geometry.dispose();
  27935. this.material.dispose();
  27936. }
  27937. }
  27938. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  27939. _vector.set( x, y, z ).unproject( camera );
  27940. const points = pointMap[ point ];
  27941. if ( points !== undefined ) {
  27942. const position = geometry.getAttribute( 'position' );
  27943. for ( let i = 0, l = points.length; i < l; i ++ ) {
  27944. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  27945. }
  27946. }
  27947. }
  27948. const _box = /*@__PURE__*/ new Box3();
  27949. class BoxHelper extends LineSegments {
  27950. constructor( object, color = 0xffff00 ) {
  27951. const indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] );
  27952. const positions = new Float32Array( 8 * 3 );
  27953. const geometry = new BufferGeometry();
  27954. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  27955. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  27956. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  27957. this.object = object;
  27958. this.type = 'BoxHelper';
  27959. this.matrixAutoUpdate = false;
  27960. this.update();
  27961. }
  27962. update( object ) {
  27963. if ( object !== undefined ) {
  27964. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  27965. }
  27966. if ( this.object !== undefined ) {
  27967. _box.setFromObject( this.object );
  27968. }
  27969. if ( _box.isEmpty() ) return;
  27970. const min = _box.min;
  27971. const max = _box.max;
  27972. /*
  27973. 5____4
  27974. 1/___0/|
  27975. | 6__|_7
  27976. 2/___3/
  27977. 0: max.x, max.y, max.z
  27978. 1: min.x, max.y, max.z
  27979. 2: min.x, min.y, max.z
  27980. 3: max.x, min.y, max.z
  27981. 4: max.x, max.y, min.z
  27982. 5: min.x, max.y, min.z
  27983. 6: min.x, min.y, min.z
  27984. 7: max.x, min.y, min.z
  27985. */
  27986. const position = this.geometry.attributes.position;
  27987. const array = position.array;
  27988. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  27989. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  27990. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  27991. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  27992. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  27993. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  27994. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  27995. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  27996. position.needsUpdate = true;
  27997. this.geometry.computeBoundingSphere();
  27998. }
  27999. setFromObject( object ) {
  28000. this.object = object;
  28001. this.update();
  28002. return this;
  28003. }
  28004. copy( source ) {
  28005. LineSegments.prototype.copy.call( this, source );
  28006. this.object = source.object;
  28007. return this;
  28008. }
  28009. }
  28010. class Box3Helper extends LineSegments {
  28011. constructor( box, color = 0xffff00 ) {
  28012. const indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] );
  28013. const positions = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, - 1, - 1, 1, - 1, - 1, - 1, - 1, 1, - 1, - 1 ];
  28014. const geometry = new BufferGeometry();
  28015. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  28016. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  28017. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  28018. this.box = box;
  28019. this.type = 'Box3Helper';
  28020. this.geometry.computeBoundingSphere();
  28021. }
  28022. updateMatrixWorld( force ) {
  28023. const box = this.box;
  28024. if ( box.isEmpty() ) return;
  28025. box.getCenter( this.position );
  28026. box.getSize( this.scale );
  28027. this.scale.multiplyScalar( 0.5 );
  28028. super.updateMatrixWorld( force );
  28029. }
  28030. }
  28031. class PlaneHelper extends Line {
  28032. constructor( plane, size = 1, hex = 0xffff00 ) {
  28033. const color = hex;
  28034. const positions = [ 1, - 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0 ];
  28035. const geometry = new BufferGeometry();
  28036. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  28037. geometry.computeBoundingSphere();
  28038. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  28039. this.type = 'PlaneHelper';
  28040. this.plane = plane;
  28041. this.size = size;
  28042. const positions2 = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, - 1, 1, 1, - 1, 1 ];
  28043. const geometry2 = new BufferGeometry();
  28044. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  28045. geometry2.computeBoundingSphere();
  28046. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  28047. }
  28048. updateMatrixWorld( force ) {
  28049. let scale = - this.plane.constant;
  28050. if ( Math.abs( scale ) < 1e-8 ) scale = 1e-8; // sign does not matter
  28051. this.scale.set( 0.5 * this.size, 0.5 * this.size, scale );
  28052. this.children[ 0 ].material.side = ( scale < 0 ) ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  28053. this.lookAt( this.plane.normal );
  28054. super.updateMatrixWorld( force );
  28055. }
  28056. }
  28057. const _axis = /*@__PURE__*/ new Vector3();
  28058. let _lineGeometry, _coneGeometry;
  28059. class ArrowHelper extends Object3D {
  28060. // dir is assumed to be normalized
  28061. constructor( dir = new Vector3( 0, 0, 1 ), origin = new Vector3( 0, 0, 0 ), length = 1, color = 0xffff00, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  28062. super();
  28063. this.type = 'ArrowHelper';
  28064. if ( _lineGeometry === undefined ) {
  28065. _lineGeometry = new BufferGeometry();
  28066. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  28067. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  28068. _coneGeometry.translate( 0, - 0.5, 0 );
  28069. }
  28070. this.position.copy( origin );
  28071. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  28072. this.line.matrixAutoUpdate = false;
  28073. this.add( this.line );
  28074. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  28075. this.cone.matrixAutoUpdate = false;
  28076. this.add( this.cone );
  28077. this.setDirection( dir );
  28078. this.setLength( length, headLength, headWidth );
  28079. }
  28080. setDirection( dir ) {
  28081. // dir is assumed to be normalized
  28082. if ( dir.y > 0.99999 ) {
  28083. this.quaternion.set( 0, 0, 0, 1 );
  28084. } else if ( dir.y < - 0.99999 ) {
  28085. this.quaternion.set( 1, 0, 0, 0 );
  28086. } else {
  28087. _axis.set( dir.z, 0, - dir.x ).normalize();
  28088. const radians = Math.acos( dir.y );
  28089. this.quaternion.setFromAxisAngle( _axis, radians );
  28090. }
  28091. }
  28092. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  28093. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  28094. this.line.updateMatrix();
  28095. this.cone.scale.set( headWidth, headLength, headWidth );
  28096. this.cone.position.y = length;
  28097. this.cone.updateMatrix();
  28098. }
  28099. setColor( color ) {
  28100. this.line.material.color.set( color );
  28101. this.cone.material.color.set( color );
  28102. }
  28103. copy( source ) {
  28104. super.copy( source, false );
  28105. this.line.copy( source.line );
  28106. this.cone.copy( source.cone );
  28107. return this;
  28108. }
  28109. }
  28110. class AxesHelper extends LineSegments {
  28111. constructor( size = 1 ) {
  28112. const vertices = [
  28113. 0, 0, 0, size, 0, 0,
  28114. 0, 0, 0, 0, size, 0,
  28115. 0, 0, 0, 0, 0, size
  28116. ];
  28117. const colors = [
  28118. 1, 0, 0, 1, 0.6, 0,
  28119. 0, 1, 0, 0.6, 1, 0,
  28120. 0, 0, 1, 0, 0.6, 1
  28121. ];
  28122. const geometry = new BufferGeometry();
  28123. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28124. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28125. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28126. super( geometry, material );
  28127. this.type = 'AxesHelper';
  28128. }
  28129. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  28130. const color = new Color();
  28131. const array = this.geometry.attributes.color.array;
  28132. color.set( xAxisColor );
  28133. color.toArray( array, 0 );
  28134. color.toArray( array, 3 );
  28135. color.set( yAxisColor );
  28136. color.toArray( array, 6 );
  28137. color.toArray( array, 9 );
  28138. color.set( zAxisColor );
  28139. color.toArray( array, 12 );
  28140. color.toArray( array, 15 );
  28141. this.geometry.attributes.color.needsUpdate = true;
  28142. return this;
  28143. }
  28144. dispose() {
  28145. this.geometry.dispose();
  28146. this.material.dispose();
  28147. }
  28148. }
  28149. class ShapePath {
  28150. constructor() {
  28151. this.type = 'ShapePath';
  28152. this.color = new Color();
  28153. this.subPaths = [];
  28154. this.currentPath = null;
  28155. }
  28156. moveTo( x, y ) {
  28157. this.currentPath = new Path();
  28158. this.subPaths.push( this.currentPath );
  28159. this.currentPath.moveTo( x, y );
  28160. return this;
  28161. }
  28162. lineTo( x, y ) {
  28163. this.currentPath.lineTo( x, y );
  28164. return this;
  28165. }
  28166. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  28167. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  28168. return this;
  28169. }
  28170. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  28171. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  28172. return this;
  28173. }
  28174. splineThru( pts ) {
  28175. this.currentPath.splineThru( pts );
  28176. return this;
  28177. }
  28178. toShapes( isCCW, noHoles ) {
  28179. function toShapesNoHoles( inSubpaths ) {
  28180. const shapes = [];
  28181. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  28182. const tmpPath = inSubpaths[ i ];
  28183. const tmpShape = new Shape();
  28184. tmpShape.curves = tmpPath.curves;
  28185. shapes.push( tmpShape );
  28186. }
  28187. return shapes;
  28188. }
  28189. function isPointInsidePolygon( inPt, inPolygon ) {
  28190. const polyLen = inPolygon.length;
  28191. // inPt on polygon contour => immediate success or
  28192. // toggling of inside/outside at every single! intersection point of an edge
  28193. // with the horizontal line through inPt, left of inPt
  28194. // not counting lowerY endpoints of edges and whole edges on that line
  28195. let inside = false;
  28196. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  28197. let edgeLowPt = inPolygon[ p ];
  28198. let edgeHighPt = inPolygon[ q ];
  28199. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  28200. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  28201. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  28202. // not parallel
  28203. if ( edgeDy < 0 ) {
  28204. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  28205. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  28206. }
  28207. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  28208. if ( inPt.y === edgeLowPt.y ) {
  28209. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  28210. // continue; // no intersection or edgeLowPt => doesn't count !!!
  28211. } else {
  28212. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  28213. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  28214. if ( perpEdge < 0 ) continue;
  28215. inside = ! inside; // true intersection left of inPt
  28216. }
  28217. } else {
  28218. // parallel or collinear
  28219. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  28220. // edge lies on the same horizontal line as inPt
  28221. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  28222. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  28223. // continue;
  28224. }
  28225. }
  28226. return inside;
  28227. }
  28228. const isClockWise = ShapeUtils.isClockWise;
  28229. const subPaths = this.subPaths;
  28230. if ( subPaths.length === 0 ) return [];
  28231. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  28232. let solid, tmpPath, tmpShape;
  28233. const shapes = [];
  28234. if ( subPaths.length === 1 ) {
  28235. tmpPath = subPaths[ 0 ];
  28236. tmpShape = new Shape();
  28237. tmpShape.curves = tmpPath.curves;
  28238. shapes.push( tmpShape );
  28239. return shapes;
  28240. }
  28241. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  28242. holesFirst = isCCW ? ! holesFirst : holesFirst;
  28243. // console.log("Holes first", holesFirst);
  28244. const betterShapeHoles = [];
  28245. const newShapes = [];
  28246. let newShapeHoles = [];
  28247. let mainIdx = 0;
  28248. let tmpPoints;
  28249. newShapes[ mainIdx ] = undefined;
  28250. newShapeHoles[ mainIdx ] = [];
  28251. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  28252. tmpPath = subPaths[ i ];
  28253. tmpPoints = tmpPath.getPoints();
  28254. solid = isClockWise( tmpPoints );
  28255. solid = isCCW ? ! solid : solid;
  28256. if ( solid ) {
  28257. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  28258. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  28259. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  28260. if ( holesFirst ) mainIdx ++;
  28261. newShapeHoles[ mainIdx ] = [];
  28262. //console.log('cw', i);
  28263. } else {
  28264. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  28265. //console.log('ccw', i);
  28266. }
  28267. }
  28268. // only Holes? -> probably all Shapes with wrong orientation
  28269. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  28270. if ( newShapes.length > 1 ) {
  28271. let ambiguous = false;
  28272. const toChange = [];
  28273. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  28274. betterShapeHoles[ sIdx ] = [];
  28275. }
  28276. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  28277. const sho = newShapeHoles[ sIdx ];
  28278. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  28279. const ho = sho[ hIdx ];
  28280. let hole_unassigned = true;
  28281. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  28282. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  28283. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  28284. if ( hole_unassigned ) {
  28285. hole_unassigned = false;
  28286. betterShapeHoles[ s2Idx ].push( ho );
  28287. } else {
  28288. ambiguous = true;
  28289. }
  28290. }
  28291. }
  28292. if ( hole_unassigned ) {
  28293. betterShapeHoles[ sIdx ].push( ho );
  28294. }
  28295. }
  28296. }
  28297. // console.log("ambiguous: ", ambiguous);
  28298. if ( toChange.length > 0 ) {
  28299. // console.log("to change: ", toChange);
  28300. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  28301. }
  28302. }
  28303. let tmpHoles;
  28304. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  28305. tmpShape = newShapes[ i ].s;
  28306. shapes.push( tmpShape );
  28307. tmpHoles = newShapeHoles[ i ];
  28308. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  28309. tmpShape.holes.push( tmpHoles[ j ].h );
  28310. }
  28311. }
  28312. //console.log("shape", shapes);
  28313. return shapes;
  28314. }
  28315. }
  28316. const _floatView = new Float32Array( 1 );
  28317. const _int32View = new Int32Array( _floatView.buffer );
  28318. class DataUtils {
  28319. // Converts float32 to float16 (stored as uint16 value).
  28320. static toHalfFloat( val ) {
  28321. if ( val > 65504 ) {
  28322. console.warn( 'THREE.DataUtils.toHalfFloat(): value exceeds 65504.' );
  28323. val = 65504; // maximum representable value in float16
  28324. }
  28325. // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
  28326. /* This method is faster than the OpenEXR implementation (very often
  28327. * used, eg. in Ogre), with the additional benefit of rounding, inspired
  28328. * by James Tursa?s half-precision code. */
  28329. _floatView[ 0 ] = val;
  28330. const x = _int32View[ 0 ];
  28331. let bits = ( x >> 16 ) & 0x8000; /* Get the sign */
  28332. let m = ( x >> 12 ) & 0x07ff; /* Keep one extra bit for rounding */
  28333. const e = ( x >> 23 ) & 0xff; /* Using int is faster here */
  28334. /* If zero, or denormal, or exponent underflows too much for a denormal
  28335. * half, return signed zero. */
  28336. if ( e < 103 ) return bits;
  28337. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  28338. if ( e > 142 ) {
  28339. bits |= 0x7c00;
  28340. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  28341. * not Inf, so make sure we set one mantissa bit too. */
  28342. bits |= ( ( e == 255 ) ? 0 : 1 ) && ( x & 0x007fffff );
  28343. return bits;
  28344. }
  28345. /* If exponent underflows but not too much, return a denormal */
  28346. if ( e < 113 ) {
  28347. m |= 0x0800;
  28348. /* Extra rounding may overflow and set mantissa to 0 and exponent
  28349. * to 1, which is OK. */
  28350. bits |= ( m >> ( 114 - e ) ) + ( ( m >> ( 113 - e ) ) & 1 );
  28351. return bits;
  28352. }
  28353. bits |= ( ( e - 112 ) << 10 ) | ( m >> 1 );
  28354. /* Extra rounding. An overflow will set mantissa to 0 and increment
  28355. * the exponent, which is OK. */
  28356. bits += m & 1;
  28357. return bits;
  28358. }
  28359. }
  28360. const LineStrip = 0;
  28361. const LinePieces = 1;
  28362. const NoColors = 0;
  28363. const FaceColors = 1;
  28364. const VertexColors = 2;
  28365. function MeshFaceMaterial( materials ) {
  28366. console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' );
  28367. return materials;
  28368. }
  28369. function MultiMaterial( materials = [] ) {
  28370. console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' );
  28371. materials.isMultiMaterial = true;
  28372. materials.materials = materials;
  28373. materials.clone = function () {
  28374. return materials.slice();
  28375. };
  28376. return materials;
  28377. }
  28378. function PointCloud( geometry, material ) {
  28379. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  28380. return new Points( geometry, material );
  28381. }
  28382. function Particle( material ) {
  28383. console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
  28384. return new Sprite( material );
  28385. }
  28386. function ParticleSystem( geometry, material ) {
  28387. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  28388. return new Points( geometry, material );
  28389. }
  28390. function PointCloudMaterial( parameters ) {
  28391. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  28392. return new PointsMaterial( parameters );
  28393. }
  28394. function ParticleBasicMaterial( parameters ) {
  28395. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  28396. return new PointsMaterial( parameters );
  28397. }
  28398. function ParticleSystemMaterial( parameters ) {
  28399. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  28400. return new PointsMaterial( parameters );
  28401. }
  28402. function Vertex( x, y, z ) {
  28403. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  28404. return new Vector3( x, y, z );
  28405. }
  28406. //
  28407. function DynamicBufferAttribute( array, itemSize ) {
  28408. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.' );
  28409. return new BufferAttribute( array, itemSize ).setUsage( DynamicDrawUsage );
  28410. }
  28411. function Int8Attribute( array, itemSize ) {
  28412. console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
  28413. return new Int8BufferAttribute( array, itemSize );
  28414. }
  28415. function Uint8Attribute( array, itemSize ) {
  28416. console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
  28417. return new Uint8BufferAttribute( array, itemSize );
  28418. }
  28419. function Uint8ClampedAttribute( array, itemSize ) {
  28420. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
  28421. return new Uint8ClampedBufferAttribute( array, itemSize );
  28422. }
  28423. function Int16Attribute( array, itemSize ) {
  28424. console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
  28425. return new Int16BufferAttribute( array, itemSize );
  28426. }
  28427. function Uint16Attribute( array, itemSize ) {
  28428. console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
  28429. return new Uint16BufferAttribute( array, itemSize );
  28430. }
  28431. function Int32Attribute( array, itemSize ) {
  28432. console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
  28433. return new Int32BufferAttribute( array, itemSize );
  28434. }
  28435. function Uint32Attribute( array, itemSize ) {
  28436. console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
  28437. return new Uint32BufferAttribute( array, itemSize );
  28438. }
  28439. function Float32Attribute( array, itemSize ) {
  28440. console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
  28441. return new Float32BufferAttribute( array, itemSize );
  28442. }
  28443. function Float64Attribute( array, itemSize ) {
  28444. console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
  28445. return new Float64BufferAttribute( array, itemSize );
  28446. }
  28447. //
  28448. Curve.create = function ( construct, getPoint ) {
  28449. console.log( 'THREE.Curve.create() has been deprecated' );
  28450. construct.prototype = Object.create( Curve.prototype );
  28451. construct.prototype.constructor = construct;
  28452. construct.prototype.getPoint = getPoint;
  28453. return construct;
  28454. };
  28455. //
  28456. Path.prototype.fromPoints = function ( points ) {
  28457. console.warn( 'THREE.Path: .fromPoints() has been renamed to .setFromPoints().' );
  28458. return this.setFromPoints( points );
  28459. };
  28460. //
  28461. function AxisHelper( size ) {
  28462. console.warn( 'THREE.AxisHelper has been renamed to THREE.AxesHelper.' );
  28463. return new AxesHelper( size );
  28464. }
  28465. function BoundingBoxHelper( object, color ) {
  28466. console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
  28467. return new BoxHelper( object, color );
  28468. }
  28469. function EdgesHelper( object, hex ) {
  28470. console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
  28471. return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  28472. }
  28473. GridHelper.prototype.setColors = function () {
  28474. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  28475. };
  28476. SkeletonHelper.prototype.update = function () {
  28477. console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' );
  28478. };
  28479. function WireframeHelper( object, hex ) {
  28480. console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
  28481. return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  28482. }
  28483. //
  28484. Loader.prototype.extractUrlBase = function ( url ) {
  28485. console.warn( 'THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.' );
  28486. return LoaderUtils.extractUrlBase( url );
  28487. };
  28488. Loader.Handlers = {
  28489. add: function ( /* regex, loader */ ) {
  28490. console.error( 'THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.' );
  28491. },
  28492. get: function ( /* file */ ) {
  28493. console.error( 'THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.' );
  28494. }
  28495. };
  28496. function XHRLoader( manager ) {
  28497. console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
  28498. return new FileLoader( manager );
  28499. }
  28500. function BinaryTextureLoader( manager ) {
  28501. console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' );
  28502. return new DataTextureLoader( manager );
  28503. }
  28504. //
  28505. Box2.prototype.center = function ( optionalTarget ) {
  28506. console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
  28507. return this.getCenter( optionalTarget );
  28508. };
  28509. Box2.prototype.empty = function () {
  28510. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  28511. return this.isEmpty();
  28512. };
  28513. Box2.prototype.isIntersectionBox = function ( box ) {
  28514. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  28515. return this.intersectsBox( box );
  28516. };
  28517. Box2.prototype.size = function ( optionalTarget ) {
  28518. console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
  28519. return this.getSize( optionalTarget );
  28520. };
  28521. //
  28522. Box3.prototype.center = function ( optionalTarget ) {
  28523. console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
  28524. return this.getCenter( optionalTarget );
  28525. };
  28526. Box3.prototype.empty = function () {
  28527. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  28528. return this.isEmpty();
  28529. };
  28530. Box3.prototype.isIntersectionBox = function ( box ) {
  28531. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  28532. return this.intersectsBox( box );
  28533. };
  28534. Box3.prototype.isIntersectionSphere = function ( sphere ) {
  28535. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  28536. return this.intersectsSphere( sphere );
  28537. };
  28538. Box3.prototype.size = function ( optionalTarget ) {
  28539. console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
  28540. return this.getSize( optionalTarget );
  28541. };
  28542. //
  28543. Sphere.prototype.empty = function () {
  28544. console.warn( 'THREE.Sphere: .empty() has been renamed to .isEmpty().' );
  28545. return this.isEmpty();
  28546. };
  28547. //
  28548. Frustum.prototype.setFromMatrix = function ( m ) {
  28549. console.warn( 'THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().' );
  28550. return this.setFromProjectionMatrix( m );
  28551. };
  28552. //
  28553. Line3.prototype.center = function ( optionalTarget ) {
  28554. console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
  28555. return this.getCenter( optionalTarget );
  28556. };
  28557. //
  28558. Matrix3.prototype.flattenToArrayOffset = function ( array, offset ) {
  28559. console.warn( 'THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.' );
  28560. return this.toArray( array, offset );
  28561. };
  28562. Matrix3.prototype.multiplyVector3 = function ( vector ) {
  28563. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  28564. return vector.applyMatrix3( this );
  28565. };
  28566. Matrix3.prototype.multiplyVector3Array = function ( /* a */ ) {
  28567. console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' );
  28568. };
  28569. Matrix3.prototype.applyToBufferAttribute = function ( attribute ) {
  28570. console.warn( 'THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.' );
  28571. return attribute.applyMatrix3( this );
  28572. };
  28573. Matrix3.prototype.applyToVector3Array = function ( /* array, offset, length */ ) {
  28574. console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' );
  28575. };
  28576. Matrix3.prototype.getInverse = function ( matrix ) {
  28577. console.warn( 'THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.' );
  28578. return this.copy( matrix ).invert();
  28579. };
  28580. //
  28581. Matrix4.prototype.extractPosition = function ( m ) {
  28582. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  28583. return this.copyPosition( m );
  28584. };
  28585. Matrix4.prototype.flattenToArrayOffset = function ( array, offset ) {
  28586. console.warn( 'THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.' );
  28587. return this.toArray( array, offset );
  28588. };
  28589. Matrix4.prototype.getPosition = function () {
  28590. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  28591. return new Vector3().setFromMatrixColumn( this, 3 );
  28592. };
  28593. Matrix4.prototype.setRotationFromQuaternion = function ( q ) {
  28594. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  28595. return this.makeRotationFromQuaternion( q );
  28596. };
  28597. Matrix4.prototype.multiplyToArray = function () {
  28598. console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' );
  28599. };
  28600. Matrix4.prototype.multiplyVector3 = function ( vector ) {
  28601. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  28602. return vector.applyMatrix4( this );
  28603. };
  28604. Matrix4.prototype.multiplyVector4 = function ( vector ) {
  28605. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  28606. return vector.applyMatrix4( this );
  28607. };
  28608. Matrix4.prototype.multiplyVector3Array = function ( /* a */ ) {
  28609. console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' );
  28610. };
  28611. Matrix4.prototype.rotateAxis = function ( v ) {
  28612. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  28613. v.transformDirection( this );
  28614. };
  28615. Matrix4.prototype.crossVector = function ( vector ) {
  28616. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  28617. return vector.applyMatrix4( this );
  28618. };
  28619. Matrix4.prototype.translate = function () {
  28620. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  28621. };
  28622. Matrix4.prototype.rotateX = function () {
  28623. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  28624. };
  28625. Matrix4.prototype.rotateY = function () {
  28626. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  28627. };
  28628. Matrix4.prototype.rotateZ = function () {
  28629. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  28630. };
  28631. Matrix4.prototype.rotateByAxis = function () {
  28632. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  28633. };
  28634. Matrix4.prototype.applyToBufferAttribute = function ( attribute ) {
  28635. console.warn( 'THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.' );
  28636. return attribute.applyMatrix4( this );
  28637. };
  28638. Matrix4.prototype.applyToVector3Array = function ( /* array, offset, length */ ) {
  28639. console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' );
  28640. };
  28641. Matrix4.prototype.makeFrustum = function ( left, right, bottom, top, near, far ) {
  28642. console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' );
  28643. return this.makePerspective( left, right, top, bottom, near, far );
  28644. };
  28645. Matrix4.prototype.getInverse = function ( matrix ) {
  28646. console.warn( 'THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.' );
  28647. return this.copy( matrix ).invert();
  28648. };
  28649. //
  28650. Plane.prototype.isIntersectionLine = function ( line ) {
  28651. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  28652. return this.intersectsLine( line );
  28653. };
  28654. //
  28655. Quaternion.prototype.multiplyVector3 = function ( vector ) {
  28656. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  28657. return vector.applyQuaternion( this );
  28658. };
  28659. Quaternion.prototype.inverse = function ( ) {
  28660. console.warn( 'THREE.Quaternion: .inverse() has been renamed to invert().' );
  28661. return this.invert();
  28662. };
  28663. //
  28664. Ray.prototype.isIntersectionBox = function ( box ) {
  28665. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  28666. return this.intersectsBox( box );
  28667. };
  28668. Ray.prototype.isIntersectionPlane = function ( plane ) {
  28669. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  28670. return this.intersectsPlane( plane );
  28671. };
  28672. Ray.prototype.isIntersectionSphere = function ( sphere ) {
  28673. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  28674. return this.intersectsSphere( sphere );
  28675. };
  28676. //
  28677. Triangle.prototype.area = function () {
  28678. console.warn( 'THREE.Triangle: .area() has been renamed to .getArea().' );
  28679. return this.getArea();
  28680. };
  28681. Triangle.prototype.barycoordFromPoint = function ( point, target ) {
  28682. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  28683. return this.getBarycoord( point, target );
  28684. };
  28685. Triangle.prototype.midpoint = function ( target ) {
  28686. console.warn( 'THREE.Triangle: .midpoint() has been renamed to .getMidpoint().' );
  28687. return this.getMidpoint( target );
  28688. };
  28689. Triangle.prototypenormal = function ( target ) {
  28690. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  28691. return this.getNormal( target );
  28692. };
  28693. Triangle.prototype.plane = function ( target ) {
  28694. console.warn( 'THREE.Triangle: .plane() has been renamed to .getPlane().' );
  28695. return this.getPlane( target );
  28696. };
  28697. Triangle.barycoordFromPoint = function ( point, a, b, c, target ) {
  28698. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  28699. return Triangle.getBarycoord( point, a, b, c, target );
  28700. };
  28701. Triangle.normal = function ( a, b, c, target ) {
  28702. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  28703. return Triangle.getNormal( a, b, c, target );
  28704. };
  28705. //
  28706. Shape.prototype.extractAllPoints = function ( divisions ) {
  28707. console.warn( 'THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.' );
  28708. return this.extractPoints( divisions );
  28709. };
  28710. Shape.prototype.extrude = function ( options ) {
  28711. console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
  28712. return new ExtrudeGeometry( this, options );
  28713. };
  28714. Shape.prototype.makeGeometry = function ( options ) {
  28715. console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
  28716. return new ShapeGeometry( this, options );
  28717. };
  28718. //
  28719. Vector2.prototype.fromAttribute = function ( attribute, index, offset ) {
  28720. console.warn( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  28721. return this.fromBufferAttribute( attribute, index, offset );
  28722. };
  28723. Vector2.prototype.distanceToManhattan = function ( v ) {
  28724. console.warn( 'THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  28725. return this.manhattanDistanceTo( v );
  28726. };
  28727. Vector2.prototype.lengthManhattan = function () {
  28728. console.warn( 'THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().' );
  28729. return this.manhattanLength();
  28730. };
  28731. //
  28732. Vector3.prototype.setEulerFromRotationMatrix = function () {
  28733. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  28734. };
  28735. Vector3.prototype.setEulerFromQuaternion = function () {
  28736. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  28737. };
  28738. Vector3.prototype.getPositionFromMatrix = function ( m ) {
  28739. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  28740. return this.setFromMatrixPosition( m );
  28741. };
  28742. Vector3.prototype.getScaleFromMatrix = function ( m ) {
  28743. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  28744. return this.setFromMatrixScale( m );
  28745. };
  28746. Vector3.prototype.getColumnFromMatrix = function ( index, matrix ) {
  28747. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  28748. return this.setFromMatrixColumn( matrix, index );
  28749. };
  28750. Vector3.prototype.applyProjection = function ( m ) {
  28751. console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' );
  28752. return this.applyMatrix4( m );
  28753. };
  28754. Vector3.prototype.fromAttribute = function ( attribute, index, offset ) {
  28755. console.warn( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  28756. return this.fromBufferAttribute( attribute, index, offset );
  28757. };
  28758. Vector3.prototype.distanceToManhattan = function ( v ) {
  28759. console.warn( 'THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  28760. return this.manhattanDistanceTo( v );
  28761. };
  28762. Vector3.prototype.lengthManhattan = function () {
  28763. console.warn( 'THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().' );
  28764. return this.manhattanLength();
  28765. };
  28766. //
  28767. Vector4.prototype.fromAttribute = function ( attribute, index, offset ) {
  28768. console.warn( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  28769. return this.fromBufferAttribute( attribute, index, offset );
  28770. };
  28771. Vector4.prototype.lengthManhattan = function () {
  28772. console.warn( 'THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().' );
  28773. return this.manhattanLength();
  28774. };
  28775. //
  28776. Object3D.prototype.getChildByName = function ( name ) {
  28777. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  28778. return this.getObjectByName( name );
  28779. };
  28780. Object3D.prototype.renderDepth = function () {
  28781. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  28782. };
  28783. Object3D.prototype.translate = function ( distance, axis ) {
  28784. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  28785. return this.translateOnAxis( axis, distance );
  28786. };
  28787. Object3D.prototype.getWorldRotation = function () {
  28788. console.error( 'THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.' );
  28789. };
  28790. Object3D.prototype.applyMatrix = function ( matrix ) {
  28791. console.warn( 'THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().' );
  28792. return this.applyMatrix4( matrix );
  28793. };
  28794. Object.defineProperties( Object3D.prototype, {
  28795. eulerOrder: {
  28796. get: function () {
  28797. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  28798. return this.rotation.order;
  28799. },
  28800. set: function ( value ) {
  28801. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  28802. this.rotation.order = value;
  28803. }
  28804. },
  28805. useQuaternion: {
  28806. get: function () {
  28807. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  28808. },
  28809. set: function () {
  28810. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  28811. }
  28812. }
  28813. } );
  28814. Mesh.prototype.setDrawMode = function () {
  28815. console.error( 'THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' );
  28816. };
  28817. Object.defineProperties( Mesh.prototype, {
  28818. drawMode: {
  28819. get: function () {
  28820. console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.' );
  28821. return TrianglesDrawMode;
  28822. },
  28823. set: function () {
  28824. console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' );
  28825. }
  28826. }
  28827. } );
  28828. SkinnedMesh.prototype.initBones = function () {
  28829. console.error( 'THREE.SkinnedMesh: initBones() has been removed.' );
  28830. };
  28831. //
  28832. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  28833. console.warn( 'THREE.PerspectiveCamera.setLens is deprecated. ' +
  28834. 'Use .setFocalLength and .filmGauge for a photographic setup.' );
  28835. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  28836. this.setFocalLength( focalLength );
  28837. };
  28838. //
  28839. Object.defineProperties( Light.prototype, {
  28840. onlyShadow: {
  28841. set: function () {
  28842. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  28843. }
  28844. },
  28845. shadowCameraFov: {
  28846. set: function ( value ) {
  28847. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  28848. this.shadow.camera.fov = value;
  28849. }
  28850. },
  28851. shadowCameraLeft: {
  28852. set: function ( value ) {
  28853. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  28854. this.shadow.camera.left = value;
  28855. }
  28856. },
  28857. shadowCameraRight: {
  28858. set: function ( value ) {
  28859. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  28860. this.shadow.camera.right = value;
  28861. }
  28862. },
  28863. shadowCameraTop: {
  28864. set: function ( value ) {
  28865. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  28866. this.shadow.camera.top = value;
  28867. }
  28868. },
  28869. shadowCameraBottom: {
  28870. set: function ( value ) {
  28871. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  28872. this.shadow.camera.bottom = value;
  28873. }
  28874. },
  28875. shadowCameraNear: {
  28876. set: function ( value ) {
  28877. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  28878. this.shadow.camera.near = value;
  28879. }
  28880. },
  28881. shadowCameraFar: {
  28882. set: function ( value ) {
  28883. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  28884. this.shadow.camera.far = value;
  28885. }
  28886. },
  28887. shadowCameraVisible: {
  28888. set: function () {
  28889. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  28890. }
  28891. },
  28892. shadowBias: {
  28893. set: function ( value ) {
  28894. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  28895. this.shadow.bias = value;
  28896. }
  28897. },
  28898. shadowDarkness: {
  28899. set: function () {
  28900. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  28901. }
  28902. },
  28903. shadowMapWidth: {
  28904. set: function ( value ) {
  28905. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  28906. this.shadow.mapSize.width = value;
  28907. }
  28908. },
  28909. shadowMapHeight: {
  28910. set: function ( value ) {
  28911. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  28912. this.shadow.mapSize.height = value;
  28913. }
  28914. }
  28915. } );
  28916. //
  28917. Object.defineProperties( BufferAttribute.prototype, {
  28918. length: {
  28919. get: function () {
  28920. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
  28921. return this.array.length;
  28922. }
  28923. },
  28924. dynamic: {
  28925. get: function () {
  28926. console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' );
  28927. return this.usage === DynamicDrawUsage;
  28928. },
  28929. set: function ( /* value */ ) {
  28930. console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' );
  28931. this.setUsage( DynamicDrawUsage );
  28932. }
  28933. }
  28934. } );
  28935. BufferAttribute.prototype.setDynamic = function ( value ) {
  28936. console.warn( 'THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.' );
  28937. this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage );
  28938. return this;
  28939. };
  28940. BufferAttribute.prototype.copyIndicesArray = function ( /* indices */ ) {
  28941. console.error( 'THREE.BufferAttribute: .copyIndicesArray() has been removed.' );
  28942. },
  28943. BufferAttribute.prototype.setArray = function ( /* array */ ) {
  28944. console.error( 'THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );
  28945. };
  28946. //
  28947. BufferGeometry.prototype.addIndex = function ( index ) {
  28948. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  28949. this.setIndex( index );
  28950. };
  28951. BufferGeometry.prototype.addAttribute = function ( name, attribute ) {
  28952. console.warn( 'THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().' );
  28953. if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) {
  28954. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  28955. return this.setAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  28956. }
  28957. if ( name === 'index' ) {
  28958. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  28959. this.setIndex( attribute );
  28960. return this;
  28961. }
  28962. return this.setAttribute( name, attribute );
  28963. };
  28964. BufferGeometry.prototype.addDrawCall = function ( start, count, indexOffset ) {
  28965. if ( indexOffset !== undefined ) {
  28966. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  28967. }
  28968. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  28969. this.addGroup( start, count );
  28970. };
  28971. BufferGeometry.prototype.clearDrawCalls = function () {
  28972. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  28973. this.clearGroups();
  28974. };
  28975. BufferGeometry.prototype.computeOffsets = function () {
  28976. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  28977. };
  28978. BufferGeometry.prototype.removeAttribute = function ( name ) {
  28979. console.warn( 'THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().' );
  28980. return this.deleteAttribute( name );
  28981. };
  28982. BufferGeometry.prototype.applyMatrix = function ( matrix ) {
  28983. console.warn( 'THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().' );
  28984. return this.applyMatrix4( matrix );
  28985. };
  28986. Object.defineProperties( BufferGeometry.prototype, {
  28987. drawcalls: {
  28988. get: function () {
  28989. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  28990. return this.groups;
  28991. }
  28992. },
  28993. offsets: {
  28994. get: function () {
  28995. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  28996. return this.groups;
  28997. }
  28998. }
  28999. } );
  29000. InterleavedBuffer.prototype.setDynamic = function ( value ) {
  29001. console.warn( 'THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.' );
  29002. this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage );
  29003. return this;
  29004. };
  29005. InterleavedBuffer.prototype.setArray = function ( /* array */ ) {
  29006. console.error( 'THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );
  29007. };
  29008. //
  29009. ExtrudeGeometry.prototype.getArrays = function () {
  29010. console.error( 'THREE.ExtrudeGeometry: .getArrays() has been removed.' );
  29011. };
  29012. ExtrudeGeometry.prototype.addShapeList = function () {
  29013. console.error( 'THREE.ExtrudeGeometry: .addShapeList() has been removed.' );
  29014. };
  29015. ExtrudeGeometry.prototype.addShape = function () {
  29016. console.error( 'THREE.ExtrudeGeometry: .addShape() has been removed.' );
  29017. };
  29018. //
  29019. Scene.prototype.dispose = function () {
  29020. console.error( 'THREE.Scene: .dispose() has been removed.' );
  29021. };
  29022. //
  29023. Uniform.prototype.onUpdate = function () {
  29024. console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
  29025. return this;
  29026. };
  29027. //
  29028. Object.defineProperties( Material.prototype, {
  29029. wrapAround: {
  29030. get: function () {
  29031. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  29032. },
  29033. set: function () {
  29034. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  29035. }
  29036. },
  29037. overdraw: {
  29038. get: function () {
  29039. console.warn( 'THREE.Material: .overdraw has been removed.' );
  29040. },
  29041. set: function () {
  29042. console.warn( 'THREE.Material: .overdraw has been removed.' );
  29043. }
  29044. },
  29045. wrapRGB: {
  29046. get: function () {
  29047. console.warn( 'THREE.Material: .wrapRGB has been removed.' );
  29048. return new Color();
  29049. }
  29050. },
  29051. shading: {
  29052. get: function () {
  29053. console.error( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  29054. },
  29055. set: function ( value ) {
  29056. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  29057. this.flatShading = ( value === FlatShading );
  29058. }
  29059. },
  29060. stencilMask: {
  29061. get: function () {
  29062. console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
  29063. return this.stencilFuncMask;
  29064. },
  29065. set: function ( value ) {
  29066. console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
  29067. this.stencilFuncMask = value;
  29068. }
  29069. },
  29070. vertexTangents: {
  29071. get: function () {
  29072. console.warn( 'THREE.' + this.type + ': .vertexTangents has been removed.' );
  29073. },
  29074. set: function () {
  29075. console.warn( 'THREE.' + this.type + ': .vertexTangents has been removed.' );
  29076. }
  29077. },
  29078. } );
  29079. Object.defineProperties( ShaderMaterial.prototype, {
  29080. derivatives: {
  29081. get: function () {
  29082. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  29083. return this.extensions.derivatives;
  29084. },
  29085. set: function ( value ) {
  29086. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  29087. this.extensions.derivatives = value;
  29088. }
  29089. }
  29090. } );
  29091. //
  29092. WebGLRenderer.prototype.clearTarget = function ( renderTarget, color, depth, stencil ) {
  29093. console.warn( 'THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.' );
  29094. this.setRenderTarget( renderTarget );
  29095. this.clear( color, depth, stencil );
  29096. };
  29097. WebGLRenderer.prototype.animate = function ( callback ) {
  29098. console.warn( 'THREE.WebGLRenderer: .animate() is now .setAnimationLoop().' );
  29099. this.setAnimationLoop( callback );
  29100. };
  29101. WebGLRenderer.prototype.getCurrentRenderTarget = function () {
  29102. console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' );
  29103. return this.getRenderTarget();
  29104. };
  29105. WebGLRenderer.prototype.getMaxAnisotropy = function () {
  29106. console.warn( 'THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().' );
  29107. return this.capabilities.getMaxAnisotropy();
  29108. };
  29109. WebGLRenderer.prototype.getPrecision = function () {
  29110. console.warn( 'THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.' );
  29111. return this.capabilities.precision;
  29112. };
  29113. WebGLRenderer.prototype.resetGLState = function () {
  29114. console.warn( 'THREE.WebGLRenderer: .resetGLState() is now .state.reset().' );
  29115. return this.state.reset();
  29116. };
  29117. WebGLRenderer.prototype.supportsFloatTextures = function () {
  29118. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  29119. return this.extensions.get( 'OES_texture_float' );
  29120. };
  29121. WebGLRenderer.prototype.supportsHalfFloatTextures = function () {
  29122. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  29123. return this.extensions.get( 'OES_texture_half_float' );
  29124. };
  29125. WebGLRenderer.prototype.supportsStandardDerivatives = function () {
  29126. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  29127. return this.extensions.get( 'OES_standard_derivatives' );
  29128. };
  29129. WebGLRenderer.prototype.supportsCompressedTextureS3TC = function () {
  29130. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  29131. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  29132. };
  29133. WebGLRenderer.prototype.supportsCompressedTexturePVRTC = function () {
  29134. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  29135. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  29136. };
  29137. WebGLRenderer.prototype.supportsBlendMinMax = function () {
  29138. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  29139. return this.extensions.get( 'EXT_blend_minmax' );
  29140. };
  29141. WebGLRenderer.prototype.supportsVertexTextures = function () {
  29142. console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
  29143. return this.capabilities.vertexTextures;
  29144. };
  29145. WebGLRenderer.prototype.supportsInstancedArrays = function () {
  29146. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  29147. return this.extensions.get( 'ANGLE_instanced_arrays' );
  29148. };
  29149. WebGLRenderer.prototype.enableScissorTest = function ( boolean ) {
  29150. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  29151. this.setScissorTest( boolean );
  29152. };
  29153. WebGLRenderer.prototype.initMaterial = function () {
  29154. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  29155. };
  29156. WebGLRenderer.prototype.addPrePlugin = function () {
  29157. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  29158. };
  29159. WebGLRenderer.prototype.addPostPlugin = function () {
  29160. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  29161. };
  29162. WebGLRenderer.prototype.updateShadowMap = function () {
  29163. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  29164. };
  29165. WebGLRenderer.prototype.setFaceCulling = function () {
  29166. console.warn( 'THREE.WebGLRenderer: .setFaceCulling() has been removed.' );
  29167. };
  29168. WebGLRenderer.prototype.allocTextureUnit = function () {
  29169. console.warn( 'THREE.WebGLRenderer: .allocTextureUnit() has been removed.' );
  29170. };
  29171. WebGLRenderer.prototype.setTexture = function () {
  29172. console.warn( 'THREE.WebGLRenderer: .setTexture() has been removed.' );
  29173. };
  29174. WebGLRenderer.prototype.setTexture2D = function () {
  29175. console.warn( 'THREE.WebGLRenderer: .setTexture2D() has been removed.' );
  29176. };
  29177. WebGLRenderer.prototype.setTextureCube = function () {
  29178. console.warn( 'THREE.WebGLRenderer: .setTextureCube() has been removed.' );
  29179. };
  29180. WebGLRenderer.prototype.getActiveMipMapLevel = function () {
  29181. console.warn( 'THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().' );
  29182. return this.getActiveMipmapLevel();
  29183. };
  29184. Object.defineProperties( WebGLRenderer.prototype, {
  29185. shadowMapEnabled: {
  29186. get: function () {
  29187. return this.shadowMap.enabled;
  29188. },
  29189. set: function ( value ) {
  29190. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  29191. this.shadowMap.enabled = value;
  29192. }
  29193. },
  29194. shadowMapType: {
  29195. get: function () {
  29196. return this.shadowMap.type;
  29197. },
  29198. set: function ( value ) {
  29199. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  29200. this.shadowMap.type = value;
  29201. }
  29202. },
  29203. shadowMapCullFace: {
  29204. get: function () {
  29205. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  29206. return undefined;
  29207. },
  29208. set: function ( /* value */ ) {
  29209. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  29210. }
  29211. },
  29212. context: {
  29213. get: function () {
  29214. console.warn( 'THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.' );
  29215. return this.getContext();
  29216. }
  29217. },
  29218. vr: {
  29219. get: function () {
  29220. console.warn( 'THREE.WebGLRenderer: .vr has been renamed to .xr' );
  29221. return this.xr;
  29222. }
  29223. },
  29224. gammaInput: {
  29225. get: function () {
  29226. console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' );
  29227. return false;
  29228. },
  29229. set: function () {
  29230. console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' );
  29231. }
  29232. },
  29233. gammaOutput: {
  29234. get: function () {
  29235. console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' );
  29236. return false;
  29237. },
  29238. set: function ( value ) {
  29239. console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' );
  29240. this.outputEncoding = ( value === true ) ? sRGBEncoding : LinearEncoding;
  29241. }
  29242. },
  29243. toneMappingWhitePoint: {
  29244. get: function () {
  29245. console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' );
  29246. return 1.0;
  29247. },
  29248. set: function () {
  29249. console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' );
  29250. }
  29251. },
  29252. } );
  29253. Object.defineProperties( WebGLShadowMap.prototype, {
  29254. cullFace: {
  29255. get: function () {
  29256. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  29257. return undefined;
  29258. },
  29259. set: function ( /* cullFace */ ) {
  29260. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  29261. }
  29262. },
  29263. renderReverseSided: {
  29264. get: function () {
  29265. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  29266. return undefined;
  29267. },
  29268. set: function () {
  29269. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  29270. }
  29271. },
  29272. renderSingleSided: {
  29273. get: function () {
  29274. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  29275. return undefined;
  29276. },
  29277. set: function () {
  29278. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  29279. }
  29280. }
  29281. } );
  29282. function WebGLRenderTargetCube( width, height, options ) {
  29283. console.warn( 'THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).' );
  29284. return new WebGLCubeRenderTarget( width, options );
  29285. }
  29286. //
  29287. Object.defineProperties( WebGLRenderTarget.prototype, {
  29288. wrapS: {
  29289. get: function () {
  29290. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  29291. return this.texture.wrapS;
  29292. },
  29293. set: function ( value ) {
  29294. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  29295. this.texture.wrapS = value;
  29296. }
  29297. },
  29298. wrapT: {
  29299. get: function () {
  29300. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  29301. return this.texture.wrapT;
  29302. },
  29303. set: function ( value ) {
  29304. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  29305. this.texture.wrapT = value;
  29306. }
  29307. },
  29308. magFilter: {
  29309. get: function () {
  29310. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  29311. return this.texture.magFilter;
  29312. },
  29313. set: function ( value ) {
  29314. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  29315. this.texture.magFilter = value;
  29316. }
  29317. },
  29318. minFilter: {
  29319. get: function () {
  29320. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  29321. return this.texture.minFilter;
  29322. },
  29323. set: function ( value ) {
  29324. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  29325. this.texture.minFilter = value;
  29326. }
  29327. },
  29328. anisotropy: {
  29329. get: function () {
  29330. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  29331. return this.texture.anisotropy;
  29332. },
  29333. set: function ( value ) {
  29334. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  29335. this.texture.anisotropy = value;
  29336. }
  29337. },
  29338. offset: {
  29339. get: function () {
  29340. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  29341. return this.texture.offset;
  29342. },
  29343. set: function ( value ) {
  29344. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  29345. this.texture.offset = value;
  29346. }
  29347. },
  29348. repeat: {
  29349. get: function () {
  29350. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  29351. return this.texture.repeat;
  29352. },
  29353. set: function ( value ) {
  29354. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  29355. this.texture.repeat = value;
  29356. }
  29357. },
  29358. format: {
  29359. get: function () {
  29360. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  29361. return this.texture.format;
  29362. },
  29363. set: function ( value ) {
  29364. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  29365. this.texture.format = value;
  29366. }
  29367. },
  29368. type: {
  29369. get: function () {
  29370. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  29371. return this.texture.type;
  29372. },
  29373. set: function ( value ) {
  29374. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  29375. this.texture.type = value;
  29376. }
  29377. },
  29378. generateMipmaps: {
  29379. get: function () {
  29380. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  29381. return this.texture.generateMipmaps;
  29382. },
  29383. set: function ( value ) {
  29384. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  29385. this.texture.generateMipmaps = value;
  29386. }
  29387. }
  29388. } );
  29389. //
  29390. Audio.prototype.load = function ( file ) {
  29391. console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
  29392. const scope = this;
  29393. const audioLoader = new AudioLoader();
  29394. audioLoader.load( file, function ( buffer ) {
  29395. scope.setBuffer( buffer );
  29396. } );
  29397. return this;
  29398. };
  29399. AudioAnalyser.prototype.getData = function () {
  29400. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  29401. return this.getFrequencyData();
  29402. };
  29403. //
  29404. CubeCamera.prototype.updateCubeMap = function ( renderer, scene ) {
  29405. console.warn( 'THREE.CubeCamera: .updateCubeMap() is now .update().' );
  29406. return this.update( renderer, scene );
  29407. };
  29408. CubeCamera.prototype.clear = function ( renderer, color, depth, stencil ) {
  29409. console.warn( 'THREE.CubeCamera: .clear() is now .renderTarget.clear().' );
  29410. return this.renderTarget.clear( renderer, color, depth, stencil );
  29411. };
  29412. ImageUtils.crossOrigin = undefined;
  29413. ImageUtils.loadTexture = function ( url, mapping, onLoad, onError ) {
  29414. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  29415. const loader = new TextureLoader();
  29416. loader.setCrossOrigin( this.crossOrigin );
  29417. const texture = loader.load( url, onLoad, undefined, onError );
  29418. if ( mapping ) texture.mapping = mapping;
  29419. return texture;
  29420. };
  29421. ImageUtils.loadTextureCube = function ( urls, mapping, onLoad, onError ) {
  29422. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  29423. const loader = new CubeTextureLoader();
  29424. loader.setCrossOrigin( this.crossOrigin );
  29425. const texture = loader.load( urls, onLoad, undefined, onError );
  29426. if ( mapping ) texture.mapping = mapping;
  29427. return texture;
  29428. };
  29429. ImageUtils.loadCompressedTexture = function () {
  29430. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  29431. };
  29432. ImageUtils.loadCompressedTextureCube = function () {
  29433. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  29434. };
  29435. //
  29436. function CanvasRenderer() {
  29437. console.error( 'THREE.CanvasRenderer has been removed' );
  29438. }
  29439. //
  29440. function JSONLoader() {
  29441. console.error( 'THREE.JSONLoader has been removed.' );
  29442. }
  29443. //
  29444. const SceneUtils = {
  29445. createMultiMaterialObject: function ( /* geometry, materials */ ) {
  29446. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  29447. },
  29448. detach: function ( /* child, parent, scene */ ) {
  29449. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  29450. },
  29451. attach: function ( /* child, scene, parent */ ) {
  29452. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  29453. }
  29454. };
  29455. //
  29456. function LensFlare() {
  29457. console.error( 'THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js' );
  29458. }
  29459. //
  29460. function ParametricGeometry() {
  29461. console.error( 'THREE.ParametricGeometry has been moved to /examples/jsm/geometries/ParametricGeometry.js' );
  29462. return new BufferGeometry();
  29463. }
  29464. function TextGeometry() {
  29465. console.error( 'THREE.TextGeometry has been moved to /examples/jsm/geometries/TextGeometry.js' );
  29466. return new BufferGeometry();
  29467. }
  29468. function FontLoader() {
  29469. console.error( 'THREE.FontLoader has been moved to /examples/jsm/loaders/FontLoader.js' );
  29470. }
  29471. function Font() {
  29472. console.error( 'THREE.Font has been moved to /examples/jsm/loaders/FontLoader.js' );
  29473. }
  29474. function ImmediateRenderObject() {
  29475. console.error( 'THREE.ImmediateRenderObject has been removed.' );
  29476. }
  29477. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  29478. /* eslint-disable no-undef */
  29479. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  29480. revision: REVISION,
  29481. } } ) );
  29482. /* eslint-enable no-undef */
  29483. }
  29484. if ( typeof window !== 'undefined' ) {
  29485. if ( window.__THREE__ ) {
  29486. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  29487. } else {
  29488. window.__THREE__ = REVISION;
  29489. }
  29490. }
  29491. export { ACESFilmicToneMapping, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AlphaFormat, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightProbe, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrowHelper, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, AxisHelper, BackSide, BasicDepthPacking, BasicShadowMap, BinaryTextureLoader, Bone, BooleanKeyframeTrack, BoundingBoxHelper, Box2, Box3, Box3Helper, BoxGeometry as BoxBufferGeometry, BoxGeometry, BoxHelper, BufferAttribute, BufferGeometry, BufferGeometryLoader, ByteType, Cache, Camera, CameraHelper, CanvasRenderer, CanvasTexture, CatmullRomCurve3, CineonToneMapping, CircleGeometry as CircleBufferGeometry, CircleGeometry, ClampToEdgeWrapping, Clock, Color, ColorKeyframeTrack, CompressedTexture, CompressedTextureLoader, ConeGeometry as ConeBufferGeometry, ConeGeometry, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeUVReflectionMapping, CubeUVRefractionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderGeometry as CylinderBufferGeometry, CylinderGeometry, Cylindrical, DataTexture, DataTexture2DArray, DataTexture3D, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry as DodecahedronBufferGeometry, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicBufferAttribute, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EdgesGeometry, EdgesHelper, EllipseCurve, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExtrudeGeometry as ExtrudeBufferGeometry, ExtrudeGeometry, FaceColors, FileLoader, FlatShading, Float16BufferAttribute, Float32Attribute, Float32BufferAttribute, Float64Attribute, Float64BufferAttribute, FloatType, Fog, FogExp2, Font, FontLoader, FrontSide, Frustum, GLBufferAttribute, GLSL1, GLSL3, GammaEncoding, GreaterDepth, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, HemisphereLightProbe, IcosahedronGeometry as IcosahedronBufferGeometry, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, ImmediateRenderObject, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, Int16Attribute, Int16BufferAttribute, Int32Attribute, Int32BufferAttribute, Int8Attribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InvertStencilOp, JSONLoader, KeepStencilOp, KeyframeTrack, LOD, LatheGeometry as LatheBufferGeometry, LatheGeometry, Layers, LensFlare, LessDepth, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, Line, Line3, LineBasicMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineLoop, LinePieces, LineSegments, LineStrip, LinearEncoding, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearToneMapping, Loader, LoaderUtils, LoadingManager, LogLuvEncoding, LoopOnce, LoopPingPong, LoopRepeat, LuminanceAlphaFormat, LuminanceFormat, MOUSE, Material, MaterialLoader, MathUtils as Math, MathUtils, Matrix3, Matrix4, MaxEquation, Mesh, MeshBasicMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshFaceMaterial, MeshLambertMaterial, MeshMatcapMaterial, MeshNormalMaterial, MeshPhongMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, MultiMaterial, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeverDepth, NeverStencilFunc, NoBlending, NoColors, NoToneMapping, NormalAnimationBlendMode, NormalBlending, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, ObjectLoader, ObjectSpaceNormalMap, OctahedronGeometry as OctahedronBufferGeometry, OctahedronGeometry, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, PCFShadowMap, PCFSoftShadowMap, PMREMGenerator, ParametricGeometry, Particle, ParticleBasicMaterial, ParticleSystem, ParticleSystemMaterial, Path, PerspectiveCamera, Plane, PlaneGeometry as PlaneBufferGeometry, PlaneGeometry, PlaneHelper, PointCloud, PointCloudMaterial, PointLight, PointLightHelper, Points, PointsMaterial, PolarGridHelper, PolyhedronGeometry as PolyhedronBufferGeometry, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, REVISION, RGBADepthPacking, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBDEncoding, RGBEEncoding, RGBEFormat, RGBFormat, RGBIntegerFormat, RGBM16Encoding, RGBM7Encoding, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RawShaderMaterial, Ray, Raycaster, RectAreaLight, RedFormat, RedIntegerFormat, ReinhardToneMapping, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RingGeometry as RingBufferGeometry, RingGeometry, SRGB8_ALPHA8_ASTC_10x10_Format, SRGB8_ALPHA8_ASTC_10x5_Format, SRGB8_ALPHA8_ASTC_10x6_Format, SRGB8_ALPHA8_ASTC_10x8_Format, SRGB8_ALPHA8_ASTC_12x10_Format, SRGB8_ALPHA8_ASTC_12x12_Format, SRGB8_ALPHA8_ASTC_4x4_Format, SRGB8_ALPHA8_ASTC_5x4_Format, SRGB8_ALPHA8_ASTC_5x5_Format, SRGB8_ALPHA8_ASTC_6x5_Format, SRGB8_ALPHA8_ASTC_6x6_Format, SRGB8_ALPHA8_ASTC_8x5_Format, SRGB8_ALPHA8_ASTC_8x6_Format, SRGB8_ALPHA8_ASTC_8x8_Format, Scene, SceneUtils, ShaderChunk, ShaderLib, ShaderMaterial, ShadowMaterial, Shape, ShapeGeometry as ShapeBufferGeometry, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, SmoothShading, Sphere, SphereGeometry as SphereBufferGeometry, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SpotLight, SpotLightHelper, Sprite, SpriteMaterial, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TOUCH, TangentSpaceNormalMap, TetrahedronGeometry as TetrahedronBufferGeometry, TetrahedronGeometry, TextGeometry, Texture, TextureLoader, TorusGeometry as TorusBufferGeometry, TorusGeometry, TorusKnotGeometry as TorusKnotBufferGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry as TubeBufferGeometry, TubeGeometry, UVMapping, Uint16Attribute, Uint16BufferAttribute, Uint32Attribute, Uint32BufferAttribute, Uint8Attribute, Uint8BufferAttribute, Uint8ClampedAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsLib, UniformsUtils, UnsignedByteType, UnsignedInt248Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShort565Type, UnsignedShortType, VSMShadowMap, Vector2, Vector3, Vector4, VectorKeyframeTrack, Vertex, VertexColors, VideoTexture, WebGL1Renderer, WebGLCubeRenderTarget, WebGLMultipleRenderTargets, WebGLMultisampleRenderTarget, WebGLRenderTarget, WebGLRenderTargetCube, WebGLRenderer, WebGLUtils, WireframeGeometry, WireframeHelper, WrapAroundEnding, XHRLoader, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, sRGBEncoding };