2
0

three.module.js 1.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996
  1. /**
  2. * @license
  3. * Copyright 2010-2021 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '127dev';
  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. function EventDispatcher() {}
  204. Object.assign( EventDispatcher.prototype, {
  205. addEventListener: function ( type, listener ) {
  206. if ( this._listeners === undefined ) this._listeners = {};
  207. const listeners = this._listeners;
  208. if ( listeners[ type ] === undefined ) {
  209. listeners[ type ] = [];
  210. }
  211. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  212. listeners[ type ].push( listener );
  213. }
  214. },
  215. hasEventListener: function ( type, listener ) {
  216. if ( this._listeners === undefined ) return false;
  217. const listeners = this._listeners;
  218. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  219. },
  220. removeEventListener: function ( type, listener ) {
  221. if ( this._listeners === undefined ) return;
  222. const listeners = this._listeners;
  223. const listenerArray = listeners[ type ];
  224. if ( listenerArray !== undefined ) {
  225. const index = listenerArray.indexOf( listener );
  226. if ( index !== - 1 ) {
  227. listenerArray.splice( index, 1 );
  228. }
  229. }
  230. },
  231. dispatchEvent: function ( event ) {
  232. if ( this._listeners === undefined ) return;
  233. const listeners = this._listeners;
  234. const listenerArray = listeners[ event.type ];
  235. if ( listenerArray !== undefined ) {
  236. event.target = this;
  237. // Make a copy, in case listeners are removed while iterating.
  238. const array = listenerArray.slice( 0 );
  239. for ( let i = 0, l = array.length; i < l; i ++ ) {
  240. array[ i ].call( this, event );
  241. }
  242. }
  243. }
  244. } );
  245. const _lut = [];
  246. for ( let i = 0; i < 256; i ++ ) {
  247. _lut[ i ] = ( i < 16 ? '0' : '' ) + ( i ).toString( 16 );
  248. }
  249. let _seed = 1234567;
  250. const MathUtils = {
  251. DEG2RAD: Math.PI / 180,
  252. RAD2DEG: 180 / Math.PI,
  253. generateUUID: function () {
  254. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  255. const d0 = Math.random() * 0xffffffff | 0;
  256. const d1 = Math.random() * 0xffffffff | 0;
  257. const d2 = Math.random() * 0xffffffff | 0;
  258. const d3 = Math.random() * 0xffffffff | 0;
  259. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  260. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  261. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  262. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  263. // .toUpperCase() here flattens concatenated strings to save heap memory space.
  264. return uuid.toUpperCase();
  265. },
  266. clamp: function ( value, min, max ) {
  267. return Math.max( min, Math.min( max, value ) );
  268. },
  269. // compute euclidian modulo of m % n
  270. // https://en.wikipedia.org/wiki/Modulo_operation
  271. euclideanModulo: function ( n, m ) {
  272. return ( ( n % m ) + m ) % m;
  273. },
  274. // Linear mapping from range <a1, a2> to range <b1, b2>
  275. mapLinear: function ( x, a1, a2, b1, b2 ) {
  276. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  277. },
  278. // https://en.wikipedia.org/wiki/Linear_interpolation
  279. lerp: function ( x, y, t ) {
  280. return ( 1 - t ) * x + t * y;
  281. },
  282. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  283. damp: function ( x, y, lambda, dt ) {
  284. return MathUtils.lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  285. },
  286. // https://www.desmos.com/calculator/vcsjnyz7x4
  287. pingpong: function ( x, length = 1 ) {
  288. return length - Math.abs( MathUtils.euclideanModulo( x, length * 2 ) - length );
  289. },
  290. // http://en.wikipedia.org/wiki/Smoothstep
  291. smoothstep: function ( x, min, max ) {
  292. if ( x <= min ) return 0;
  293. if ( x >= max ) return 1;
  294. x = ( x - min ) / ( max - min );
  295. return x * x * ( 3 - 2 * x );
  296. },
  297. smootherstep: function ( x, min, max ) {
  298. if ( x <= min ) return 0;
  299. if ( x >= max ) return 1;
  300. x = ( x - min ) / ( max - min );
  301. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  302. },
  303. // Random integer from <low, high> interval
  304. randInt: function ( low, high ) {
  305. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  306. },
  307. // Random float from <low, high> interval
  308. randFloat: function ( low, high ) {
  309. return low + Math.random() * ( high - low );
  310. },
  311. // Random float from <-range/2, range/2> interval
  312. randFloatSpread: function ( range ) {
  313. return range * ( 0.5 - Math.random() );
  314. },
  315. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  316. seededRandom: function ( s ) {
  317. if ( s !== undefined ) _seed = s % 2147483647;
  318. // Park-Miller algorithm
  319. _seed = _seed * 16807 % 2147483647;
  320. return ( _seed - 1 ) / 2147483646;
  321. },
  322. degToRad: function ( degrees ) {
  323. return degrees * MathUtils.DEG2RAD;
  324. },
  325. radToDeg: function ( radians ) {
  326. return radians * MathUtils.RAD2DEG;
  327. },
  328. isPowerOfTwo: function ( value ) {
  329. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  330. },
  331. ceilPowerOfTwo: function ( value ) {
  332. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  333. },
  334. floorPowerOfTwo: function ( value ) {
  335. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  336. },
  337. setQuaternionFromProperEuler: function ( q, a, b, c, order ) {
  338. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  339. // rotations are applied to the axes in the order specified by 'order'
  340. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  341. // angles are in radians
  342. const cos = Math.cos;
  343. const sin = Math.sin;
  344. const c2 = cos( b / 2 );
  345. const s2 = sin( b / 2 );
  346. const c13 = cos( ( a + c ) / 2 );
  347. const s13 = sin( ( a + c ) / 2 );
  348. const c1_3 = cos( ( a - c ) / 2 );
  349. const s1_3 = sin( ( a - c ) / 2 );
  350. const c3_1 = cos( ( c - a ) / 2 );
  351. const s3_1 = sin( ( c - a ) / 2 );
  352. switch ( order ) {
  353. case 'XYX':
  354. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  355. break;
  356. case 'YZY':
  357. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  358. break;
  359. case 'ZXZ':
  360. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  361. break;
  362. case 'XZX':
  363. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  364. break;
  365. case 'YXY':
  366. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  367. break;
  368. case 'ZYZ':
  369. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  370. break;
  371. default:
  372. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  373. }
  374. }
  375. };
  376. class Vector2 {
  377. constructor( x = 0, y = 0 ) {
  378. this.x = x;
  379. this.y = y;
  380. }
  381. get width() {
  382. return this.x;
  383. }
  384. set width( value ) {
  385. this.x = value;
  386. }
  387. get height() {
  388. return this.y;
  389. }
  390. set height( value ) {
  391. this.y = value;
  392. }
  393. set( x, y ) {
  394. this.x = x;
  395. this.y = y;
  396. return this;
  397. }
  398. setScalar( scalar ) {
  399. this.x = scalar;
  400. this.y = scalar;
  401. return this;
  402. }
  403. setX( x ) {
  404. this.x = x;
  405. return this;
  406. }
  407. setY( y ) {
  408. this.y = y;
  409. return this;
  410. }
  411. setComponent( index, value ) {
  412. switch ( index ) {
  413. case 0: this.x = value; break;
  414. case 1: this.y = value; break;
  415. default: throw new Error( 'index is out of range: ' + index );
  416. }
  417. return this;
  418. }
  419. getComponent( index ) {
  420. switch ( index ) {
  421. case 0: return this.x;
  422. case 1: return this.y;
  423. default: throw new Error( 'index is out of range: ' + index );
  424. }
  425. }
  426. clone() {
  427. return new this.constructor( this.x, this.y );
  428. }
  429. copy( v ) {
  430. this.x = v.x;
  431. this.y = v.y;
  432. return this;
  433. }
  434. add( v, w ) {
  435. if ( w !== undefined ) {
  436. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  437. return this.addVectors( v, w );
  438. }
  439. this.x += v.x;
  440. this.y += v.y;
  441. return this;
  442. }
  443. addScalar( s ) {
  444. this.x += s;
  445. this.y += s;
  446. return this;
  447. }
  448. addVectors( a, b ) {
  449. this.x = a.x + b.x;
  450. this.y = a.y + b.y;
  451. return this;
  452. }
  453. addScaledVector( v, s ) {
  454. this.x += v.x * s;
  455. this.y += v.y * s;
  456. return this;
  457. }
  458. sub( v, w ) {
  459. if ( w !== undefined ) {
  460. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  461. return this.subVectors( v, w );
  462. }
  463. this.x -= v.x;
  464. this.y -= v.y;
  465. return this;
  466. }
  467. subScalar( s ) {
  468. this.x -= s;
  469. this.y -= s;
  470. return this;
  471. }
  472. subVectors( a, b ) {
  473. this.x = a.x - b.x;
  474. this.y = a.y - b.y;
  475. return this;
  476. }
  477. multiply( v ) {
  478. this.x *= v.x;
  479. this.y *= v.y;
  480. return this;
  481. }
  482. multiplyScalar( scalar ) {
  483. this.x *= scalar;
  484. this.y *= scalar;
  485. return this;
  486. }
  487. divide( v ) {
  488. this.x /= v.x;
  489. this.y /= v.y;
  490. return this;
  491. }
  492. divideScalar( scalar ) {
  493. return this.multiplyScalar( 1 / scalar );
  494. }
  495. applyMatrix3( m ) {
  496. const x = this.x, y = this.y;
  497. const e = m.elements;
  498. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  499. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  500. return this;
  501. }
  502. min( v ) {
  503. this.x = Math.min( this.x, v.x );
  504. this.y = Math.min( this.y, v.y );
  505. return this;
  506. }
  507. max( v ) {
  508. this.x = Math.max( this.x, v.x );
  509. this.y = Math.max( this.y, v.y );
  510. return this;
  511. }
  512. clamp( min, max ) {
  513. // assumes min < max, componentwise
  514. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  515. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  516. return this;
  517. }
  518. clampScalar( minVal, maxVal ) {
  519. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  520. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  521. return this;
  522. }
  523. clampLength( min, max ) {
  524. const length = this.length();
  525. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  526. }
  527. floor() {
  528. this.x = Math.floor( this.x );
  529. this.y = Math.floor( this.y );
  530. return this;
  531. }
  532. ceil() {
  533. this.x = Math.ceil( this.x );
  534. this.y = Math.ceil( this.y );
  535. return this;
  536. }
  537. round() {
  538. this.x = Math.round( this.x );
  539. this.y = Math.round( this.y );
  540. return this;
  541. }
  542. roundToZero() {
  543. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  544. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  545. return this;
  546. }
  547. negate() {
  548. this.x = - this.x;
  549. this.y = - this.y;
  550. return this;
  551. }
  552. dot( v ) {
  553. return this.x * v.x + this.y * v.y;
  554. }
  555. cross( v ) {
  556. return this.x * v.y - this.y * v.x;
  557. }
  558. lengthSq() {
  559. return this.x * this.x + this.y * this.y;
  560. }
  561. length() {
  562. return Math.sqrt( this.x * this.x + this.y * this.y );
  563. }
  564. manhattanLength() {
  565. return Math.abs( this.x ) + Math.abs( this.y );
  566. }
  567. normalize() {
  568. return this.divideScalar( this.length() || 1 );
  569. }
  570. angle() {
  571. // computes the angle in radians with respect to the positive x-axis
  572. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  573. return angle;
  574. }
  575. distanceTo( v ) {
  576. return Math.sqrt( this.distanceToSquared( v ) );
  577. }
  578. distanceToSquared( v ) {
  579. const dx = this.x - v.x, dy = this.y - v.y;
  580. return dx * dx + dy * dy;
  581. }
  582. manhattanDistanceTo( v ) {
  583. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  584. }
  585. setLength( length ) {
  586. return this.normalize().multiplyScalar( length );
  587. }
  588. lerp( v, alpha ) {
  589. this.x += ( v.x - this.x ) * alpha;
  590. this.y += ( v.y - this.y ) * alpha;
  591. return this;
  592. }
  593. lerpVectors( v1, v2, alpha ) {
  594. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  595. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  596. return this;
  597. }
  598. equals( v ) {
  599. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  600. }
  601. fromArray( array, offset = 0 ) {
  602. this.x = array[ offset ];
  603. this.y = array[ offset + 1 ];
  604. return this;
  605. }
  606. toArray( array = [], offset = 0 ) {
  607. array[ offset ] = this.x;
  608. array[ offset + 1 ] = this.y;
  609. return array;
  610. }
  611. fromBufferAttribute( attribute, index, offset ) {
  612. if ( offset !== undefined ) {
  613. console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' );
  614. }
  615. this.x = attribute.getX( index );
  616. this.y = attribute.getY( index );
  617. return this;
  618. }
  619. rotateAround( center, angle ) {
  620. const c = Math.cos( angle ), s = Math.sin( angle );
  621. const x = this.x - center.x;
  622. const y = this.y - center.y;
  623. this.x = x * c - y * s + center.x;
  624. this.y = x * s + y * c + center.y;
  625. return this;
  626. }
  627. random() {
  628. this.x = Math.random();
  629. this.y = Math.random();
  630. return this;
  631. }
  632. }
  633. Vector2.prototype.isVector2 = true;
  634. class Matrix3 {
  635. constructor() {
  636. this.elements = [
  637. 1, 0, 0,
  638. 0, 1, 0,
  639. 0, 0, 1
  640. ];
  641. if ( arguments.length > 0 ) {
  642. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  643. }
  644. }
  645. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  646. const te = this.elements;
  647. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  648. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  649. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  650. return this;
  651. }
  652. identity() {
  653. this.set(
  654. 1, 0, 0,
  655. 0, 1, 0,
  656. 0, 0, 1
  657. );
  658. return this;
  659. }
  660. copy( m ) {
  661. const te = this.elements;
  662. const me = m.elements;
  663. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  664. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  665. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  666. return this;
  667. }
  668. extractBasis( xAxis, yAxis, zAxis ) {
  669. xAxis.setFromMatrix3Column( this, 0 );
  670. yAxis.setFromMatrix3Column( this, 1 );
  671. zAxis.setFromMatrix3Column( this, 2 );
  672. return this;
  673. }
  674. setFromMatrix4( m ) {
  675. const me = m.elements;
  676. this.set(
  677. me[ 0 ], me[ 4 ], me[ 8 ],
  678. me[ 1 ], me[ 5 ], me[ 9 ],
  679. me[ 2 ], me[ 6 ], me[ 10 ]
  680. );
  681. return this;
  682. }
  683. multiply( m ) {
  684. return this.multiplyMatrices( this, m );
  685. }
  686. premultiply( m ) {
  687. return this.multiplyMatrices( m, this );
  688. }
  689. multiplyMatrices( a, b ) {
  690. const ae = a.elements;
  691. const be = b.elements;
  692. const te = this.elements;
  693. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  694. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  695. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  696. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  697. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  698. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  699. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  700. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  701. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  702. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  703. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  704. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  705. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  706. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  707. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  708. return this;
  709. }
  710. multiplyScalar( s ) {
  711. const te = this.elements;
  712. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  713. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  714. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  715. return this;
  716. }
  717. determinant() {
  718. const te = this.elements;
  719. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  720. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  721. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  722. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  723. }
  724. invert() {
  725. const te = this.elements,
  726. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  727. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  728. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  729. t11 = n33 * n22 - n32 * n23,
  730. t12 = n32 * n13 - n33 * n12,
  731. t13 = n23 * n12 - n22 * n13,
  732. det = n11 * t11 + n21 * t12 + n31 * t13;
  733. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  734. const detInv = 1 / det;
  735. te[ 0 ] = t11 * detInv;
  736. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  737. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  738. te[ 3 ] = t12 * detInv;
  739. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  740. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  741. te[ 6 ] = t13 * detInv;
  742. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  743. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  744. return this;
  745. }
  746. transpose() {
  747. let tmp;
  748. const m = this.elements;
  749. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  750. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  751. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  752. return this;
  753. }
  754. getNormalMatrix( matrix4 ) {
  755. return this.setFromMatrix4( matrix4 ).invert().transpose();
  756. }
  757. transposeIntoArray( r ) {
  758. const m = this.elements;
  759. r[ 0 ] = m[ 0 ];
  760. r[ 1 ] = m[ 3 ];
  761. r[ 2 ] = m[ 6 ];
  762. r[ 3 ] = m[ 1 ];
  763. r[ 4 ] = m[ 4 ];
  764. r[ 5 ] = m[ 7 ];
  765. r[ 6 ] = m[ 2 ];
  766. r[ 7 ] = m[ 5 ];
  767. r[ 8 ] = m[ 8 ];
  768. return this;
  769. }
  770. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  771. const c = Math.cos( rotation );
  772. const s = Math.sin( rotation );
  773. this.set(
  774. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  775. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  776. 0, 0, 1
  777. );
  778. return this;
  779. }
  780. scale( sx, sy ) {
  781. const te = this.elements;
  782. te[ 0 ] *= sx; te[ 3 ] *= sx; te[ 6 ] *= sx;
  783. te[ 1 ] *= sy; te[ 4 ] *= sy; te[ 7 ] *= sy;
  784. return this;
  785. }
  786. rotate( theta ) {
  787. const c = Math.cos( theta );
  788. const s = Math.sin( theta );
  789. const te = this.elements;
  790. const a11 = te[ 0 ], a12 = te[ 3 ], a13 = te[ 6 ];
  791. const a21 = te[ 1 ], a22 = te[ 4 ], a23 = te[ 7 ];
  792. te[ 0 ] = c * a11 + s * a21;
  793. te[ 3 ] = c * a12 + s * a22;
  794. te[ 6 ] = c * a13 + s * a23;
  795. te[ 1 ] = - s * a11 + c * a21;
  796. te[ 4 ] = - s * a12 + c * a22;
  797. te[ 7 ] = - s * a13 + c * a23;
  798. return this;
  799. }
  800. translate( tx, ty ) {
  801. const te = this.elements;
  802. te[ 0 ] += tx * te[ 2 ]; te[ 3 ] += tx * te[ 5 ]; te[ 6 ] += tx * te[ 8 ];
  803. te[ 1 ] += ty * te[ 2 ]; te[ 4 ] += ty * te[ 5 ]; te[ 7 ] += ty * te[ 8 ];
  804. return this;
  805. }
  806. equals( matrix ) {
  807. const te = this.elements;
  808. const me = matrix.elements;
  809. for ( let i = 0; i < 9; i ++ ) {
  810. if ( te[ i ] !== me[ i ] ) return false;
  811. }
  812. return true;
  813. }
  814. fromArray( array, offset = 0 ) {
  815. for ( let i = 0; i < 9; i ++ ) {
  816. this.elements[ i ] = array[ i + offset ];
  817. }
  818. return this;
  819. }
  820. toArray( array = [], offset = 0 ) {
  821. const te = this.elements;
  822. array[ offset ] = te[ 0 ];
  823. array[ offset + 1 ] = te[ 1 ];
  824. array[ offset + 2 ] = te[ 2 ];
  825. array[ offset + 3 ] = te[ 3 ];
  826. array[ offset + 4 ] = te[ 4 ];
  827. array[ offset + 5 ] = te[ 5 ];
  828. array[ offset + 6 ] = te[ 6 ];
  829. array[ offset + 7 ] = te[ 7 ];
  830. array[ offset + 8 ] = te[ 8 ];
  831. return array;
  832. }
  833. clone() {
  834. return new this.constructor().fromArray( this.elements );
  835. }
  836. }
  837. Matrix3.prototype.isMatrix3 = true;
  838. let _canvas;
  839. const ImageUtils = {
  840. getDataURL: function ( image ) {
  841. if ( /^data:/i.test( image.src ) ) {
  842. return image.src;
  843. }
  844. if ( typeof HTMLCanvasElement == 'undefined' ) {
  845. return image.src;
  846. }
  847. let canvas;
  848. if ( image instanceof HTMLCanvasElement ) {
  849. canvas = image;
  850. } else {
  851. if ( _canvas === undefined ) _canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  852. _canvas.width = image.width;
  853. _canvas.height = image.height;
  854. const context = _canvas.getContext( '2d' );
  855. if ( image instanceof ImageData ) {
  856. context.putImageData( image, 0, 0 );
  857. } else {
  858. context.drawImage( image, 0, 0, image.width, image.height );
  859. }
  860. canvas = _canvas;
  861. }
  862. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  863. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  864. return canvas.toDataURL( 'image/jpeg', 0.6 );
  865. } else {
  866. return canvas.toDataURL( 'image/png' );
  867. }
  868. }
  869. };
  870. let textureId = 0;
  871. class Texture extends EventDispatcher {
  872. 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 ) {
  873. super();
  874. Object.defineProperty( this, 'id', { value: textureId ++ } );
  875. this.uuid = MathUtils.generateUUID();
  876. this.name = '';
  877. this.image = image;
  878. this.mipmaps = [];
  879. this.mapping = mapping;
  880. this.wrapS = wrapS;
  881. this.wrapT = wrapT;
  882. this.magFilter = magFilter;
  883. this.minFilter = minFilter;
  884. this.anisotropy = anisotropy;
  885. this.format = format;
  886. this.internalFormat = null;
  887. this.type = type;
  888. this.offset = new Vector2( 0, 0 );
  889. this.repeat = new Vector2( 1, 1 );
  890. this.center = new Vector2( 0, 0 );
  891. this.rotation = 0;
  892. this.matrixAutoUpdate = true;
  893. this.matrix = new Matrix3();
  894. this.generateMipmaps = true;
  895. this.premultiplyAlpha = false;
  896. this.flipY = true;
  897. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  898. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  899. //
  900. // Also changing the encoding after already used by a Material will not automatically make the Material
  901. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  902. this.encoding = encoding;
  903. this.version = 0;
  904. this.onUpdate = null;
  905. }
  906. updateMatrix() {
  907. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  908. }
  909. clone() {
  910. return new this.constructor().copy( this );
  911. }
  912. copy( source ) {
  913. this.name = source.name;
  914. this.image = source.image;
  915. this.mipmaps = source.mipmaps.slice( 0 );
  916. this.mapping = source.mapping;
  917. this.wrapS = source.wrapS;
  918. this.wrapT = source.wrapT;
  919. this.magFilter = source.magFilter;
  920. this.minFilter = source.minFilter;
  921. this.anisotropy = source.anisotropy;
  922. this.format = source.format;
  923. this.internalFormat = source.internalFormat;
  924. this.type = source.type;
  925. this.offset.copy( source.offset );
  926. this.repeat.copy( source.repeat );
  927. this.center.copy( source.center );
  928. this.rotation = source.rotation;
  929. this.matrixAutoUpdate = source.matrixAutoUpdate;
  930. this.matrix.copy( source.matrix );
  931. this.generateMipmaps = source.generateMipmaps;
  932. this.premultiplyAlpha = source.premultiplyAlpha;
  933. this.flipY = source.flipY;
  934. this.unpackAlignment = source.unpackAlignment;
  935. this.encoding = source.encoding;
  936. return this;
  937. }
  938. toJSON( meta ) {
  939. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  940. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  941. return meta.textures[ this.uuid ];
  942. }
  943. const output = {
  944. metadata: {
  945. version: 4.5,
  946. type: 'Texture',
  947. generator: 'Texture.toJSON'
  948. },
  949. uuid: this.uuid,
  950. name: this.name,
  951. mapping: this.mapping,
  952. repeat: [ this.repeat.x, this.repeat.y ],
  953. offset: [ this.offset.x, this.offset.y ],
  954. center: [ this.center.x, this.center.y ],
  955. rotation: this.rotation,
  956. wrap: [ this.wrapS, this.wrapT ],
  957. format: this.format,
  958. type: this.type,
  959. encoding: this.encoding,
  960. minFilter: this.minFilter,
  961. magFilter: this.magFilter,
  962. anisotropy: this.anisotropy,
  963. flipY: this.flipY,
  964. premultiplyAlpha: this.premultiplyAlpha,
  965. unpackAlignment: this.unpackAlignment
  966. };
  967. if ( this.image !== undefined ) {
  968. // TODO: Move to THREE.Image
  969. const image = this.image;
  970. if ( image.uuid === undefined ) {
  971. image.uuid = MathUtils.generateUUID(); // UGH
  972. }
  973. if ( ! isRootObject && meta.images[ image.uuid ] === undefined ) {
  974. let url;
  975. if ( Array.isArray( image ) ) {
  976. // process array of images e.g. CubeTexture
  977. url = [];
  978. for ( let i = 0, l = image.length; i < l; i ++ ) {
  979. // check cube texture with data textures
  980. if ( image[ i ].isDataTexture ) {
  981. url.push( serializeImage( image[ i ].image ) );
  982. } else {
  983. url.push( serializeImage( image[ i ] ) );
  984. }
  985. }
  986. } else {
  987. // process single image
  988. url = serializeImage( image );
  989. }
  990. meta.images[ image.uuid ] = {
  991. uuid: image.uuid,
  992. url: url
  993. };
  994. }
  995. output.image = image.uuid;
  996. }
  997. if ( ! isRootObject ) {
  998. meta.textures[ this.uuid ] = output;
  999. }
  1000. return output;
  1001. }
  1002. dispose() {
  1003. this.dispatchEvent( { type: 'dispose' } );
  1004. }
  1005. transformUv( uv ) {
  1006. if ( this.mapping !== UVMapping ) return uv;
  1007. uv.applyMatrix3( this.matrix );
  1008. if ( uv.x < 0 || uv.x > 1 ) {
  1009. switch ( this.wrapS ) {
  1010. case RepeatWrapping:
  1011. uv.x = uv.x - Math.floor( uv.x );
  1012. break;
  1013. case ClampToEdgeWrapping:
  1014. uv.x = uv.x < 0 ? 0 : 1;
  1015. break;
  1016. case MirroredRepeatWrapping:
  1017. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1018. uv.x = Math.ceil( uv.x ) - uv.x;
  1019. } else {
  1020. uv.x = uv.x - Math.floor( uv.x );
  1021. }
  1022. break;
  1023. }
  1024. }
  1025. if ( uv.y < 0 || uv.y > 1 ) {
  1026. switch ( this.wrapT ) {
  1027. case RepeatWrapping:
  1028. uv.y = uv.y - Math.floor( uv.y );
  1029. break;
  1030. case ClampToEdgeWrapping:
  1031. uv.y = uv.y < 0 ? 0 : 1;
  1032. break;
  1033. case MirroredRepeatWrapping:
  1034. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1035. uv.y = Math.ceil( uv.y ) - uv.y;
  1036. } else {
  1037. uv.y = uv.y - Math.floor( uv.y );
  1038. }
  1039. break;
  1040. }
  1041. }
  1042. if ( this.flipY ) {
  1043. uv.y = 1 - uv.y;
  1044. }
  1045. return uv;
  1046. }
  1047. set needsUpdate( value ) {
  1048. if ( value === true ) this.version ++;
  1049. }
  1050. }
  1051. Texture.DEFAULT_IMAGE = undefined;
  1052. Texture.DEFAULT_MAPPING = UVMapping;
  1053. Texture.prototype.isTexture = true;
  1054. function serializeImage( image ) {
  1055. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1056. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1057. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1058. // default images
  1059. return ImageUtils.getDataURL( image );
  1060. } else {
  1061. if ( image.data ) {
  1062. // images of DataTexture
  1063. return {
  1064. data: Array.prototype.slice.call( image.data ),
  1065. width: image.width,
  1066. height: image.height,
  1067. type: image.data.constructor.name
  1068. };
  1069. } else {
  1070. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1071. return {};
  1072. }
  1073. }
  1074. }
  1075. class Vector4 {
  1076. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1077. this.x = x;
  1078. this.y = y;
  1079. this.z = z;
  1080. this.w = w;
  1081. }
  1082. get width() {
  1083. return this.z;
  1084. }
  1085. set width( value ) {
  1086. this.z = value;
  1087. }
  1088. get height() {
  1089. return this.w;
  1090. }
  1091. set height( value ) {
  1092. this.w = value;
  1093. }
  1094. set( x, y, z, w ) {
  1095. this.x = x;
  1096. this.y = y;
  1097. this.z = z;
  1098. this.w = w;
  1099. return this;
  1100. }
  1101. setScalar( scalar ) {
  1102. this.x = scalar;
  1103. this.y = scalar;
  1104. this.z = scalar;
  1105. this.w = scalar;
  1106. return this;
  1107. }
  1108. setX( x ) {
  1109. this.x = x;
  1110. return this;
  1111. }
  1112. setY( y ) {
  1113. this.y = y;
  1114. return this;
  1115. }
  1116. setZ( z ) {
  1117. this.z = z;
  1118. return this;
  1119. }
  1120. setW( w ) {
  1121. this.w = w;
  1122. return this;
  1123. }
  1124. setComponent( index, value ) {
  1125. switch ( index ) {
  1126. case 0: this.x = value; break;
  1127. case 1: this.y = value; break;
  1128. case 2: this.z = value; break;
  1129. case 3: this.w = value; break;
  1130. default: throw new Error( 'index is out of range: ' + index );
  1131. }
  1132. return this;
  1133. }
  1134. getComponent( index ) {
  1135. switch ( index ) {
  1136. case 0: return this.x;
  1137. case 1: return this.y;
  1138. case 2: return this.z;
  1139. case 3: return this.w;
  1140. default: throw new Error( 'index is out of range: ' + index );
  1141. }
  1142. }
  1143. clone() {
  1144. return new this.constructor( this.x, this.y, this.z, this.w );
  1145. }
  1146. copy( v ) {
  1147. this.x = v.x;
  1148. this.y = v.y;
  1149. this.z = v.z;
  1150. this.w = ( v.w !== undefined ) ? v.w : 1;
  1151. return this;
  1152. }
  1153. add( v, w ) {
  1154. if ( w !== undefined ) {
  1155. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1156. return this.addVectors( v, w );
  1157. }
  1158. this.x += v.x;
  1159. this.y += v.y;
  1160. this.z += v.z;
  1161. this.w += v.w;
  1162. return this;
  1163. }
  1164. addScalar( s ) {
  1165. this.x += s;
  1166. this.y += s;
  1167. this.z += s;
  1168. this.w += s;
  1169. return this;
  1170. }
  1171. addVectors( a, b ) {
  1172. this.x = a.x + b.x;
  1173. this.y = a.y + b.y;
  1174. this.z = a.z + b.z;
  1175. this.w = a.w + b.w;
  1176. return this;
  1177. }
  1178. addScaledVector( v, s ) {
  1179. this.x += v.x * s;
  1180. this.y += v.y * s;
  1181. this.z += v.z * s;
  1182. this.w += v.w * s;
  1183. return this;
  1184. }
  1185. sub( v, w ) {
  1186. if ( w !== undefined ) {
  1187. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1188. return this.subVectors( v, w );
  1189. }
  1190. this.x -= v.x;
  1191. this.y -= v.y;
  1192. this.z -= v.z;
  1193. this.w -= v.w;
  1194. return this;
  1195. }
  1196. subScalar( s ) {
  1197. this.x -= s;
  1198. this.y -= s;
  1199. this.z -= s;
  1200. this.w -= s;
  1201. return this;
  1202. }
  1203. subVectors( a, b ) {
  1204. this.x = a.x - b.x;
  1205. this.y = a.y - b.y;
  1206. this.z = a.z - b.z;
  1207. this.w = a.w - b.w;
  1208. return this;
  1209. }
  1210. multiply( v ) {
  1211. this.x *= v.x;
  1212. this.y *= v.y;
  1213. this.z *= v.z;
  1214. this.w *= v.w;
  1215. return this;
  1216. }
  1217. multiplyScalar( scalar ) {
  1218. this.x *= scalar;
  1219. this.y *= scalar;
  1220. this.z *= scalar;
  1221. this.w *= scalar;
  1222. return this;
  1223. }
  1224. applyMatrix4( m ) {
  1225. const x = this.x, y = this.y, z = this.z, w = this.w;
  1226. const e = m.elements;
  1227. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1228. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1229. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1230. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1231. return this;
  1232. }
  1233. divideScalar( scalar ) {
  1234. return this.multiplyScalar( 1 / scalar );
  1235. }
  1236. setAxisAngleFromQuaternion( q ) {
  1237. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1238. // q is assumed to be normalized
  1239. this.w = 2 * Math.acos( q.w );
  1240. const s = Math.sqrt( 1 - q.w * q.w );
  1241. if ( s < 0.0001 ) {
  1242. this.x = 1;
  1243. this.y = 0;
  1244. this.z = 0;
  1245. } else {
  1246. this.x = q.x / s;
  1247. this.y = q.y / s;
  1248. this.z = q.z / s;
  1249. }
  1250. return this;
  1251. }
  1252. setAxisAngleFromRotationMatrix( m ) {
  1253. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1254. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1255. let angle, x, y, z; // variables for result
  1256. const epsilon = 0.01, // margin to allow for rounding errors
  1257. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1258. te = m.elements,
  1259. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1260. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1261. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1262. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1263. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1264. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1265. // singularity found
  1266. // first check for identity matrix which must have +1 for all terms
  1267. // in leading diagonal and zero in other terms
  1268. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1269. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1270. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1271. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1272. // this singularity is identity matrix so angle = 0
  1273. this.set( 1, 0, 0, 0 );
  1274. return this; // zero angle, arbitrary axis
  1275. }
  1276. // otherwise this singularity is angle = 180
  1277. angle = Math.PI;
  1278. const xx = ( m11 + 1 ) / 2;
  1279. const yy = ( m22 + 1 ) / 2;
  1280. const zz = ( m33 + 1 ) / 2;
  1281. const xy = ( m12 + m21 ) / 4;
  1282. const xz = ( m13 + m31 ) / 4;
  1283. const yz = ( m23 + m32 ) / 4;
  1284. if ( ( xx > yy ) && ( xx > zz ) ) {
  1285. // m11 is the largest diagonal term
  1286. if ( xx < epsilon ) {
  1287. x = 0;
  1288. y = 0.707106781;
  1289. z = 0.707106781;
  1290. } else {
  1291. x = Math.sqrt( xx );
  1292. y = xy / x;
  1293. z = xz / x;
  1294. }
  1295. } else if ( yy > zz ) {
  1296. // m22 is the largest diagonal term
  1297. if ( yy < epsilon ) {
  1298. x = 0.707106781;
  1299. y = 0;
  1300. z = 0.707106781;
  1301. } else {
  1302. y = Math.sqrt( yy );
  1303. x = xy / y;
  1304. z = yz / y;
  1305. }
  1306. } else {
  1307. // m33 is the largest diagonal term so base result on this
  1308. if ( zz < epsilon ) {
  1309. x = 0.707106781;
  1310. y = 0.707106781;
  1311. z = 0;
  1312. } else {
  1313. z = Math.sqrt( zz );
  1314. x = xz / z;
  1315. y = yz / z;
  1316. }
  1317. }
  1318. this.set( x, y, z, angle );
  1319. return this; // return 180 deg rotation
  1320. }
  1321. // as we have reached here there are no singularities so we can handle normally
  1322. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1323. ( m13 - m31 ) * ( m13 - m31 ) +
  1324. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1325. if ( Math.abs( s ) < 0.001 ) s = 1;
  1326. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1327. // caught by singularity test above, but I've left it in just in case
  1328. this.x = ( m32 - m23 ) / s;
  1329. this.y = ( m13 - m31 ) / s;
  1330. this.z = ( m21 - m12 ) / s;
  1331. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1332. return this;
  1333. }
  1334. min( v ) {
  1335. this.x = Math.min( this.x, v.x );
  1336. this.y = Math.min( this.y, v.y );
  1337. this.z = Math.min( this.z, v.z );
  1338. this.w = Math.min( this.w, v.w );
  1339. return this;
  1340. }
  1341. max( v ) {
  1342. this.x = Math.max( this.x, v.x );
  1343. this.y = Math.max( this.y, v.y );
  1344. this.z = Math.max( this.z, v.z );
  1345. this.w = Math.max( this.w, v.w );
  1346. return this;
  1347. }
  1348. clamp( min, max ) {
  1349. // assumes min < max, componentwise
  1350. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1351. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1352. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1353. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1354. return this;
  1355. }
  1356. clampScalar( minVal, maxVal ) {
  1357. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1358. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1359. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1360. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  1361. return this;
  1362. }
  1363. clampLength( min, max ) {
  1364. const length = this.length();
  1365. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1366. }
  1367. floor() {
  1368. this.x = Math.floor( this.x );
  1369. this.y = Math.floor( this.y );
  1370. this.z = Math.floor( this.z );
  1371. this.w = Math.floor( this.w );
  1372. return this;
  1373. }
  1374. ceil() {
  1375. this.x = Math.ceil( this.x );
  1376. this.y = Math.ceil( this.y );
  1377. this.z = Math.ceil( this.z );
  1378. this.w = Math.ceil( this.w );
  1379. return this;
  1380. }
  1381. round() {
  1382. this.x = Math.round( this.x );
  1383. this.y = Math.round( this.y );
  1384. this.z = Math.round( this.z );
  1385. this.w = Math.round( this.w );
  1386. return this;
  1387. }
  1388. roundToZero() {
  1389. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1390. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1391. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1392. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1393. return this;
  1394. }
  1395. negate() {
  1396. this.x = - this.x;
  1397. this.y = - this.y;
  1398. this.z = - this.z;
  1399. this.w = - this.w;
  1400. return this;
  1401. }
  1402. dot( v ) {
  1403. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1404. }
  1405. lengthSq() {
  1406. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1407. }
  1408. length() {
  1409. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1410. }
  1411. manhattanLength() {
  1412. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1413. }
  1414. normalize() {
  1415. return this.divideScalar( this.length() || 1 );
  1416. }
  1417. setLength( length ) {
  1418. return this.normalize().multiplyScalar( length );
  1419. }
  1420. lerp( v, alpha ) {
  1421. this.x += ( v.x - this.x ) * alpha;
  1422. this.y += ( v.y - this.y ) * alpha;
  1423. this.z += ( v.z - this.z ) * alpha;
  1424. this.w += ( v.w - this.w ) * alpha;
  1425. return this;
  1426. }
  1427. lerpVectors( v1, v2, alpha ) {
  1428. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1429. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1430. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1431. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  1432. return this;
  1433. }
  1434. equals( v ) {
  1435. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1436. }
  1437. fromArray( array, offset = 0 ) {
  1438. this.x = array[ offset ];
  1439. this.y = array[ offset + 1 ];
  1440. this.z = array[ offset + 2 ];
  1441. this.w = array[ offset + 3 ];
  1442. return this;
  1443. }
  1444. toArray( array = [], offset = 0 ) {
  1445. array[ offset ] = this.x;
  1446. array[ offset + 1 ] = this.y;
  1447. array[ offset + 2 ] = this.z;
  1448. array[ offset + 3 ] = this.w;
  1449. return array;
  1450. }
  1451. fromBufferAttribute( attribute, index, offset ) {
  1452. if ( offset !== undefined ) {
  1453. console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' );
  1454. }
  1455. this.x = attribute.getX( index );
  1456. this.y = attribute.getY( index );
  1457. this.z = attribute.getZ( index );
  1458. this.w = attribute.getW( index );
  1459. return this;
  1460. }
  1461. random() {
  1462. this.x = Math.random();
  1463. this.y = Math.random();
  1464. this.z = Math.random();
  1465. this.w = Math.random();
  1466. return this;
  1467. }
  1468. }
  1469. Vector4.prototype.isVector4 = true;
  1470. /*
  1471. In options, we can specify:
  1472. * Texture parameters for an auto-generated target texture
  1473. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1474. */
  1475. class WebGLRenderTarget extends EventDispatcher {
  1476. constructor( width, height, options ) {
  1477. super();
  1478. this.width = width;
  1479. this.height = height;
  1480. this.depth = 1;
  1481. this.scissor = new Vector4( 0, 0, width, height );
  1482. this.scissorTest = false;
  1483. this.viewport = new Vector4( 0, 0, width, height );
  1484. options = options || {};
  1485. this.texture = new Texture( undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  1486. this.texture.image = {};
  1487. this.texture.image.width = width;
  1488. this.texture.image.height = height;
  1489. this.texture.image.depth = 1;
  1490. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  1491. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  1492. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  1493. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  1494. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  1495. }
  1496. setTexture( texture ) {
  1497. texture.image = {
  1498. width: this.width,
  1499. height: this.height,
  1500. depth: this.depth
  1501. };
  1502. this.texture = texture;
  1503. }
  1504. setSize( width, height, depth = 1 ) {
  1505. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1506. this.width = width;
  1507. this.height = height;
  1508. this.depth = depth;
  1509. this.texture.image.width = width;
  1510. this.texture.image.height = height;
  1511. this.texture.image.depth = depth;
  1512. this.dispose();
  1513. }
  1514. this.viewport.set( 0, 0, width, height );
  1515. this.scissor.set( 0, 0, width, height );
  1516. }
  1517. clone() {
  1518. return new this.constructor().copy( this );
  1519. }
  1520. copy( source ) {
  1521. this.width = source.width;
  1522. this.height = source.height;
  1523. this.depth = source.depth;
  1524. this.viewport.copy( source.viewport );
  1525. this.texture = source.texture.clone();
  1526. this.depthBuffer = source.depthBuffer;
  1527. this.stencilBuffer = source.stencilBuffer;
  1528. this.depthTexture = source.depthTexture;
  1529. return this;
  1530. }
  1531. dispose() {
  1532. this.dispatchEvent( { type: 'dispose' } );
  1533. }
  1534. }
  1535. WebGLRenderTarget.prototype.isWebGLRenderTarget = true;
  1536. class WebGLMultisampleRenderTarget extends WebGLRenderTarget {
  1537. constructor( width, height, options ) {
  1538. super( width, height, options );
  1539. this.samples = 4;
  1540. }
  1541. copy( source ) {
  1542. super.copy.call( this, source );
  1543. this.samples = source.samples;
  1544. return this;
  1545. }
  1546. }
  1547. WebGLMultisampleRenderTarget.prototype.isWebGLMultisampleRenderTarget = true;
  1548. class Quaternion {
  1549. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1550. this._x = x;
  1551. this._y = y;
  1552. this._z = z;
  1553. this._w = w;
  1554. }
  1555. static slerp( qa, qb, qm, t ) {
  1556. return qm.copy( qa ).slerp( qb, t );
  1557. }
  1558. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1559. // fuzz-free, array-based Quaternion SLERP operation
  1560. let x0 = src0[ srcOffset0 + 0 ],
  1561. y0 = src0[ srcOffset0 + 1 ],
  1562. z0 = src0[ srcOffset0 + 2 ],
  1563. w0 = src0[ srcOffset0 + 3 ];
  1564. const x1 = src1[ srcOffset1 + 0 ],
  1565. y1 = src1[ srcOffset1 + 1 ],
  1566. z1 = src1[ srcOffset1 + 2 ],
  1567. w1 = src1[ srcOffset1 + 3 ];
  1568. if ( t === 0 ) {
  1569. dst[ dstOffset + 0 ] = x0;
  1570. dst[ dstOffset + 1 ] = y0;
  1571. dst[ dstOffset + 2 ] = z0;
  1572. dst[ dstOffset + 3 ] = w0;
  1573. return;
  1574. }
  1575. if ( t === 1 ) {
  1576. dst[ dstOffset + 0 ] = x1;
  1577. dst[ dstOffset + 1 ] = y1;
  1578. dst[ dstOffset + 2 ] = z1;
  1579. dst[ dstOffset + 3 ] = w1;
  1580. return;
  1581. }
  1582. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1583. let s = 1 - t;
  1584. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1585. dir = ( cos >= 0 ? 1 : - 1 ),
  1586. sqrSin = 1 - cos * cos;
  1587. // Skip the Slerp for tiny steps to avoid numeric problems:
  1588. if ( sqrSin > Number.EPSILON ) {
  1589. const sin = Math.sqrt( sqrSin ),
  1590. len = Math.atan2( sin, cos * dir );
  1591. s = Math.sin( s * len ) / sin;
  1592. t = Math.sin( t * len ) / sin;
  1593. }
  1594. const tDir = t * dir;
  1595. x0 = x0 * s + x1 * tDir;
  1596. y0 = y0 * s + y1 * tDir;
  1597. z0 = z0 * s + z1 * tDir;
  1598. w0 = w0 * s + w1 * tDir;
  1599. // Normalize in case we just did a lerp:
  1600. if ( s === 1 - t ) {
  1601. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  1602. x0 *= f;
  1603. y0 *= f;
  1604. z0 *= f;
  1605. w0 *= f;
  1606. }
  1607. }
  1608. dst[ dstOffset ] = x0;
  1609. dst[ dstOffset + 1 ] = y0;
  1610. dst[ dstOffset + 2 ] = z0;
  1611. dst[ dstOffset + 3 ] = w0;
  1612. }
  1613. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  1614. const x0 = src0[ srcOffset0 ];
  1615. const y0 = src0[ srcOffset0 + 1 ];
  1616. const z0 = src0[ srcOffset0 + 2 ];
  1617. const w0 = src0[ srcOffset0 + 3 ];
  1618. const x1 = src1[ srcOffset1 ];
  1619. const y1 = src1[ srcOffset1 + 1 ];
  1620. const z1 = src1[ srcOffset1 + 2 ];
  1621. const w1 = src1[ srcOffset1 + 3 ];
  1622. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  1623. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  1624. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  1625. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  1626. return dst;
  1627. }
  1628. get x() {
  1629. return this._x;
  1630. }
  1631. set x( value ) {
  1632. this._x = value;
  1633. this._onChangeCallback();
  1634. }
  1635. get y() {
  1636. return this._y;
  1637. }
  1638. set y( value ) {
  1639. this._y = value;
  1640. this._onChangeCallback();
  1641. }
  1642. get z() {
  1643. return this._z;
  1644. }
  1645. set z( value ) {
  1646. this._z = value;
  1647. this._onChangeCallback();
  1648. }
  1649. get w() {
  1650. return this._w;
  1651. }
  1652. set w( value ) {
  1653. this._w = value;
  1654. this._onChangeCallback();
  1655. }
  1656. set( x, y, z, w ) {
  1657. this._x = x;
  1658. this._y = y;
  1659. this._z = z;
  1660. this._w = w;
  1661. this._onChangeCallback();
  1662. return this;
  1663. }
  1664. clone() {
  1665. return new this.constructor( this._x, this._y, this._z, this._w );
  1666. }
  1667. copy( quaternion ) {
  1668. this._x = quaternion.x;
  1669. this._y = quaternion.y;
  1670. this._z = quaternion.z;
  1671. this._w = quaternion.w;
  1672. this._onChangeCallback();
  1673. return this;
  1674. }
  1675. setFromEuler( euler, update ) {
  1676. if ( ! ( euler && euler.isEuler ) ) {
  1677. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  1678. }
  1679. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  1680. // http://www.mathworks.com/matlabcentral/fileexchange/
  1681. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1682. // content/SpinCalc.m
  1683. const cos = Math.cos;
  1684. const sin = Math.sin;
  1685. const c1 = cos( x / 2 );
  1686. const c2 = cos( y / 2 );
  1687. const c3 = cos( z / 2 );
  1688. const s1 = sin( x / 2 );
  1689. const s2 = sin( y / 2 );
  1690. const s3 = sin( z / 2 );
  1691. switch ( order ) {
  1692. case 'XYZ':
  1693. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1694. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1695. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1696. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1697. break;
  1698. case 'YXZ':
  1699. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1700. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1701. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1702. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1703. break;
  1704. case 'ZXY':
  1705. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1706. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1707. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1708. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1709. break;
  1710. case 'ZYX':
  1711. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1712. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1713. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1714. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1715. break;
  1716. case 'YZX':
  1717. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1718. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1719. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1720. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1721. break;
  1722. case 'XZY':
  1723. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1724. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1725. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1726. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1727. break;
  1728. default:
  1729. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  1730. }
  1731. if ( update !== false ) this._onChangeCallback();
  1732. return this;
  1733. }
  1734. setFromAxisAngle( axis, angle ) {
  1735. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  1736. // assumes axis is normalized
  1737. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  1738. this._x = axis.x * s;
  1739. this._y = axis.y * s;
  1740. this._z = axis.z * s;
  1741. this._w = Math.cos( halfAngle );
  1742. this._onChangeCallback();
  1743. return this;
  1744. }
  1745. setFromRotationMatrix( m ) {
  1746. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  1747. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1748. const te = m.elements,
  1749. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1750. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1751. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  1752. trace = m11 + m22 + m33;
  1753. if ( trace > 0 ) {
  1754. const s = 0.5 / Math.sqrt( trace + 1.0 );
  1755. this._w = 0.25 / s;
  1756. this._x = ( m32 - m23 ) * s;
  1757. this._y = ( m13 - m31 ) * s;
  1758. this._z = ( m21 - m12 ) * s;
  1759. } else if ( m11 > m22 && m11 > m33 ) {
  1760. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  1761. this._w = ( m32 - m23 ) / s;
  1762. this._x = 0.25 * s;
  1763. this._y = ( m12 + m21 ) / s;
  1764. this._z = ( m13 + m31 ) / s;
  1765. } else if ( m22 > m33 ) {
  1766. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  1767. this._w = ( m13 - m31 ) / s;
  1768. this._x = ( m12 + m21 ) / s;
  1769. this._y = 0.25 * s;
  1770. this._z = ( m23 + m32 ) / s;
  1771. } else {
  1772. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  1773. this._w = ( m21 - m12 ) / s;
  1774. this._x = ( m13 + m31 ) / s;
  1775. this._y = ( m23 + m32 ) / s;
  1776. this._z = 0.25 * s;
  1777. }
  1778. this._onChangeCallback();
  1779. return this;
  1780. }
  1781. setFromUnitVectors( vFrom, vTo ) {
  1782. // assumes direction vectors vFrom and vTo are normalized
  1783. const EPS = 0.000001;
  1784. let r = vFrom.dot( vTo ) + 1;
  1785. if ( r < EPS ) {
  1786. r = 0;
  1787. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  1788. this._x = - vFrom.y;
  1789. this._y = vFrom.x;
  1790. this._z = 0;
  1791. this._w = r;
  1792. } else {
  1793. this._x = 0;
  1794. this._y = - vFrom.z;
  1795. this._z = vFrom.y;
  1796. this._w = r;
  1797. }
  1798. } else {
  1799. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  1800. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  1801. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  1802. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  1803. this._w = r;
  1804. }
  1805. return this.normalize();
  1806. }
  1807. angleTo( q ) {
  1808. return 2 * Math.acos( Math.abs( MathUtils.clamp( this.dot( q ), - 1, 1 ) ) );
  1809. }
  1810. rotateTowards( q, step ) {
  1811. const angle = this.angleTo( q );
  1812. if ( angle === 0 ) return this;
  1813. const t = Math.min( 1, step / angle );
  1814. this.slerp( q, t );
  1815. return this;
  1816. }
  1817. identity() {
  1818. return this.set( 0, 0, 0, 1 );
  1819. }
  1820. invert() {
  1821. // quaternion is assumed to have unit length
  1822. return this.conjugate();
  1823. }
  1824. conjugate() {
  1825. this._x *= - 1;
  1826. this._y *= - 1;
  1827. this._z *= - 1;
  1828. this._onChangeCallback();
  1829. return this;
  1830. }
  1831. dot( v ) {
  1832. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  1833. }
  1834. lengthSq() {
  1835. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  1836. }
  1837. length() {
  1838. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  1839. }
  1840. normalize() {
  1841. let l = this.length();
  1842. if ( l === 0 ) {
  1843. this._x = 0;
  1844. this._y = 0;
  1845. this._z = 0;
  1846. this._w = 1;
  1847. } else {
  1848. l = 1 / l;
  1849. this._x = this._x * l;
  1850. this._y = this._y * l;
  1851. this._z = this._z * l;
  1852. this._w = this._w * l;
  1853. }
  1854. this._onChangeCallback();
  1855. return this;
  1856. }
  1857. multiply( q, p ) {
  1858. if ( p !== undefined ) {
  1859. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  1860. return this.multiplyQuaternions( q, p );
  1861. }
  1862. return this.multiplyQuaternions( this, q );
  1863. }
  1864. premultiply( q ) {
  1865. return this.multiplyQuaternions( q, this );
  1866. }
  1867. multiplyQuaternions( a, b ) {
  1868. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  1869. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  1870. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  1871. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  1872. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  1873. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  1874. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  1875. this._onChangeCallback();
  1876. return this;
  1877. }
  1878. slerp( qb, t ) {
  1879. if ( t === 0 ) return this;
  1880. if ( t === 1 ) return this.copy( qb );
  1881. const x = this._x, y = this._y, z = this._z, w = this._w;
  1882. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  1883. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  1884. if ( cosHalfTheta < 0 ) {
  1885. this._w = - qb._w;
  1886. this._x = - qb._x;
  1887. this._y = - qb._y;
  1888. this._z = - qb._z;
  1889. cosHalfTheta = - cosHalfTheta;
  1890. } else {
  1891. this.copy( qb );
  1892. }
  1893. if ( cosHalfTheta >= 1.0 ) {
  1894. this._w = w;
  1895. this._x = x;
  1896. this._y = y;
  1897. this._z = z;
  1898. return this;
  1899. }
  1900. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  1901. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  1902. const s = 1 - t;
  1903. this._w = s * w + t * this._w;
  1904. this._x = s * x + t * this._x;
  1905. this._y = s * y + t * this._y;
  1906. this._z = s * z + t * this._z;
  1907. this.normalize();
  1908. this._onChangeCallback();
  1909. return this;
  1910. }
  1911. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  1912. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  1913. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  1914. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  1915. this._w = ( w * ratioA + this._w * ratioB );
  1916. this._x = ( x * ratioA + this._x * ratioB );
  1917. this._y = ( y * ratioA + this._y * ratioB );
  1918. this._z = ( z * ratioA + this._z * ratioB );
  1919. this._onChangeCallback();
  1920. return this;
  1921. }
  1922. equals( quaternion ) {
  1923. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  1924. }
  1925. fromArray( array, offset = 0 ) {
  1926. this._x = array[ offset ];
  1927. this._y = array[ offset + 1 ];
  1928. this._z = array[ offset + 2 ];
  1929. this._w = array[ offset + 3 ];
  1930. this._onChangeCallback();
  1931. return this;
  1932. }
  1933. toArray( array = [], offset = 0 ) {
  1934. array[ offset ] = this._x;
  1935. array[ offset + 1 ] = this._y;
  1936. array[ offset + 2 ] = this._z;
  1937. array[ offset + 3 ] = this._w;
  1938. return array;
  1939. }
  1940. fromBufferAttribute( attribute, index ) {
  1941. this._x = attribute.getX( index );
  1942. this._y = attribute.getY( index );
  1943. this._z = attribute.getZ( index );
  1944. this._w = attribute.getW( index );
  1945. return this;
  1946. }
  1947. _onChange( callback ) {
  1948. this._onChangeCallback = callback;
  1949. return this;
  1950. }
  1951. _onChangeCallback() {}
  1952. }
  1953. Quaternion.prototype.isQuaternion = true;
  1954. class Vector3 {
  1955. constructor( x = 0, y = 0, z = 0 ) {
  1956. this.x = x;
  1957. this.y = y;
  1958. this.z = z;
  1959. }
  1960. set( x, y, z ) {
  1961. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  1962. this.x = x;
  1963. this.y = y;
  1964. this.z = z;
  1965. return this;
  1966. }
  1967. setScalar( scalar ) {
  1968. this.x = scalar;
  1969. this.y = scalar;
  1970. this.z = scalar;
  1971. return this;
  1972. }
  1973. setX( x ) {
  1974. this.x = x;
  1975. return this;
  1976. }
  1977. setY( y ) {
  1978. this.y = y;
  1979. return this;
  1980. }
  1981. setZ( z ) {
  1982. this.z = z;
  1983. return this;
  1984. }
  1985. setComponent( index, value ) {
  1986. switch ( index ) {
  1987. case 0: this.x = value; break;
  1988. case 1: this.y = value; break;
  1989. case 2: this.z = value; break;
  1990. default: throw new Error( 'index is out of range: ' + index );
  1991. }
  1992. return this;
  1993. }
  1994. getComponent( index ) {
  1995. switch ( index ) {
  1996. case 0: return this.x;
  1997. case 1: return this.y;
  1998. case 2: return this.z;
  1999. default: throw new Error( 'index is out of range: ' + index );
  2000. }
  2001. }
  2002. clone() {
  2003. return new this.constructor( this.x, this.y, this.z );
  2004. }
  2005. copy( v ) {
  2006. this.x = v.x;
  2007. this.y = v.y;
  2008. this.z = v.z;
  2009. return this;
  2010. }
  2011. add( v, w ) {
  2012. if ( w !== undefined ) {
  2013. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  2014. return this.addVectors( v, w );
  2015. }
  2016. this.x += v.x;
  2017. this.y += v.y;
  2018. this.z += v.z;
  2019. return this;
  2020. }
  2021. addScalar( s ) {
  2022. this.x += s;
  2023. this.y += s;
  2024. this.z += s;
  2025. return this;
  2026. }
  2027. addVectors( a, b ) {
  2028. this.x = a.x + b.x;
  2029. this.y = a.y + b.y;
  2030. this.z = a.z + b.z;
  2031. return this;
  2032. }
  2033. addScaledVector( v, s ) {
  2034. this.x += v.x * s;
  2035. this.y += v.y * s;
  2036. this.z += v.z * s;
  2037. return this;
  2038. }
  2039. sub( v, w ) {
  2040. if ( w !== undefined ) {
  2041. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  2042. return this.subVectors( v, w );
  2043. }
  2044. this.x -= v.x;
  2045. this.y -= v.y;
  2046. this.z -= v.z;
  2047. return this;
  2048. }
  2049. subScalar( s ) {
  2050. this.x -= s;
  2051. this.y -= s;
  2052. this.z -= s;
  2053. return this;
  2054. }
  2055. subVectors( a, b ) {
  2056. this.x = a.x - b.x;
  2057. this.y = a.y - b.y;
  2058. this.z = a.z - b.z;
  2059. return this;
  2060. }
  2061. multiply( v, w ) {
  2062. if ( w !== undefined ) {
  2063. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  2064. return this.multiplyVectors( v, w );
  2065. }
  2066. this.x *= v.x;
  2067. this.y *= v.y;
  2068. this.z *= v.z;
  2069. return this;
  2070. }
  2071. multiplyScalar( scalar ) {
  2072. this.x *= scalar;
  2073. this.y *= scalar;
  2074. this.z *= scalar;
  2075. return this;
  2076. }
  2077. multiplyVectors( a, b ) {
  2078. this.x = a.x * b.x;
  2079. this.y = a.y * b.y;
  2080. this.z = a.z * b.z;
  2081. return this;
  2082. }
  2083. applyEuler( euler ) {
  2084. if ( ! ( euler && euler.isEuler ) ) {
  2085. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  2086. }
  2087. return this.applyQuaternion( _quaternion.setFromEuler( euler ) );
  2088. }
  2089. applyAxisAngle( axis, angle ) {
  2090. return this.applyQuaternion( _quaternion.setFromAxisAngle( axis, angle ) );
  2091. }
  2092. applyMatrix3( m ) {
  2093. const x = this.x, y = this.y, z = this.z;
  2094. const e = m.elements;
  2095. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2096. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2097. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2098. return this;
  2099. }
  2100. applyNormalMatrix( m ) {
  2101. return this.applyMatrix3( m ).normalize();
  2102. }
  2103. applyMatrix4( m ) {
  2104. const x = this.x, y = this.y, z = this.z;
  2105. const e = m.elements;
  2106. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2107. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2108. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2109. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2110. return this;
  2111. }
  2112. applyQuaternion( q ) {
  2113. const x = this.x, y = this.y, z = this.z;
  2114. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2115. // calculate quat * vector
  2116. const ix = qw * x + qy * z - qz * y;
  2117. const iy = qw * y + qz * x - qx * z;
  2118. const iz = qw * z + qx * y - qy * x;
  2119. const iw = - qx * x - qy * y - qz * z;
  2120. // calculate result * inverse quat
  2121. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  2122. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  2123. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  2124. return this;
  2125. }
  2126. project( camera ) {
  2127. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2128. }
  2129. unproject( camera ) {
  2130. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2131. }
  2132. transformDirection( m ) {
  2133. // input: THREE.Matrix4 affine matrix
  2134. // vector interpreted as a direction
  2135. const x = this.x, y = this.y, z = this.z;
  2136. const e = m.elements;
  2137. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2138. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2139. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2140. return this.normalize();
  2141. }
  2142. divide( v ) {
  2143. this.x /= v.x;
  2144. this.y /= v.y;
  2145. this.z /= v.z;
  2146. return this;
  2147. }
  2148. divideScalar( scalar ) {
  2149. return this.multiplyScalar( 1 / scalar );
  2150. }
  2151. min( v ) {
  2152. this.x = Math.min( this.x, v.x );
  2153. this.y = Math.min( this.y, v.y );
  2154. this.z = Math.min( this.z, v.z );
  2155. return this;
  2156. }
  2157. max( v ) {
  2158. this.x = Math.max( this.x, v.x );
  2159. this.y = Math.max( this.y, v.y );
  2160. this.z = Math.max( this.z, v.z );
  2161. return this;
  2162. }
  2163. clamp( min, max ) {
  2164. // assumes min < max, componentwise
  2165. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2166. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2167. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2168. return this;
  2169. }
  2170. clampScalar( minVal, maxVal ) {
  2171. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2172. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2173. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2174. return this;
  2175. }
  2176. clampLength( min, max ) {
  2177. const length = this.length();
  2178. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2179. }
  2180. floor() {
  2181. this.x = Math.floor( this.x );
  2182. this.y = Math.floor( this.y );
  2183. this.z = Math.floor( this.z );
  2184. return this;
  2185. }
  2186. ceil() {
  2187. this.x = Math.ceil( this.x );
  2188. this.y = Math.ceil( this.y );
  2189. this.z = Math.ceil( this.z );
  2190. return this;
  2191. }
  2192. round() {
  2193. this.x = Math.round( this.x );
  2194. this.y = Math.round( this.y );
  2195. this.z = Math.round( this.z );
  2196. return this;
  2197. }
  2198. roundToZero() {
  2199. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  2200. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  2201. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  2202. return this;
  2203. }
  2204. negate() {
  2205. this.x = - this.x;
  2206. this.y = - this.y;
  2207. this.z = - this.z;
  2208. return this;
  2209. }
  2210. dot( v ) {
  2211. return this.x * v.x + this.y * v.y + this.z * v.z;
  2212. }
  2213. // TODO lengthSquared?
  2214. lengthSq() {
  2215. return this.x * this.x + this.y * this.y + this.z * this.z;
  2216. }
  2217. length() {
  2218. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2219. }
  2220. manhattanLength() {
  2221. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2222. }
  2223. normalize() {
  2224. return this.divideScalar( this.length() || 1 );
  2225. }
  2226. setLength( length ) {
  2227. return this.normalize().multiplyScalar( length );
  2228. }
  2229. lerp( v, alpha ) {
  2230. this.x += ( v.x - this.x ) * alpha;
  2231. this.y += ( v.y - this.y ) * alpha;
  2232. this.z += ( v.z - this.z ) * alpha;
  2233. return this;
  2234. }
  2235. lerpVectors( v1, v2, alpha ) {
  2236. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2237. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2238. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2239. return this;
  2240. }
  2241. cross( v, w ) {
  2242. if ( w !== undefined ) {
  2243. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  2244. return this.crossVectors( v, w );
  2245. }
  2246. return this.crossVectors( this, v );
  2247. }
  2248. crossVectors( a, b ) {
  2249. const ax = a.x, ay = a.y, az = a.z;
  2250. const bx = b.x, by = b.y, bz = b.z;
  2251. this.x = ay * bz - az * by;
  2252. this.y = az * bx - ax * bz;
  2253. this.z = ax * by - ay * bx;
  2254. return this;
  2255. }
  2256. projectOnVector( v ) {
  2257. const denominator = v.lengthSq();
  2258. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2259. const scalar = v.dot( this ) / denominator;
  2260. return this.copy( v ).multiplyScalar( scalar );
  2261. }
  2262. projectOnPlane( planeNormal ) {
  2263. _vector.copy( this ).projectOnVector( planeNormal );
  2264. return this.sub( _vector );
  2265. }
  2266. reflect( normal ) {
  2267. // reflect incident vector off plane orthogonal to normal
  2268. // normal is assumed to have unit length
  2269. return this.sub( _vector.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2270. }
  2271. angleTo( v ) {
  2272. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2273. if ( denominator === 0 ) return Math.PI / 2;
  2274. const theta = this.dot( v ) / denominator;
  2275. // clamp, to handle numerical problems
  2276. return Math.acos( MathUtils.clamp( theta, - 1, 1 ) );
  2277. }
  2278. distanceTo( v ) {
  2279. return Math.sqrt( this.distanceToSquared( v ) );
  2280. }
  2281. distanceToSquared( v ) {
  2282. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2283. return dx * dx + dy * dy + dz * dz;
  2284. }
  2285. manhattanDistanceTo( v ) {
  2286. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2287. }
  2288. setFromSpherical( s ) {
  2289. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2290. }
  2291. setFromSphericalCoords( radius, phi, theta ) {
  2292. const sinPhiRadius = Math.sin( phi ) * radius;
  2293. this.x = sinPhiRadius * Math.sin( theta );
  2294. this.y = Math.cos( phi ) * radius;
  2295. this.z = sinPhiRadius * Math.cos( theta );
  2296. return this;
  2297. }
  2298. setFromCylindrical( c ) {
  2299. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2300. }
  2301. setFromCylindricalCoords( radius, theta, y ) {
  2302. this.x = radius * Math.sin( theta );
  2303. this.y = y;
  2304. this.z = radius * Math.cos( theta );
  2305. return this;
  2306. }
  2307. setFromMatrixPosition( m ) {
  2308. const e = m.elements;
  2309. this.x = e[ 12 ];
  2310. this.y = e[ 13 ];
  2311. this.z = e[ 14 ];
  2312. return this;
  2313. }
  2314. setFromMatrixScale( m ) {
  2315. const sx = this.setFromMatrixColumn( m, 0 ).length();
  2316. const sy = this.setFromMatrixColumn( m, 1 ).length();
  2317. const sz = this.setFromMatrixColumn( m, 2 ).length();
  2318. this.x = sx;
  2319. this.y = sy;
  2320. this.z = sz;
  2321. return this;
  2322. }
  2323. setFromMatrixColumn( m, index ) {
  2324. return this.fromArray( m.elements, index * 4 );
  2325. }
  2326. setFromMatrix3Column( m, index ) {
  2327. return this.fromArray( m.elements, index * 3 );
  2328. }
  2329. equals( v ) {
  2330. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2331. }
  2332. fromArray( array, offset = 0 ) {
  2333. this.x = array[ offset ];
  2334. this.y = array[ offset + 1 ];
  2335. this.z = array[ offset + 2 ];
  2336. return this;
  2337. }
  2338. toArray( array = [], offset = 0 ) {
  2339. array[ offset ] = this.x;
  2340. array[ offset + 1 ] = this.y;
  2341. array[ offset + 2 ] = this.z;
  2342. return array;
  2343. }
  2344. fromBufferAttribute( attribute, index, offset ) {
  2345. if ( offset !== undefined ) {
  2346. console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' );
  2347. }
  2348. this.x = attribute.getX( index );
  2349. this.y = attribute.getY( index );
  2350. this.z = attribute.getZ( index );
  2351. return this;
  2352. }
  2353. random() {
  2354. this.x = Math.random();
  2355. this.y = Math.random();
  2356. this.z = Math.random();
  2357. return this;
  2358. }
  2359. }
  2360. Vector3.prototype.isVector3 = true;
  2361. const _vector = /*@__PURE__*/ new Vector3();
  2362. const _quaternion = /*@__PURE__*/ new Quaternion();
  2363. class Box3 {
  2364. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  2365. this.min = min;
  2366. this.max = max;
  2367. }
  2368. set( min, max ) {
  2369. this.min.copy( min );
  2370. this.max.copy( max );
  2371. return this;
  2372. }
  2373. setFromArray( array ) {
  2374. let minX = + Infinity;
  2375. let minY = + Infinity;
  2376. let minZ = + Infinity;
  2377. let maxX = - Infinity;
  2378. let maxY = - Infinity;
  2379. let maxZ = - Infinity;
  2380. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  2381. const x = array[ i ];
  2382. const y = array[ i + 1 ];
  2383. const z = array[ i + 2 ];
  2384. if ( x < minX ) minX = x;
  2385. if ( y < minY ) minY = y;
  2386. if ( z < minZ ) minZ = z;
  2387. if ( x > maxX ) maxX = x;
  2388. if ( y > maxY ) maxY = y;
  2389. if ( z > maxZ ) maxZ = z;
  2390. }
  2391. this.min.set( minX, minY, minZ );
  2392. this.max.set( maxX, maxY, maxZ );
  2393. return this;
  2394. }
  2395. setFromBufferAttribute( attribute ) {
  2396. let minX = + Infinity;
  2397. let minY = + Infinity;
  2398. let minZ = + Infinity;
  2399. let maxX = - Infinity;
  2400. let maxY = - Infinity;
  2401. let maxZ = - Infinity;
  2402. for ( let i = 0, l = attribute.count; i < l; i ++ ) {
  2403. const x = attribute.getX( i );
  2404. const y = attribute.getY( i );
  2405. const z = attribute.getZ( i );
  2406. if ( x < minX ) minX = x;
  2407. if ( y < minY ) minY = y;
  2408. if ( z < minZ ) minZ = z;
  2409. if ( x > maxX ) maxX = x;
  2410. if ( y > maxY ) maxY = y;
  2411. if ( z > maxZ ) maxZ = z;
  2412. }
  2413. this.min.set( minX, minY, minZ );
  2414. this.max.set( maxX, maxY, maxZ );
  2415. return this;
  2416. }
  2417. setFromPoints( points ) {
  2418. this.makeEmpty();
  2419. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2420. this.expandByPoint( points[ i ] );
  2421. }
  2422. return this;
  2423. }
  2424. setFromCenterAndSize( center, size ) {
  2425. const halfSize = _vector$1.copy( size ).multiplyScalar( 0.5 );
  2426. this.min.copy( center ).sub( halfSize );
  2427. this.max.copy( center ).add( halfSize );
  2428. return this;
  2429. }
  2430. setFromObject( object ) {
  2431. this.makeEmpty();
  2432. return this.expandByObject( object );
  2433. }
  2434. clone() {
  2435. return new this.constructor().copy( this );
  2436. }
  2437. copy( box ) {
  2438. this.min.copy( box.min );
  2439. this.max.copy( box.max );
  2440. return this;
  2441. }
  2442. makeEmpty() {
  2443. this.min.x = this.min.y = this.min.z = + Infinity;
  2444. this.max.x = this.max.y = this.max.z = - Infinity;
  2445. return this;
  2446. }
  2447. isEmpty() {
  2448. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2449. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2450. }
  2451. getCenter( target ) {
  2452. if ( target === undefined ) {
  2453. console.warn( 'THREE.Box3: .getCenter() target is now required' );
  2454. target = new Vector3();
  2455. }
  2456. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2457. }
  2458. getSize( target ) {
  2459. if ( target === undefined ) {
  2460. console.warn( 'THREE.Box3: .getSize() target is now required' );
  2461. target = new Vector3();
  2462. }
  2463. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  2464. }
  2465. expandByPoint( point ) {
  2466. this.min.min( point );
  2467. this.max.max( point );
  2468. return this;
  2469. }
  2470. expandByVector( vector ) {
  2471. this.min.sub( vector );
  2472. this.max.add( vector );
  2473. return this;
  2474. }
  2475. expandByScalar( scalar ) {
  2476. this.min.addScalar( - scalar );
  2477. this.max.addScalar( scalar );
  2478. return this;
  2479. }
  2480. expandByObject( object ) {
  2481. // Computes the world-axis-aligned bounding box of an object (including its children),
  2482. // accounting for both the object's, and children's, world transforms
  2483. object.updateWorldMatrix( false, false );
  2484. const geometry = object.geometry;
  2485. if ( geometry !== undefined ) {
  2486. if ( geometry.boundingBox === null ) {
  2487. geometry.computeBoundingBox();
  2488. }
  2489. _box.copy( geometry.boundingBox );
  2490. _box.applyMatrix4( object.matrixWorld );
  2491. this.union( _box );
  2492. }
  2493. const children = object.children;
  2494. for ( let i = 0, l = children.length; i < l; i ++ ) {
  2495. this.expandByObject( children[ i ] );
  2496. }
  2497. return this;
  2498. }
  2499. containsPoint( point ) {
  2500. return point.x < this.min.x || point.x > this.max.x ||
  2501. point.y < this.min.y || point.y > this.max.y ||
  2502. point.z < this.min.z || point.z > this.max.z ? false : true;
  2503. }
  2504. containsBox( box ) {
  2505. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  2506. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  2507. this.min.z <= box.min.z && box.max.z <= this.max.z;
  2508. }
  2509. getParameter( point, target ) {
  2510. // This can potentially have a divide by zero if the box
  2511. // has a size dimension of 0.
  2512. if ( target === undefined ) {
  2513. console.warn( 'THREE.Box3: .getParameter() target is now required' );
  2514. target = new Vector3();
  2515. }
  2516. return target.set(
  2517. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2518. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2519. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2520. );
  2521. }
  2522. intersectsBox( box ) {
  2523. // using 6 splitting planes to rule out intersections.
  2524. return box.max.x < this.min.x || box.min.x > this.max.x ||
  2525. box.max.y < this.min.y || box.min.y > this.max.y ||
  2526. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  2527. }
  2528. intersectsSphere( sphere ) {
  2529. // Find the point on the AABB closest to the sphere center.
  2530. this.clampPoint( sphere.center, _vector$1 );
  2531. // If that point is inside the sphere, the AABB and sphere intersect.
  2532. return _vector$1.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  2533. }
  2534. intersectsPlane( plane ) {
  2535. // We compute the minimum and maximum dot product values. If those values
  2536. // are on the same side (back or front) of the plane, then there is no intersection.
  2537. let min, max;
  2538. if ( plane.normal.x > 0 ) {
  2539. min = plane.normal.x * this.min.x;
  2540. max = plane.normal.x * this.max.x;
  2541. } else {
  2542. min = plane.normal.x * this.max.x;
  2543. max = plane.normal.x * this.min.x;
  2544. }
  2545. if ( plane.normal.y > 0 ) {
  2546. min += plane.normal.y * this.min.y;
  2547. max += plane.normal.y * this.max.y;
  2548. } else {
  2549. min += plane.normal.y * this.max.y;
  2550. max += plane.normal.y * this.min.y;
  2551. }
  2552. if ( plane.normal.z > 0 ) {
  2553. min += plane.normal.z * this.min.z;
  2554. max += plane.normal.z * this.max.z;
  2555. } else {
  2556. min += plane.normal.z * this.max.z;
  2557. max += plane.normal.z * this.min.z;
  2558. }
  2559. return ( min <= - plane.constant && max >= - plane.constant );
  2560. }
  2561. intersectsTriangle( triangle ) {
  2562. if ( this.isEmpty() ) {
  2563. return false;
  2564. }
  2565. // compute box center and extents
  2566. this.getCenter( _center );
  2567. _extents.subVectors( this.max, _center );
  2568. // translate triangle to aabb origin
  2569. _v0.subVectors( triangle.a, _center );
  2570. _v1.subVectors( triangle.b, _center );
  2571. _v2.subVectors( triangle.c, _center );
  2572. // compute edge vectors for triangle
  2573. _f0.subVectors( _v1, _v0 );
  2574. _f1.subVectors( _v2, _v1 );
  2575. _f2.subVectors( _v0, _v2 );
  2576. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  2577. // 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
  2578. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2579. let axes = [
  2580. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  2581. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  2582. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  2583. ];
  2584. if ( ! satForAxes( axes, _v0, _v1, _v2, _extents ) ) {
  2585. return false;
  2586. }
  2587. // test 3 face normals from the aabb
  2588. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  2589. if ( ! satForAxes( axes, _v0, _v1, _v2, _extents ) ) {
  2590. return false;
  2591. }
  2592. // finally testing the face normal of the triangle
  2593. // use already existing triangle edge vectors here
  2594. _triangleNormal.crossVectors( _f0, _f1 );
  2595. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  2596. return satForAxes( axes, _v0, _v1, _v2, _extents );
  2597. }
  2598. clampPoint( point, target ) {
  2599. if ( target === undefined ) {
  2600. console.warn( 'THREE.Box3: .clampPoint() target is now required' );
  2601. target = new Vector3();
  2602. }
  2603. return target.copy( point ).clamp( this.min, this.max );
  2604. }
  2605. distanceToPoint( point ) {
  2606. const clampedPoint = _vector$1.copy( point ).clamp( this.min, this.max );
  2607. return clampedPoint.sub( point ).length();
  2608. }
  2609. getBoundingSphere( target ) {
  2610. if ( target === undefined ) {
  2611. console.error( 'THREE.Box3: .getBoundingSphere() target is now required' );
  2612. //target = new Sphere(); // removed to avoid cyclic dependency
  2613. }
  2614. this.getCenter( target.center );
  2615. target.radius = this.getSize( _vector$1 ).length() * 0.5;
  2616. return target;
  2617. }
  2618. intersect( box ) {
  2619. this.min.max( box.min );
  2620. this.max.min( box.max );
  2621. // 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.
  2622. if ( this.isEmpty() ) this.makeEmpty();
  2623. return this;
  2624. }
  2625. union( box ) {
  2626. this.min.min( box.min );
  2627. this.max.max( box.max );
  2628. return this;
  2629. }
  2630. applyMatrix4( matrix ) {
  2631. // transform of empty box is an empty box.
  2632. if ( this.isEmpty() ) return this;
  2633. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2634. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2635. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2636. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2637. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2638. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2639. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2640. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2641. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2642. this.setFromPoints( _points );
  2643. return this;
  2644. }
  2645. translate( offset ) {
  2646. this.min.add( offset );
  2647. this.max.add( offset );
  2648. return this;
  2649. }
  2650. equals( box ) {
  2651. return box.min.equals( this.min ) && box.max.equals( this.max );
  2652. }
  2653. }
  2654. Box3.prototype.isBox3 = true;
  2655. const _points = [
  2656. /*@__PURE__*/ new Vector3(),
  2657. /*@__PURE__*/ new Vector3(),
  2658. /*@__PURE__*/ new Vector3(),
  2659. /*@__PURE__*/ new Vector3(),
  2660. /*@__PURE__*/ new Vector3(),
  2661. /*@__PURE__*/ new Vector3(),
  2662. /*@__PURE__*/ new Vector3(),
  2663. /*@__PURE__*/ new Vector3()
  2664. ];
  2665. const _vector$1 = /*@__PURE__*/ new Vector3();
  2666. const _box = /*@__PURE__*/ new Box3();
  2667. // triangle centered vertices
  2668. const _v0 = /*@__PURE__*/ new Vector3();
  2669. const _v1 = /*@__PURE__*/ new Vector3();
  2670. const _v2 = /*@__PURE__*/ new Vector3();
  2671. // triangle edge vectors
  2672. const _f0 = /*@__PURE__*/ new Vector3();
  2673. const _f1 = /*@__PURE__*/ new Vector3();
  2674. const _f2 = /*@__PURE__*/ new Vector3();
  2675. const _center = /*@__PURE__*/ new Vector3();
  2676. const _extents = /*@__PURE__*/ new Vector3();
  2677. const _triangleNormal = /*@__PURE__*/ new Vector3();
  2678. const _testAxis = /*@__PURE__*/ new Vector3();
  2679. function satForAxes( axes, v0, v1, v2, extents ) {
  2680. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  2681. _testAxis.fromArray( axes, i );
  2682. // project the aabb onto the seperating axis
  2683. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  2684. // project all 3 vertices of the triangle onto the seperating axis
  2685. const p0 = v0.dot( _testAxis );
  2686. const p1 = v1.dot( _testAxis );
  2687. const p2 = v2.dot( _testAxis );
  2688. // actual test, basically see if either of the most extreme of the triangle points intersects r
  2689. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  2690. // points of the projected triangle are outside the projected half-length of the aabb
  2691. // the axis is seperating and we can exit
  2692. return false;
  2693. }
  2694. }
  2695. return true;
  2696. }
  2697. const _box$1 = /*@__PURE__*/ new Box3();
  2698. class Sphere {
  2699. constructor( center = new Vector3(), radius = - 1 ) {
  2700. this.center = center;
  2701. this.radius = radius;
  2702. }
  2703. set( center, radius ) {
  2704. this.center.copy( center );
  2705. this.radius = radius;
  2706. return this;
  2707. }
  2708. setFromPoints( points, optionalCenter ) {
  2709. const center = this.center;
  2710. if ( optionalCenter !== undefined ) {
  2711. center.copy( optionalCenter );
  2712. } else {
  2713. _box$1.setFromPoints( points ).getCenter( center );
  2714. }
  2715. let maxRadiusSq = 0;
  2716. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2717. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  2718. }
  2719. this.radius = Math.sqrt( maxRadiusSq );
  2720. return this;
  2721. }
  2722. copy( sphere ) {
  2723. this.center.copy( sphere.center );
  2724. this.radius = sphere.radius;
  2725. return this;
  2726. }
  2727. isEmpty() {
  2728. return ( this.radius < 0 );
  2729. }
  2730. makeEmpty() {
  2731. this.center.set( 0, 0, 0 );
  2732. this.radius = - 1;
  2733. return this;
  2734. }
  2735. containsPoint( point ) {
  2736. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  2737. }
  2738. distanceToPoint( point ) {
  2739. return ( point.distanceTo( this.center ) - this.radius );
  2740. }
  2741. intersectsSphere( sphere ) {
  2742. const radiusSum = this.radius + sphere.radius;
  2743. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  2744. }
  2745. intersectsBox( box ) {
  2746. return box.intersectsSphere( this );
  2747. }
  2748. intersectsPlane( plane ) {
  2749. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  2750. }
  2751. clampPoint( point, target ) {
  2752. const deltaLengthSq = this.center.distanceToSquared( point );
  2753. if ( target === undefined ) {
  2754. console.warn( 'THREE.Sphere: .clampPoint() target is now required' );
  2755. target = new Vector3();
  2756. }
  2757. target.copy( point );
  2758. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  2759. target.sub( this.center ).normalize();
  2760. target.multiplyScalar( this.radius ).add( this.center );
  2761. }
  2762. return target;
  2763. }
  2764. getBoundingBox( target ) {
  2765. if ( target === undefined ) {
  2766. console.warn( 'THREE.Sphere: .getBoundingBox() target is now required' );
  2767. target = new Box3();
  2768. }
  2769. if ( this.isEmpty() ) {
  2770. // Empty sphere produces empty bounding box
  2771. target.makeEmpty();
  2772. return target;
  2773. }
  2774. target.set( this.center, this.center );
  2775. target.expandByScalar( this.radius );
  2776. return target;
  2777. }
  2778. applyMatrix4( matrix ) {
  2779. this.center.applyMatrix4( matrix );
  2780. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  2781. return this;
  2782. }
  2783. translate( offset ) {
  2784. this.center.add( offset );
  2785. return this;
  2786. }
  2787. equals( sphere ) {
  2788. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  2789. }
  2790. clone() {
  2791. return new this.constructor().copy( this );
  2792. }
  2793. }
  2794. const _vector$2 = /*@__PURE__*/ new Vector3();
  2795. const _segCenter = /*@__PURE__*/ new Vector3();
  2796. const _segDir = /*@__PURE__*/ new Vector3();
  2797. const _diff = /*@__PURE__*/ new Vector3();
  2798. const _edge1 = /*@__PURE__*/ new Vector3();
  2799. const _edge2 = /*@__PURE__*/ new Vector3();
  2800. const _normal = /*@__PURE__*/ new Vector3();
  2801. class Ray {
  2802. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  2803. this.origin = origin;
  2804. this.direction = direction;
  2805. }
  2806. set( origin, direction ) {
  2807. this.origin.copy( origin );
  2808. this.direction.copy( direction );
  2809. return this;
  2810. }
  2811. copy( ray ) {
  2812. this.origin.copy( ray.origin );
  2813. this.direction.copy( ray.direction );
  2814. return this;
  2815. }
  2816. at( t, target ) {
  2817. if ( target === undefined ) {
  2818. console.warn( 'THREE.Ray: .at() target is now required' );
  2819. target = new Vector3();
  2820. }
  2821. return target.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  2822. }
  2823. lookAt( v ) {
  2824. this.direction.copy( v ).sub( this.origin ).normalize();
  2825. return this;
  2826. }
  2827. recast( t ) {
  2828. this.origin.copy( this.at( t, _vector$2 ) );
  2829. return this;
  2830. }
  2831. closestPointToPoint( point, target ) {
  2832. if ( target === undefined ) {
  2833. console.warn( 'THREE.Ray: .closestPointToPoint() target is now required' );
  2834. target = new Vector3();
  2835. }
  2836. target.subVectors( point, this.origin );
  2837. const directionDistance = target.dot( this.direction );
  2838. if ( directionDistance < 0 ) {
  2839. return target.copy( this.origin );
  2840. }
  2841. return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  2842. }
  2843. distanceToPoint( point ) {
  2844. return Math.sqrt( this.distanceSqToPoint( point ) );
  2845. }
  2846. distanceSqToPoint( point ) {
  2847. const directionDistance = _vector$2.subVectors( point, this.origin ).dot( this.direction );
  2848. // point behind the ray
  2849. if ( directionDistance < 0 ) {
  2850. return this.origin.distanceToSquared( point );
  2851. }
  2852. _vector$2.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  2853. return _vector$2.distanceToSquared( point );
  2854. }
  2855. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  2856. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  2857. // It returns the min distance between the ray and the segment
  2858. // defined by v0 and v1
  2859. // It can also set two optional targets :
  2860. // - The closest point on the ray
  2861. // - The closest point on the segment
  2862. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  2863. _segDir.copy( v1 ).sub( v0 ).normalize();
  2864. _diff.copy( this.origin ).sub( _segCenter );
  2865. const segExtent = v0.distanceTo( v1 ) * 0.5;
  2866. const a01 = - this.direction.dot( _segDir );
  2867. const b0 = _diff.dot( this.direction );
  2868. const b1 = - _diff.dot( _segDir );
  2869. const c = _diff.lengthSq();
  2870. const det = Math.abs( 1 - a01 * a01 );
  2871. let s0, s1, sqrDist, extDet;
  2872. if ( det > 0 ) {
  2873. // The ray and segment are not parallel.
  2874. s0 = a01 * b1 - b0;
  2875. s1 = a01 * b0 - b1;
  2876. extDet = segExtent * det;
  2877. if ( s0 >= 0 ) {
  2878. if ( s1 >= - extDet ) {
  2879. if ( s1 <= extDet ) {
  2880. // region 0
  2881. // Minimum at interior points of ray and segment.
  2882. const invDet = 1 / det;
  2883. s0 *= invDet;
  2884. s1 *= invDet;
  2885. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  2886. } else {
  2887. // region 1
  2888. s1 = segExtent;
  2889. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  2890. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  2891. }
  2892. } else {
  2893. // region 5
  2894. s1 = - segExtent;
  2895. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  2896. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  2897. }
  2898. } else {
  2899. if ( s1 <= - extDet ) {
  2900. // region 4
  2901. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  2902. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  2903. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  2904. } else if ( s1 <= extDet ) {
  2905. // region 3
  2906. s0 = 0;
  2907. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  2908. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  2909. } else {
  2910. // region 2
  2911. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  2912. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  2913. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  2914. }
  2915. }
  2916. } else {
  2917. // Ray and segment are parallel.
  2918. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  2919. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  2920. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  2921. }
  2922. if ( optionalPointOnRay ) {
  2923. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  2924. }
  2925. if ( optionalPointOnSegment ) {
  2926. optionalPointOnSegment.copy( _segDir ).multiplyScalar( s1 ).add( _segCenter );
  2927. }
  2928. return sqrDist;
  2929. }
  2930. intersectSphere( sphere, target ) {
  2931. _vector$2.subVectors( sphere.center, this.origin );
  2932. const tca = _vector$2.dot( this.direction );
  2933. const d2 = _vector$2.dot( _vector$2 ) - tca * tca;
  2934. const radius2 = sphere.radius * sphere.radius;
  2935. if ( d2 > radius2 ) return null;
  2936. const thc = Math.sqrt( radius2 - d2 );
  2937. // t0 = first intersect point - entrance on front of sphere
  2938. const t0 = tca - thc;
  2939. // t1 = second intersect point - exit point on back of sphere
  2940. const t1 = tca + thc;
  2941. // test to see if both t0 and t1 are behind the ray - if so, return null
  2942. if ( t0 < 0 && t1 < 0 ) return null;
  2943. // test to see if t0 is behind the ray:
  2944. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  2945. // in order to always return an intersect point that is in front of the ray.
  2946. if ( t0 < 0 ) return this.at( t1, target );
  2947. // else t0 is in front of the ray, so return the first collision point scaled by t0
  2948. return this.at( t0, target );
  2949. }
  2950. intersectsSphere( sphere ) {
  2951. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  2952. }
  2953. distanceToPlane( plane ) {
  2954. const denominator = plane.normal.dot( this.direction );
  2955. if ( denominator === 0 ) {
  2956. // line is coplanar, return origin
  2957. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  2958. return 0;
  2959. }
  2960. // Null is preferable to undefined since undefined means.... it is undefined
  2961. return null;
  2962. }
  2963. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  2964. // Return if the ray never intersects the plane
  2965. return t >= 0 ? t : null;
  2966. }
  2967. intersectPlane( plane, target ) {
  2968. const t = this.distanceToPlane( plane );
  2969. if ( t === null ) {
  2970. return null;
  2971. }
  2972. return this.at( t, target );
  2973. }
  2974. intersectsPlane( plane ) {
  2975. // check if the ray lies on the plane first
  2976. const distToPoint = plane.distanceToPoint( this.origin );
  2977. if ( distToPoint === 0 ) {
  2978. return true;
  2979. }
  2980. const denominator = plane.normal.dot( this.direction );
  2981. if ( denominator * distToPoint < 0 ) {
  2982. return true;
  2983. }
  2984. // ray origin is behind the plane (and is pointing behind it)
  2985. return false;
  2986. }
  2987. intersectBox( box, target ) {
  2988. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  2989. const invdirx = 1 / this.direction.x,
  2990. invdiry = 1 / this.direction.y,
  2991. invdirz = 1 / this.direction.z;
  2992. const origin = this.origin;
  2993. if ( invdirx >= 0 ) {
  2994. tmin = ( box.min.x - origin.x ) * invdirx;
  2995. tmax = ( box.max.x - origin.x ) * invdirx;
  2996. } else {
  2997. tmin = ( box.max.x - origin.x ) * invdirx;
  2998. tmax = ( box.min.x - origin.x ) * invdirx;
  2999. }
  3000. if ( invdiry >= 0 ) {
  3001. tymin = ( box.min.y - origin.y ) * invdiry;
  3002. tymax = ( box.max.y - origin.y ) * invdiry;
  3003. } else {
  3004. tymin = ( box.max.y - origin.y ) * invdiry;
  3005. tymax = ( box.min.y - origin.y ) * invdiry;
  3006. }
  3007. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3008. // These lines also handle the case where tmin or tmax is NaN
  3009. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3010. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  3011. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  3012. if ( invdirz >= 0 ) {
  3013. tzmin = ( box.min.z - origin.z ) * invdirz;
  3014. tzmax = ( box.max.z - origin.z ) * invdirz;
  3015. } else {
  3016. tzmin = ( box.max.z - origin.z ) * invdirz;
  3017. tzmax = ( box.min.z - origin.z ) * invdirz;
  3018. }
  3019. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3020. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3021. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3022. //return point closest to the ray (positive side)
  3023. if ( tmax < 0 ) return null;
  3024. return this.at( tmin >= 0 ? tmin : tmax, target );
  3025. }
  3026. intersectsBox( box ) {
  3027. return this.intersectBox( box, _vector$2 ) !== null;
  3028. }
  3029. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3030. // Compute the offset origin, edges, and normal.
  3031. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3032. _edge1.subVectors( b, a );
  3033. _edge2.subVectors( c, a );
  3034. _normal.crossVectors( _edge1, _edge2 );
  3035. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3036. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3037. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3038. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3039. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3040. let DdN = this.direction.dot( _normal );
  3041. let sign;
  3042. if ( DdN > 0 ) {
  3043. if ( backfaceCulling ) return null;
  3044. sign = 1;
  3045. } else if ( DdN < 0 ) {
  3046. sign = - 1;
  3047. DdN = - DdN;
  3048. } else {
  3049. return null;
  3050. }
  3051. _diff.subVectors( this.origin, a );
  3052. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3053. // b1 < 0, no intersection
  3054. if ( DdQxE2 < 0 ) {
  3055. return null;
  3056. }
  3057. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3058. // b2 < 0, no intersection
  3059. if ( DdE1xQ < 0 ) {
  3060. return null;
  3061. }
  3062. // b1+b2 > 1, no intersection
  3063. if ( DdQxE2 + DdE1xQ > DdN ) {
  3064. return null;
  3065. }
  3066. // Line intersects triangle, check if ray does.
  3067. const QdN = - sign * _diff.dot( _normal );
  3068. // t < 0, no intersection
  3069. if ( QdN < 0 ) {
  3070. return null;
  3071. }
  3072. // Ray intersects triangle.
  3073. return this.at( QdN / DdN, target );
  3074. }
  3075. applyMatrix4( matrix4 ) {
  3076. this.origin.applyMatrix4( matrix4 );
  3077. this.direction.transformDirection( matrix4 );
  3078. return this;
  3079. }
  3080. equals( ray ) {
  3081. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3082. }
  3083. clone() {
  3084. return new this.constructor().copy( this );
  3085. }
  3086. }
  3087. class Matrix4 {
  3088. constructor() {
  3089. this.elements = [
  3090. 1, 0, 0, 0,
  3091. 0, 1, 0, 0,
  3092. 0, 0, 1, 0,
  3093. 0, 0, 0, 1
  3094. ];
  3095. if ( arguments.length > 0 ) {
  3096. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  3097. }
  3098. }
  3099. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3100. const te = this.elements;
  3101. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3102. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3103. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3104. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3105. return this;
  3106. }
  3107. identity() {
  3108. this.set(
  3109. 1, 0, 0, 0,
  3110. 0, 1, 0, 0,
  3111. 0, 0, 1, 0,
  3112. 0, 0, 0, 1
  3113. );
  3114. return this;
  3115. }
  3116. clone() {
  3117. return new Matrix4().fromArray( this.elements );
  3118. }
  3119. copy( m ) {
  3120. const te = this.elements;
  3121. const me = m.elements;
  3122. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3123. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3124. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3125. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3126. return this;
  3127. }
  3128. copyPosition( m ) {
  3129. const te = this.elements, me = m.elements;
  3130. te[ 12 ] = me[ 12 ];
  3131. te[ 13 ] = me[ 13 ];
  3132. te[ 14 ] = me[ 14 ];
  3133. return this;
  3134. }
  3135. setFromMatrix3( m ) {
  3136. const me = m.elements;
  3137. this.set(
  3138. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3139. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3140. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3141. 0, 0, 0, 1
  3142. );
  3143. return this;
  3144. }
  3145. extractBasis( xAxis, yAxis, zAxis ) {
  3146. xAxis.setFromMatrixColumn( this, 0 );
  3147. yAxis.setFromMatrixColumn( this, 1 );
  3148. zAxis.setFromMatrixColumn( this, 2 );
  3149. return this;
  3150. }
  3151. makeBasis( xAxis, yAxis, zAxis ) {
  3152. this.set(
  3153. xAxis.x, yAxis.x, zAxis.x, 0,
  3154. xAxis.y, yAxis.y, zAxis.y, 0,
  3155. xAxis.z, yAxis.z, zAxis.z, 0,
  3156. 0, 0, 0, 1
  3157. );
  3158. return this;
  3159. }
  3160. extractRotation( m ) {
  3161. // this method does not support reflection matrices
  3162. const te = this.elements;
  3163. const me = m.elements;
  3164. const scaleX = 1 / _v1$1.setFromMatrixColumn( m, 0 ).length();
  3165. const scaleY = 1 / _v1$1.setFromMatrixColumn( m, 1 ).length();
  3166. const scaleZ = 1 / _v1$1.setFromMatrixColumn( m, 2 ).length();
  3167. te[ 0 ] = me[ 0 ] * scaleX;
  3168. te[ 1 ] = me[ 1 ] * scaleX;
  3169. te[ 2 ] = me[ 2 ] * scaleX;
  3170. te[ 3 ] = 0;
  3171. te[ 4 ] = me[ 4 ] * scaleY;
  3172. te[ 5 ] = me[ 5 ] * scaleY;
  3173. te[ 6 ] = me[ 6 ] * scaleY;
  3174. te[ 7 ] = 0;
  3175. te[ 8 ] = me[ 8 ] * scaleZ;
  3176. te[ 9 ] = me[ 9 ] * scaleZ;
  3177. te[ 10 ] = me[ 10 ] * scaleZ;
  3178. te[ 11 ] = 0;
  3179. te[ 12 ] = 0;
  3180. te[ 13 ] = 0;
  3181. te[ 14 ] = 0;
  3182. te[ 15 ] = 1;
  3183. return this;
  3184. }
  3185. makeRotationFromEuler( euler ) {
  3186. if ( ! ( euler && euler.isEuler ) ) {
  3187. console.error( 'THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  3188. }
  3189. const te = this.elements;
  3190. const x = euler.x, y = euler.y, z = euler.z;
  3191. const a = Math.cos( x ), b = Math.sin( x );
  3192. const c = Math.cos( y ), d = Math.sin( y );
  3193. const e = Math.cos( z ), f = Math.sin( z );
  3194. if ( euler.order === 'XYZ' ) {
  3195. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3196. te[ 0 ] = c * e;
  3197. te[ 4 ] = - c * f;
  3198. te[ 8 ] = d;
  3199. te[ 1 ] = af + be * d;
  3200. te[ 5 ] = ae - bf * d;
  3201. te[ 9 ] = - b * c;
  3202. te[ 2 ] = bf - ae * d;
  3203. te[ 6 ] = be + af * d;
  3204. te[ 10 ] = a * c;
  3205. } else if ( euler.order === 'YXZ' ) {
  3206. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3207. te[ 0 ] = ce + df * b;
  3208. te[ 4 ] = de * b - cf;
  3209. te[ 8 ] = a * d;
  3210. te[ 1 ] = a * f;
  3211. te[ 5 ] = a * e;
  3212. te[ 9 ] = - b;
  3213. te[ 2 ] = cf * b - de;
  3214. te[ 6 ] = df + ce * b;
  3215. te[ 10 ] = a * c;
  3216. } else if ( euler.order === 'ZXY' ) {
  3217. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3218. te[ 0 ] = ce - df * b;
  3219. te[ 4 ] = - a * f;
  3220. te[ 8 ] = de + cf * b;
  3221. te[ 1 ] = cf + de * b;
  3222. te[ 5 ] = a * e;
  3223. te[ 9 ] = df - ce * b;
  3224. te[ 2 ] = - a * d;
  3225. te[ 6 ] = b;
  3226. te[ 10 ] = a * c;
  3227. } else if ( euler.order === 'ZYX' ) {
  3228. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3229. te[ 0 ] = c * e;
  3230. te[ 4 ] = be * d - af;
  3231. te[ 8 ] = ae * d + bf;
  3232. te[ 1 ] = c * f;
  3233. te[ 5 ] = bf * d + ae;
  3234. te[ 9 ] = af * d - be;
  3235. te[ 2 ] = - d;
  3236. te[ 6 ] = b * c;
  3237. te[ 10 ] = a * c;
  3238. } else if ( euler.order === 'YZX' ) {
  3239. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3240. te[ 0 ] = c * e;
  3241. te[ 4 ] = bd - ac * f;
  3242. te[ 8 ] = bc * f + ad;
  3243. te[ 1 ] = f;
  3244. te[ 5 ] = a * e;
  3245. te[ 9 ] = - b * e;
  3246. te[ 2 ] = - d * e;
  3247. te[ 6 ] = ad * f + bc;
  3248. te[ 10 ] = ac - bd * f;
  3249. } else if ( euler.order === 'XZY' ) {
  3250. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3251. te[ 0 ] = c * e;
  3252. te[ 4 ] = - f;
  3253. te[ 8 ] = d * e;
  3254. te[ 1 ] = ac * f + bd;
  3255. te[ 5 ] = a * e;
  3256. te[ 9 ] = ad * f - bc;
  3257. te[ 2 ] = bc * f - ad;
  3258. te[ 6 ] = b * e;
  3259. te[ 10 ] = bd * f + ac;
  3260. }
  3261. // bottom row
  3262. te[ 3 ] = 0;
  3263. te[ 7 ] = 0;
  3264. te[ 11 ] = 0;
  3265. // last column
  3266. te[ 12 ] = 0;
  3267. te[ 13 ] = 0;
  3268. te[ 14 ] = 0;
  3269. te[ 15 ] = 1;
  3270. return this;
  3271. }
  3272. makeRotationFromQuaternion( q ) {
  3273. return this.compose( _zero, q, _one );
  3274. }
  3275. lookAt( eye, target, up ) {
  3276. const te = this.elements;
  3277. _z.subVectors( eye, target );
  3278. if ( _z.lengthSq() === 0 ) {
  3279. // eye and target are in the same position
  3280. _z.z = 1;
  3281. }
  3282. _z.normalize();
  3283. _x.crossVectors( up, _z );
  3284. if ( _x.lengthSq() === 0 ) {
  3285. // up and z are parallel
  3286. if ( Math.abs( up.z ) === 1 ) {
  3287. _z.x += 0.0001;
  3288. } else {
  3289. _z.z += 0.0001;
  3290. }
  3291. _z.normalize();
  3292. _x.crossVectors( up, _z );
  3293. }
  3294. _x.normalize();
  3295. _y.crossVectors( _z, _x );
  3296. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3297. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3298. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3299. return this;
  3300. }
  3301. multiply( m, n ) {
  3302. if ( n !== undefined ) {
  3303. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  3304. return this.multiplyMatrices( m, n );
  3305. }
  3306. return this.multiplyMatrices( this, m );
  3307. }
  3308. premultiply( m ) {
  3309. return this.multiplyMatrices( m, this );
  3310. }
  3311. multiplyMatrices( a, b ) {
  3312. const ae = a.elements;
  3313. const be = b.elements;
  3314. const te = this.elements;
  3315. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3316. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3317. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3318. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3319. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3320. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3321. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3322. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3323. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3324. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3325. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3326. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3327. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3328. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3329. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3330. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3331. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3332. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3333. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3334. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3335. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3336. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3337. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3338. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3339. return this;
  3340. }
  3341. multiplyScalar( s ) {
  3342. const te = this.elements;
  3343. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3344. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3345. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3346. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3347. return this;
  3348. }
  3349. determinant() {
  3350. const te = this.elements;
  3351. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3352. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3353. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3354. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3355. //TODO: make this more efficient
  3356. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3357. return (
  3358. n41 * (
  3359. + n14 * n23 * n32
  3360. - n13 * n24 * n32
  3361. - n14 * n22 * n33
  3362. + n12 * n24 * n33
  3363. + n13 * n22 * n34
  3364. - n12 * n23 * n34
  3365. ) +
  3366. n42 * (
  3367. + n11 * n23 * n34
  3368. - n11 * n24 * n33
  3369. + n14 * n21 * n33
  3370. - n13 * n21 * n34
  3371. + n13 * n24 * n31
  3372. - n14 * n23 * n31
  3373. ) +
  3374. n43 * (
  3375. + n11 * n24 * n32
  3376. - n11 * n22 * n34
  3377. - n14 * n21 * n32
  3378. + n12 * n21 * n34
  3379. + n14 * n22 * n31
  3380. - n12 * n24 * n31
  3381. ) +
  3382. n44 * (
  3383. - n13 * n22 * n31
  3384. - n11 * n23 * n32
  3385. + n11 * n22 * n33
  3386. + n13 * n21 * n32
  3387. - n12 * n21 * n33
  3388. + n12 * n23 * n31
  3389. )
  3390. );
  3391. }
  3392. transpose() {
  3393. const te = this.elements;
  3394. let tmp;
  3395. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3396. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3397. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3398. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3399. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3400. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3401. return this;
  3402. }
  3403. setPosition( x, y, z ) {
  3404. const te = this.elements;
  3405. if ( x.isVector3 ) {
  3406. te[ 12 ] = x.x;
  3407. te[ 13 ] = x.y;
  3408. te[ 14 ] = x.z;
  3409. } else {
  3410. te[ 12 ] = x;
  3411. te[ 13 ] = y;
  3412. te[ 14 ] = z;
  3413. }
  3414. return this;
  3415. }
  3416. invert() {
  3417. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3418. const te = this.elements,
  3419. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  3420. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  3421. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  3422. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  3423. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3424. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3425. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3426. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3427. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3428. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  3429. const detInv = 1 / det;
  3430. te[ 0 ] = t11 * detInv;
  3431. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  3432. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  3433. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  3434. te[ 4 ] = t12 * detInv;
  3435. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  3436. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  3437. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  3438. te[ 8 ] = t13 * detInv;
  3439. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  3440. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  3441. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  3442. te[ 12 ] = t14 * detInv;
  3443. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  3444. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  3445. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  3446. return this;
  3447. }
  3448. scale( v ) {
  3449. const te = this.elements;
  3450. const x = v.x, y = v.y, z = v.z;
  3451. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3452. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3453. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3454. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3455. return this;
  3456. }
  3457. getMaxScaleOnAxis() {
  3458. const te = this.elements;
  3459. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3460. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3461. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3462. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3463. }
  3464. makeTranslation( x, y, z ) {
  3465. this.set(
  3466. 1, 0, 0, x,
  3467. 0, 1, 0, y,
  3468. 0, 0, 1, z,
  3469. 0, 0, 0, 1
  3470. );
  3471. return this;
  3472. }
  3473. makeRotationX( theta ) {
  3474. const c = Math.cos( theta ), s = Math.sin( theta );
  3475. this.set(
  3476. 1, 0, 0, 0,
  3477. 0, c, - s, 0,
  3478. 0, s, c, 0,
  3479. 0, 0, 0, 1
  3480. );
  3481. return this;
  3482. }
  3483. makeRotationY( theta ) {
  3484. const c = Math.cos( theta ), s = Math.sin( theta );
  3485. this.set(
  3486. c, 0, s, 0,
  3487. 0, 1, 0, 0,
  3488. - s, 0, c, 0,
  3489. 0, 0, 0, 1
  3490. );
  3491. return this;
  3492. }
  3493. makeRotationZ( theta ) {
  3494. const c = Math.cos( theta ), s = Math.sin( theta );
  3495. this.set(
  3496. c, - s, 0, 0,
  3497. s, c, 0, 0,
  3498. 0, 0, 1, 0,
  3499. 0, 0, 0, 1
  3500. );
  3501. return this;
  3502. }
  3503. makeRotationAxis( axis, angle ) {
  3504. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3505. const c = Math.cos( angle );
  3506. const s = Math.sin( angle );
  3507. const t = 1 - c;
  3508. const x = axis.x, y = axis.y, z = axis.z;
  3509. const tx = t * x, ty = t * y;
  3510. this.set(
  3511. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3512. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3513. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3514. 0, 0, 0, 1
  3515. );
  3516. return this;
  3517. }
  3518. makeScale( x, y, z ) {
  3519. this.set(
  3520. x, 0, 0, 0,
  3521. 0, y, 0, 0,
  3522. 0, 0, z, 0,
  3523. 0, 0, 0, 1
  3524. );
  3525. return this;
  3526. }
  3527. makeShear( x, y, z ) {
  3528. this.set(
  3529. 1, y, z, 0,
  3530. x, 1, z, 0,
  3531. x, y, 1, 0,
  3532. 0, 0, 0, 1
  3533. );
  3534. return this;
  3535. }
  3536. compose( position, quaternion, scale ) {
  3537. const te = this.elements;
  3538. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  3539. const x2 = x + x, y2 = y + y, z2 = z + z;
  3540. const xx = x * x2, xy = x * y2, xz = x * z2;
  3541. const yy = y * y2, yz = y * z2, zz = z * z2;
  3542. const wx = w * x2, wy = w * y2, wz = w * z2;
  3543. const sx = scale.x, sy = scale.y, sz = scale.z;
  3544. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  3545. te[ 1 ] = ( xy + wz ) * sx;
  3546. te[ 2 ] = ( xz - wy ) * sx;
  3547. te[ 3 ] = 0;
  3548. te[ 4 ] = ( xy - wz ) * sy;
  3549. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  3550. te[ 6 ] = ( yz + wx ) * sy;
  3551. te[ 7 ] = 0;
  3552. te[ 8 ] = ( xz + wy ) * sz;
  3553. te[ 9 ] = ( yz - wx ) * sz;
  3554. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  3555. te[ 11 ] = 0;
  3556. te[ 12 ] = position.x;
  3557. te[ 13 ] = position.y;
  3558. te[ 14 ] = position.z;
  3559. te[ 15 ] = 1;
  3560. return this;
  3561. }
  3562. decompose( position, quaternion, scale ) {
  3563. const te = this.elements;
  3564. let sx = _v1$1.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  3565. const sy = _v1$1.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  3566. const sz = _v1$1.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  3567. // if determine is negative, we need to invert one scale
  3568. const det = this.determinant();
  3569. if ( det < 0 ) sx = - sx;
  3570. position.x = te[ 12 ];
  3571. position.y = te[ 13 ];
  3572. position.z = te[ 14 ];
  3573. // scale the rotation part
  3574. _m1.copy( this );
  3575. const invSX = 1 / sx;
  3576. const invSY = 1 / sy;
  3577. const invSZ = 1 / sz;
  3578. _m1.elements[ 0 ] *= invSX;
  3579. _m1.elements[ 1 ] *= invSX;
  3580. _m1.elements[ 2 ] *= invSX;
  3581. _m1.elements[ 4 ] *= invSY;
  3582. _m1.elements[ 5 ] *= invSY;
  3583. _m1.elements[ 6 ] *= invSY;
  3584. _m1.elements[ 8 ] *= invSZ;
  3585. _m1.elements[ 9 ] *= invSZ;
  3586. _m1.elements[ 10 ] *= invSZ;
  3587. quaternion.setFromRotationMatrix( _m1 );
  3588. scale.x = sx;
  3589. scale.y = sy;
  3590. scale.z = sz;
  3591. return this;
  3592. }
  3593. makePerspective( left, right, top, bottom, near, far ) {
  3594. if ( far === undefined ) {
  3595. console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' );
  3596. }
  3597. const te = this.elements;
  3598. const x = 2 * near / ( right - left );
  3599. const y = 2 * near / ( top - bottom );
  3600. const a = ( right + left ) / ( right - left );
  3601. const b = ( top + bottom ) / ( top - bottom );
  3602. const c = - ( far + near ) / ( far - near );
  3603. const d = - 2 * far * near / ( far - near );
  3604. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  3605. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  3606. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  3607. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  3608. return this;
  3609. }
  3610. makeOrthographic( left, right, top, bottom, near, far ) {
  3611. const te = this.elements;
  3612. const w = 1.0 / ( right - left );
  3613. const h = 1.0 / ( top - bottom );
  3614. const p = 1.0 / ( far - near );
  3615. const x = ( right + left ) * w;
  3616. const y = ( top + bottom ) * h;
  3617. const z = ( far + near ) * p;
  3618. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  3619. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  3620. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  3621. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  3622. return this;
  3623. }
  3624. equals( matrix ) {
  3625. const te = this.elements;
  3626. const me = matrix.elements;
  3627. for ( let i = 0; i < 16; i ++ ) {
  3628. if ( te[ i ] !== me[ i ] ) return false;
  3629. }
  3630. return true;
  3631. }
  3632. fromArray( array, offset = 0 ) {
  3633. for ( let i = 0; i < 16; i ++ ) {
  3634. this.elements[ i ] = array[ i + offset ];
  3635. }
  3636. return this;
  3637. }
  3638. toArray( array = [], offset = 0 ) {
  3639. const te = this.elements;
  3640. array[ offset ] = te[ 0 ];
  3641. array[ offset + 1 ] = te[ 1 ];
  3642. array[ offset + 2 ] = te[ 2 ];
  3643. array[ offset + 3 ] = te[ 3 ];
  3644. array[ offset + 4 ] = te[ 4 ];
  3645. array[ offset + 5 ] = te[ 5 ];
  3646. array[ offset + 6 ] = te[ 6 ];
  3647. array[ offset + 7 ] = te[ 7 ];
  3648. array[ offset + 8 ] = te[ 8 ];
  3649. array[ offset + 9 ] = te[ 9 ];
  3650. array[ offset + 10 ] = te[ 10 ];
  3651. array[ offset + 11 ] = te[ 11 ];
  3652. array[ offset + 12 ] = te[ 12 ];
  3653. array[ offset + 13 ] = te[ 13 ];
  3654. array[ offset + 14 ] = te[ 14 ];
  3655. array[ offset + 15 ] = te[ 15 ];
  3656. return array;
  3657. }
  3658. }
  3659. Matrix4.prototype.isMatrix4 = true;
  3660. const _v1$1 = /*@__PURE__*/ new Vector3();
  3661. const _m1 = /*@__PURE__*/ new Matrix4();
  3662. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  3663. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  3664. const _x = /*@__PURE__*/ new Vector3();
  3665. const _y = /*@__PURE__*/ new Vector3();
  3666. const _z = /*@__PURE__*/ new Vector3();
  3667. const _matrix = /*@__PURE__*/ new Matrix4();
  3668. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  3669. class Euler {
  3670. constructor( x = 0, y = 0, z = 0, order = Euler.DefaultOrder ) {
  3671. this._x = x;
  3672. this._y = y;
  3673. this._z = z;
  3674. this._order = order;
  3675. }
  3676. get x() {
  3677. return this._x;
  3678. }
  3679. set x( value ) {
  3680. this._x = value;
  3681. this._onChangeCallback();
  3682. }
  3683. get y() {
  3684. return this._y;
  3685. }
  3686. set y( value ) {
  3687. this._y = value;
  3688. this._onChangeCallback();
  3689. }
  3690. get z() {
  3691. return this._z;
  3692. }
  3693. set z( value ) {
  3694. this._z = value;
  3695. this._onChangeCallback();
  3696. }
  3697. get order() {
  3698. return this._order;
  3699. }
  3700. set order( value ) {
  3701. this._order = value;
  3702. this._onChangeCallback();
  3703. }
  3704. set( x, y, z, order ) {
  3705. this._x = x;
  3706. this._y = y;
  3707. this._z = z;
  3708. this._order = order || this._order;
  3709. this._onChangeCallback();
  3710. return this;
  3711. }
  3712. clone() {
  3713. return new this.constructor( this._x, this._y, this._z, this._order );
  3714. }
  3715. copy( euler ) {
  3716. this._x = euler._x;
  3717. this._y = euler._y;
  3718. this._z = euler._z;
  3719. this._order = euler._order;
  3720. this._onChangeCallback();
  3721. return this;
  3722. }
  3723. setFromRotationMatrix( m, order, update ) {
  3724. const clamp = MathUtils.clamp;
  3725. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3726. const te = m.elements;
  3727. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  3728. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  3729. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  3730. order = order || this._order;
  3731. switch ( order ) {
  3732. case 'XYZ':
  3733. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  3734. if ( Math.abs( m13 ) < 0.9999999 ) {
  3735. this._x = Math.atan2( - m23, m33 );
  3736. this._z = Math.atan2( - m12, m11 );
  3737. } else {
  3738. this._x = Math.atan2( m32, m22 );
  3739. this._z = 0;
  3740. }
  3741. break;
  3742. case 'YXZ':
  3743. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  3744. if ( Math.abs( m23 ) < 0.9999999 ) {
  3745. this._y = Math.atan2( m13, m33 );
  3746. this._z = Math.atan2( m21, m22 );
  3747. } else {
  3748. this._y = Math.atan2( - m31, m11 );
  3749. this._z = 0;
  3750. }
  3751. break;
  3752. case 'ZXY':
  3753. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  3754. if ( Math.abs( m32 ) < 0.9999999 ) {
  3755. this._y = Math.atan2( - m31, m33 );
  3756. this._z = Math.atan2( - m12, m22 );
  3757. } else {
  3758. this._y = 0;
  3759. this._z = Math.atan2( m21, m11 );
  3760. }
  3761. break;
  3762. case 'ZYX':
  3763. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  3764. if ( Math.abs( m31 ) < 0.9999999 ) {
  3765. this._x = Math.atan2( m32, m33 );
  3766. this._z = Math.atan2( m21, m11 );
  3767. } else {
  3768. this._x = 0;
  3769. this._z = Math.atan2( - m12, m22 );
  3770. }
  3771. break;
  3772. case 'YZX':
  3773. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  3774. if ( Math.abs( m21 ) < 0.9999999 ) {
  3775. this._x = Math.atan2( - m23, m22 );
  3776. this._y = Math.atan2( - m31, m11 );
  3777. } else {
  3778. this._x = 0;
  3779. this._y = Math.atan2( m13, m33 );
  3780. }
  3781. break;
  3782. case 'XZY':
  3783. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  3784. if ( Math.abs( m12 ) < 0.9999999 ) {
  3785. this._x = Math.atan2( m32, m22 );
  3786. this._y = Math.atan2( m13, m11 );
  3787. } else {
  3788. this._x = Math.atan2( - m23, m33 );
  3789. this._y = 0;
  3790. }
  3791. break;
  3792. default:
  3793. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  3794. }
  3795. this._order = order;
  3796. if ( update !== false ) this._onChangeCallback();
  3797. return this;
  3798. }
  3799. setFromQuaternion( q, order, update ) {
  3800. _matrix.makeRotationFromQuaternion( q );
  3801. return this.setFromRotationMatrix( _matrix, order, update );
  3802. }
  3803. setFromVector3( v, order ) {
  3804. return this.set( v.x, v.y, v.z, order || this._order );
  3805. }
  3806. reorder( newOrder ) {
  3807. // WARNING: this discards revolution information -bhouston
  3808. _quaternion$1.setFromEuler( this );
  3809. return this.setFromQuaternion( _quaternion$1, newOrder );
  3810. }
  3811. equals( euler ) {
  3812. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  3813. }
  3814. fromArray( array ) {
  3815. this._x = array[ 0 ];
  3816. this._y = array[ 1 ];
  3817. this._z = array[ 2 ];
  3818. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  3819. this._onChangeCallback();
  3820. return this;
  3821. }
  3822. toArray( array = [], offset = 0 ) {
  3823. array[ offset ] = this._x;
  3824. array[ offset + 1 ] = this._y;
  3825. array[ offset + 2 ] = this._z;
  3826. array[ offset + 3 ] = this._order;
  3827. return array;
  3828. }
  3829. toVector3( optionalResult ) {
  3830. if ( optionalResult ) {
  3831. return optionalResult.set( this._x, this._y, this._z );
  3832. } else {
  3833. return new Vector3( this._x, this._y, this._z );
  3834. }
  3835. }
  3836. _onChange( callback ) {
  3837. this._onChangeCallback = callback;
  3838. return this;
  3839. }
  3840. _onChangeCallback() {}
  3841. }
  3842. Euler.prototype.isEuler = true;
  3843. Euler.DefaultOrder = 'XYZ';
  3844. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  3845. class Layers {
  3846. constructor() {
  3847. this.mask = 1 | 0;
  3848. }
  3849. set( channel ) {
  3850. this.mask = 1 << channel | 0;
  3851. }
  3852. enable( channel ) {
  3853. this.mask |= 1 << channel | 0;
  3854. }
  3855. enableAll() {
  3856. this.mask = 0xffffffff | 0;
  3857. }
  3858. toggle( channel ) {
  3859. this.mask ^= 1 << channel | 0;
  3860. }
  3861. disable( channel ) {
  3862. this.mask &= ~ ( 1 << channel | 0 );
  3863. }
  3864. disableAll() {
  3865. this.mask = 0;
  3866. }
  3867. test( layers ) {
  3868. return ( this.mask & layers.mask ) !== 0;
  3869. }
  3870. }
  3871. let _object3DId = 0;
  3872. const _v1$2 = new Vector3();
  3873. const _q1 = new Quaternion();
  3874. const _m1$1 = new Matrix4();
  3875. const _target = new Vector3();
  3876. const _position = new Vector3();
  3877. const _scale = new Vector3();
  3878. const _quaternion$2 = new Quaternion();
  3879. const _xAxis = new Vector3( 1, 0, 0 );
  3880. const _yAxis = new Vector3( 0, 1, 0 );
  3881. const _zAxis = new Vector3( 0, 0, 1 );
  3882. const _addedEvent = { type: 'added' };
  3883. const _removedEvent = { type: 'removed' };
  3884. function Object3D() {
  3885. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  3886. this.uuid = MathUtils.generateUUID();
  3887. this.name = '';
  3888. this.type = 'Object3D';
  3889. this.parent = null;
  3890. this.children = [];
  3891. this.up = Object3D.DefaultUp.clone();
  3892. const position = new Vector3();
  3893. const rotation = new Euler();
  3894. const quaternion = new Quaternion();
  3895. const scale = new Vector3( 1, 1, 1 );
  3896. function onRotationChange() {
  3897. quaternion.setFromEuler( rotation, false );
  3898. }
  3899. function onQuaternionChange() {
  3900. rotation.setFromQuaternion( quaternion, undefined, false );
  3901. }
  3902. rotation._onChange( onRotationChange );
  3903. quaternion._onChange( onQuaternionChange );
  3904. Object.defineProperties( this, {
  3905. position: {
  3906. configurable: true,
  3907. enumerable: true,
  3908. value: position
  3909. },
  3910. rotation: {
  3911. configurable: true,
  3912. enumerable: true,
  3913. value: rotation
  3914. },
  3915. quaternion: {
  3916. configurable: true,
  3917. enumerable: true,
  3918. value: quaternion
  3919. },
  3920. scale: {
  3921. configurable: true,
  3922. enumerable: true,
  3923. value: scale
  3924. },
  3925. modelViewMatrix: {
  3926. value: new Matrix4()
  3927. },
  3928. normalMatrix: {
  3929. value: new Matrix3()
  3930. }
  3931. } );
  3932. this.matrix = new Matrix4();
  3933. this.matrixWorld = new Matrix4();
  3934. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  3935. this.matrixWorldNeedsUpdate = false;
  3936. this.layers = new Layers();
  3937. this.visible = true;
  3938. this.castShadow = false;
  3939. this.receiveShadow = false;
  3940. this.frustumCulled = true;
  3941. this.renderOrder = 0;
  3942. this.animations = [];
  3943. this.userData = {};
  3944. }
  3945. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  3946. Object3D.DefaultMatrixAutoUpdate = true;
  3947. Object3D.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  3948. constructor: Object3D,
  3949. isObject3D: true,
  3950. onBeforeRender: function () {},
  3951. onAfterRender: function () {},
  3952. applyMatrix4: function ( matrix ) {
  3953. if ( this.matrixAutoUpdate ) this.updateMatrix();
  3954. this.matrix.premultiply( matrix );
  3955. this.matrix.decompose( this.position, this.quaternion, this.scale );
  3956. },
  3957. applyQuaternion: function ( q ) {
  3958. this.quaternion.premultiply( q );
  3959. return this;
  3960. },
  3961. setRotationFromAxisAngle: function ( axis, angle ) {
  3962. // assumes axis is normalized
  3963. this.quaternion.setFromAxisAngle( axis, angle );
  3964. },
  3965. setRotationFromEuler: function ( euler ) {
  3966. this.quaternion.setFromEuler( euler, true );
  3967. },
  3968. setRotationFromMatrix: function ( m ) {
  3969. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3970. this.quaternion.setFromRotationMatrix( m );
  3971. },
  3972. setRotationFromQuaternion: function ( q ) {
  3973. // assumes q is normalized
  3974. this.quaternion.copy( q );
  3975. },
  3976. rotateOnAxis: function ( axis, angle ) {
  3977. // rotate object on axis in object space
  3978. // axis is assumed to be normalized
  3979. _q1.setFromAxisAngle( axis, angle );
  3980. this.quaternion.multiply( _q1 );
  3981. return this;
  3982. },
  3983. rotateOnWorldAxis: function ( axis, angle ) {
  3984. // rotate object on axis in world space
  3985. // axis is assumed to be normalized
  3986. // method assumes no rotated parent
  3987. _q1.setFromAxisAngle( axis, angle );
  3988. this.quaternion.premultiply( _q1 );
  3989. return this;
  3990. },
  3991. rotateX: function ( angle ) {
  3992. return this.rotateOnAxis( _xAxis, angle );
  3993. },
  3994. rotateY: function ( angle ) {
  3995. return this.rotateOnAxis( _yAxis, angle );
  3996. },
  3997. rotateZ: function ( angle ) {
  3998. return this.rotateOnAxis( _zAxis, angle );
  3999. },
  4000. translateOnAxis: function ( axis, distance ) {
  4001. // translate object by distance along axis in object space
  4002. // axis is assumed to be normalized
  4003. _v1$2.copy( axis ).applyQuaternion( this.quaternion );
  4004. this.position.add( _v1$2.multiplyScalar( distance ) );
  4005. return this;
  4006. },
  4007. translateX: function ( distance ) {
  4008. return this.translateOnAxis( _xAxis, distance );
  4009. },
  4010. translateY: function ( distance ) {
  4011. return this.translateOnAxis( _yAxis, distance );
  4012. },
  4013. translateZ: function ( distance ) {
  4014. return this.translateOnAxis( _zAxis, distance );
  4015. },
  4016. localToWorld: function ( vector ) {
  4017. return vector.applyMatrix4( this.matrixWorld );
  4018. },
  4019. worldToLocal: function ( vector ) {
  4020. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  4021. },
  4022. lookAt: function ( x, y, z ) {
  4023. // This method does not support objects having non-uniformly-scaled parent(s)
  4024. if ( x.isVector3 ) {
  4025. _target.copy( x );
  4026. } else {
  4027. _target.set( x, y, z );
  4028. }
  4029. const parent = this.parent;
  4030. this.updateWorldMatrix( true, false );
  4031. _position.setFromMatrixPosition( this.matrixWorld );
  4032. if ( this.isCamera || this.isLight ) {
  4033. _m1$1.lookAt( _position, _target, this.up );
  4034. } else {
  4035. _m1$1.lookAt( _target, _position, this.up );
  4036. }
  4037. this.quaternion.setFromRotationMatrix( _m1$1 );
  4038. if ( parent ) {
  4039. _m1$1.extractRotation( parent.matrixWorld );
  4040. _q1.setFromRotationMatrix( _m1$1 );
  4041. this.quaternion.premultiply( _q1.invert() );
  4042. }
  4043. },
  4044. add: function ( object ) {
  4045. if ( arguments.length > 1 ) {
  4046. for ( let i = 0; i < arguments.length; i ++ ) {
  4047. this.add( arguments[ i ] );
  4048. }
  4049. return this;
  4050. }
  4051. if ( object === this ) {
  4052. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4053. return this;
  4054. }
  4055. if ( object && object.isObject3D ) {
  4056. if ( object.parent !== null ) {
  4057. object.parent.remove( object );
  4058. }
  4059. object.parent = this;
  4060. this.children.push( object );
  4061. object.dispatchEvent( _addedEvent );
  4062. } else {
  4063. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4064. }
  4065. return this;
  4066. },
  4067. remove: function ( object ) {
  4068. if ( arguments.length > 1 ) {
  4069. for ( let i = 0; i < arguments.length; i ++ ) {
  4070. this.remove( arguments[ i ] );
  4071. }
  4072. return this;
  4073. }
  4074. const index = this.children.indexOf( object );
  4075. if ( index !== - 1 ) {
  4076. object.parent = null;
  4077. this.children.splice( index, 1 );
  4078. object.dispatchEvent( _removedEvent );
  4079. }
  4080. return this;
  4081. },
  4082. clear: function () {
  4083. for ( let i = 0; i < this.children.length; i ++ ) {
  4084. const object = this.children[ i ];
  4085. object.parent = null;
  4086. object.dispatchEvent( _removedEvent );
  4087. }
  4088. this.children.length = 0;
  4089. return this;
  4090. },
  4091. attach: function ( object ) {
  4092. // adds object as a child of this, while maintaining the object's world transform
  4093. this.updateWorldMatrix( true, false );
  4094. _m1$1.copy( this.matrixWorld ).invert();
  4095. if ( object.parent !== null ) {
  4096. object.parent.updateWorldMatrix( true, false );
  4097. _m1$1.multiply( object.parent.matrixWorld );
  4098. }
  4099. object.applyMatrix4( _m1$1 );
  4100. this.add( object );
  4101. object.updateWorldMatrix( false, true );
  4102. return this;
  4103. },
  4104. getObjectById: function ( id ) {
  4105. return this.getObjectByProperty( 'id', id );
  4106. },
  4107. getObjectByName: function ( name ) {
  4108. return this.getObjectByProperty( 'name', name );
  4109. },
  4110. getObjectByProperty: function ( name, value ) {
  4111. if ( this[ name ] === value ) return this;
  4112. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4113. const child = this.children[ i ];
  4114. const object = child.getObjectByProperty( name, value );
  4115. if ( object !== undefined ) {
  4116. return object;
  4117. }
  4118. }
  4119. return undefined;
  4120. },
  4121. getWorldPosition: function ( target ) {
  4122. if ( target === undefined ) {
  4123. console.warn( 'THREE.Object3D: .getWorldPosition() target is now required' );
  4124. target = new Vector3();
  4125. }
  4126. this.updateWorldMatrix( true, false );
  4127. return target.setFromMatrixPosition( this.matrixWorld );
  4128. },
  4129. getWorldQuaternion: function ( target ) {
  4130. if ( target === undefined ) {
  4131. console.warn( 'THREE.Object3D: .getWorldQuaternion() target is now required' );
  4132. target = new Quaternion();
  4133. }
  4134. this.updateWorldMatrix( true, false );
  4135. this.matrixWorld.decompose( _position, target, _scale );
  4136. return target;
  4137. },
  4138. getWorldScale: function ( target ) {
  4139. if ( target === undefined ) {
  4140. console.warn( 'THREE.Object3D: .getWorldScale() target is now required' );
  4141. target = new Vector3();
  4142. }
  4143. this.updateWorldMatrix( true, false );
  4144. this.matrixWorld.decompose( _position, _quaternion$2, target );
  4145. return target;
  4146. },
  4147. getWorldDirection: function ( target ) {
  4148. if ( target === undefined ) {
  4149. console.warn( 'THREE.Object3D: .getWorldDirection() target is now required' );
  4150. target = new Vector3();
  4151. }
  4152. this.updateWorldMatrix( true, false );
  4153. const e = this.matrixWorld.elements;
  4154. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4155. },
  4156. raycast: function () {},
  4157. traverse: function ( callback ) {
  4158. callback( this );
  4159. const children = this.children;
  4160. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4161. children[ i ].traverse( callback );
  4162. }
  4163. },
  4164. traverseVisible: function ( callback ) {
  4165. if ( this.visible === false ) return;
  4166. callback( this );
  4167. const children = this.children;
  4168. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4169. children[ i ].traverseVisible( callback );
  4170. }
  4171. },
  4172. traverseAncestors: function ( callback ) {
  4173. const parent = this.parent;
  4174. if ( parent !== null ) {
  4175. callback( parent );
  4176. parent.traverseAncestors( callback );
  4177. }
  4178. },
  4179. updateMatrix: function () {
  4180. this.matrix.compose( this.position, this.quaternion, this.scale );
  4181. this.matrixWorldNeedsUpdate = true;
  4182. },
  4183. updateMatrixWorld: function ( force ) {
  4184. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4185. if ( this.matrixWorldNeedsUpdate || force ) {
  4186. if ( this.parent === null ) {
  4187. this.matrixWorld.copy( this.matrix );
  4188. } else {
  4189. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4190. }
  4191. this.matrixWorldNeedsUpdate = false;
  4192. force = true;
  4193. }
  4194. // update children
  4195. const children = this.children;
  4196. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4197. children[ i ].updateMatrixWorld( force );
  4198. }
  4199. },
  4200. updateWorldMatrix: function ( updateParents, updateChildren ) {
  4201. const parent = this.parent;
  4202. if ( updateParents === true && parent !== null ) {
  4203. parent.updateWorldMatrix( true, false );
  4204. }
  4205. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4206. if ( this.parent === null ) {
  4207. this.matrixWorld.copy( this.matrix );
  4208. } else {
  4209. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4210. }
  4211. // update children
  4212. if ( updateChildren === true ) {
  4213. const children = this.children;
  4214. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4215. children[ i ].updateWorldMatrix( false, true );
  4216. }
  4217. }
  4218. },
  4219. toJSON: function ( meta ) {
  4220. // meta is a string when called from JSON.stringify
  4221. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4222. const output = {};
  4223. // meta is a hash used to collect geometries, materials.
  4224. // not providing it implies that this is the root object
  4225. // being serialized.
  4226. if ( isRootObject ) {
  4227. // initialize meta obj
  4228. meta = {
  4229. geometries: {},
  4230. materials: {},
  4231. textures: {},
  4232. images: {},
  4233. shapes: {},
  4234. skeletons: {},
  4235. animations: {}
  4236. };
  4237. output.metadata = {
  4238. version: 4.5,
  4239. type: 'Object',
  4240. generator: 'Object3D.toJSON'
  4241. };
  4242. }
  4243. // standard Object3D serialization
  4244. const object = {};
  4245. object.uuid = this.uuid;
  4246. object.type = this.type;
  4247. if ( this.name !== '' ) object.name = this.name;
  4248. if ( this.castShadow === true ) object.castShadow = true;
  4249. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4250. if ( this.visible === false ) object.visible = false;
  4251. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4252. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4253. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  4254. object.layers = this.layers.mask;
  4255. object.matrix = this.matrix.toArray();
  4256. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4257. // object specific properties
  4258. if ( this.isInstancedMesh ) {
  4259. object.type = 'InstancedMesh';
  4260. object.count = this.count;
  4261. object.instanceMatrix = this.instanceMatrix.toJSON();
  4262. }
  4263. //
  4264. function serialize( library, element ) {
  4265. if ( library[ element.uuid ] === undefined ) {
  4266. library[ element.uuid ] = element.toJSON( meta );
  4267. }
  4268. return element.uuid;
  4269. }
  4270. if ( this.isMesh || this.isLine || this.isPoints ) {
  4271. object.geometry = serialize( meta.geometries, this.geometry );
  4272. const parameters = this.geometry.parameters;
  4273. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4274. const shapes = parameters.shapes;
  4275. if ( Array.isArray( shapes ) ) {
  4276. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4277. const shape = shapes[ i ];
  4278. serialize( meta.shapes, shape );
  4279. }
  4280. } else {
  4281. serialize( meta.shapes, shapes );
  4282. }
  4283. }
  4284. }
  4285. if ( this.isSkinnedMesh ) {
  4286. object.bindMode = this.bindMode;
  4287. object.bindMatrix = this.bindMatrix.toArray();
  4288. if ( this.skeleton !== undefined ) {
  4289. serialize( meta.skeletons, this.skeleton );
  4290. object.skeleton = this.skeleton.uuid;
  4291. }
  4292. }
  4293. if ( this.material !== undefined ) {
  4294. if ( Array.isArray( this.material ) ) {
  4295. const uuids = [];
  4296. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4297. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4298. }
  4299. object.material = uuids;
  4300. } else {
  4301. object.material = serialize( meta.materials, this.material );
  4302. }
  4303. }
  4304. //
  4305. if ( this.children.length > 0 ) {
  4306. object.children = [];
  4307. for ( let i = 0; i < this.children.length; i ++ ) {
  4308. object.children.push( this.children[ i ].toJSON( meta ).object );
  4309. }
  4310. }
  4311. //
  4312. if ( this.animations.length > 0 ) {
  4313. object.animations = [];
  4314. for ( let i = 0; i < this.animations.length; i ++ ) {
  4315. const animation = this.animations[ i ];
  4316. object.animations.push( serialize( meta.animations, animation ) );
  4317. }
  4318. }
  4319. if ( isRootObject ) {
  4320. const geometries = extractFromCache( meta.geometries );
  4321. const materials = extractFromCache( meta.materials );
  4322. const textures = extractFromCache( meta.textures );
  4323. const images = extractFromCache( meta.images );
  4324. const shapes = extractFromCache( meta.shapes );
  4325. const skeletons = extractFromCache( meta.skeletons );
  4326. const animations = extractFromCache( meta.animations );
  4327. if ( geometries.length > 0 ) output.geometries = geometries;
  4328. if ( materials.length > 0 ) output.materials = materials;
  4329. if ( textures.length > 0 ) output.textures = textures;
  4330. if ( images.length > 0 ) output.images = images;
  4331. if ( shapes.length > 0 ) output.shapes = shapes;
  4332. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4333. if ( animations.length > 0 ) output.animations = animations;
  4334. }
  4335. output.object = object;
  4336. return output;
  4337. // extract data from the cache hash
  4338. // remove metadata on each item
  4339. // and return as array
  4340. function extractFromCache( cache ) {
  4341. const values = [];
  4342. for ( const key in cache ) {
  4343. const data = cache[ key ];
  4344. delete data.metadata;
  4345. values.push( data );
  4346. }
  4347. return values;
  4348. }
  4349. },
  4350. clone: function ( recursive ) {
  4351. return new this.constructor().copy( this, recursive );
  4352. },
  4353. copy: function ( source, recursive = true ) {
  4354. this.name = source.name;
  4355. this.up.copy( source.up );
  4356. this.position.copy( source.position );
  4357. this.rotation.order = source.rotation.order;
  4358. this.quaternion.copy( source.quaternion );
  4359. this.scale.copy( source.scale );
  4360. this.matrix.copy( source.matrix );
  4361. this.matrixWorld.copy( source.matrixWorld );
  4362. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4363. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4364. this.layers.mask = source.layers.mask;
  4365. this.visible = source.visible;
  4366. this.castShadow = source.castShadow;
  4367. this.receiveShadow = source.receiveShadow;
  4368. this.frustumCulled = source.frustumCulled;
  4369. this.renderOrder = source.renderOrder;
  4370. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4371. if ( recursive === true ) {
  4372. for ( let i = 0; i < source.children.length; i ++ ) {
  4373. const child = source.children[ i ];
  4374. this.add( child.clone() );
  4375. }
  4376. }
  4377. return this;
  4378. }
  4379. } );
  4380. const _vector1 = /*@__PURE__*/ new Vector3();
  4381. const _vector2 = /*@__PURE__*/ new Vector3();
  4382. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  4383. class Plane {
  4384. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  4385. // normal is assumed to be normalized
  4386. this.normal = normal;
  4387. this.constant = constant;
  4388. }
  4389. set( normal, constant ) {
  4390. this.normal.copy( normal );
  4391. this.constant = constant;
  4392. return this;
  4393. }
  4394. setComponents( x, y, z, w ) {
  4395. this.normal.set( x, y, z );
  4396. this.constant = w;
  4397. return this;
  4398. }
  4399. setFromNormalAndCoplanarPoint( normal, point ) {
  4400. this.normal.copy( normal );
  4401. this.constant = - point.dot( this.normal );
  4402. return this;
  4403. }
  4404. setFromCoplanarPoints( a, b, c ) {
  4405. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  4406. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  4407. this.setFromNormalAndCoplanarPoint( normal, a );
  4408. return this;
  4409. }
  4410. copy( plane ) {
  4411. this.normal.copy( plane.normal );
  4412. this.constant = plane.constant;
  4413. return this;
  4414. }
  4415. normalize() {
  4416. // Note: will lead to a divide by zero if the plane is invalid.
  4417. const inverseNormalLength = 1.0 / this.normal.length();
  4418. this.normal.multiplyScalar( inverseNormalLength );
  4419. this.constant *= inverseNormalLength;
  4420. return this;
  4421. }
  4422. negate() {
  4423. this.constant *= - 1;
  4424. this.normal.negate();
  4425. return this;
  4426. }
  4427. distanceToPoint( point ) {
  4428. return this.normal.dot( point ) + this.constant;
  4429. }
  4430. distanceToSphere( sphere ) {
  4431. return this.distanceToPoint( sphere.center ) - sphere.radius;
  4432. }
  4433. projectPoint( point, target ) {
  4434. if ( target === undefined ) {
  4435. console.warn( 'THREE.Plane: .projectPoint() target is now required' );
  4436. target = new Vector3();
  4437. }
  4438. return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point );
  4439. }
  4440. intersectLine( line, target ) {
  4441. if ( target === undefined ) {
  4442. console.warn( 'THREE.Plane: .intersectLine() target is now required' );
  4443. target = new Vector3();
  4444. }
  4445. const direction = line.delta( _vector1 );
  4446. const denominator = this.normal.dot( direction );
  4447. if ( denominator === 0 ) {
  4448. // line is coplanar, return origin
  4449. if ( this.distanceToPoint( line.start ) === 0 ) {
  4450. return target.copy( line.start );
  4451. }
  4452. // Unsure if this is the correct method to handle this case.
  4453. return undefined;
  4454. }
  4455. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  4456. if ( t < 0 || t > 1 ) {
  4457. return undefined;
  4458. }
  4459. return target.copy( direction ).multiplyScalar( t ).add( line.start );
  4460. }
  4461. intersectsLine( line ) {
  4462. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  4463. const startSign = this.distanceToPoint( line.start );
  4464. const endSign = this.distanceToPoint( line.end );
  4465. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  4466. }
  4467. intersectsBox( box ) {
  4468. return box.intersectsPlane( this );
  4469. }
  4470. intersectsSphere( sphere ) {
  4471. return sphere.intersectsPlane( this );
  4472. }
  4473. coplanarPoint( target ) {
  4474. if ( target === undefined ) {
  4475. console.warn( 'THREE.Plane: .coplanarPoint() target is now required' );
  4476. target = new Vector3();
  4477. }
  4478. return target.copy( this.normal ).multiplyScalar( - this.constant );
  4479. }
  4480. applyMatrix4( matrix, optionalNormalMatrix ) {
  4481. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  4482. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  4483. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  4484. this.constant = - referencePoint.dot( normal );
  4485. return this;
  4486. }
  4487. translate( offset ) {
  4488. this.constant -= offset.dot( this.normal );
  4489. return this;
  4490. }
  4491. equals( plane ) {
  4492. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  4493. }
  4494. clone() {
  4495. return new this.constructor().copy( this );
  4496. }
  4497. }
  4498. Plane.prototype.isPlane = true;
  4499. const _v0$1 = /*@__PURE__*/ new Vector3();
  4500. const _v1$3 = /*@__PURE__*/ new Vector3();
  4501. const _v2$1 = /*@__PURE__*/ new Vector3();
  4502. const _v3 = /*@__PURE__*/ new Vector3();
  4503. const _vab = /*@__PURE__*/ new Vector3();
  4504. const _vac = /*@__PURE__*/ new Vector3();
  4505. const _vbc = /*@__PURE__*/ new Vector3();
  4506. const _vap = /*@__PURE__*/ new Vector3();
  4507. const _vbp = /*@__PURE__*/ new Vector3();
  4508. const _vcp = /*@__PURE__*/ new Vector3();
  4509. class Triangle {
  4510. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  4511. this.a = a;
  4512. this.b = b;
  4513. this.c = c;
  4514. }
  4515. static getNormal( a, b, c, target ) {
  4516. if ( target === undefined ) {
  4517. console.warn( 'THREE.Triangle: .getNormal() target is now required' );
  4518. target = new Vector3();
  4519. }
  4520. target.subVectors( c, b );
  4521. _v0$1.subVectors( a, b );
  4522. target.cross( _v0$1 );
  4523. const targetLengthSq = target.lengthSq();
  4524. if ( targetLengthSq > 0 ) {
  4525. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  4526. }
  4527. return target.set( 0, 0, 0 );
  4528. }
  4529. // static/instance method to calculate barycentric coordinates
  4530. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4531. static getBarycoord( point, a, b, c, target ) {
  4532. _v0$1.subVectors( c, a );
  4533. _v1$3.subVectors( b, a );
  4534. _v2$1.subVectors( point, a );
  4535. const dot00 = _v0$1.dot( _v0$1 );
  4536. const dot01 = _v0$1.dot( _v1$3 );
  4537. const dot02 = _v0$1.dot( _v2$1 );
  4538. const dot11 = _v1$3.dot( _v1$3 );
  4539. const dot12 = _v1$3.dot( _v2$1 );
  4540. const denom = ( dot00 * dot11 - dot01 * dot01 );
  4541. if ( target === undefined ) {
  4542. console.warn( 'THREE.Triangle: .getBarycoord() target is now required' );
  4543. target = new Vector3();
  4544. }
  4545. // collinear or singular triangle
  4546. if ( denom === 0 ) {
  4547. // arbitrary location outside of triangle?
  4548. // not sure if this is the best idea, maybe should be returning undefined
  4549. return target.set( - 2, - 1, - 1 );
  4550. }
  4551. const invDenom = 1 / denom;
  4552. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4553. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4554. // barycentric coordinates must always sum to 1
  4555. return target.set( 1 - u - v, v, u );
  4556. }
  4557. static containsPoint( point, a, b, c ) {
  4558. this.getBarycoord( point, a, b, c, _v3 );
  4559. return ( _v3.x >= 0 ) && ( _v3.y >= 0 ) && ( ( _v3.x + _v3.y ) <= 1 );
  4560. }
  4561. static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) {
  4562. this.getBarycoord( point, p1, p2, p3, _v3 );
  4563. target.set( 0, 0 );
  4564. target.addScaledVector( uv1, _v3.x );
  4565. target.addScaledVector( uv2, _v3.y );
  4566. target.addScaledVector( uv3, _v3.z );
  4567. return target;
  4568. }
  4569. static isFrontFacing( a, b, c, direction ) {
  4570. _v0$1.subVectors( c, b );
  4571. _v1$3.subVectors( a, b );
  4572. // strictly front facing
  4573. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  4574. }
  4575. set( a, b, c ) {
  4576. this.a.copy( a );
  4577. this.b.copy( b );
  4578. this.c.copy( c );
  4579. return this;
  4580. }
  4581. setFromPointsAndIndices( points, i0, i1, i2 ) {
  4582. this.a.copy( points[ i0 ] );
  4583. this.b.copy( points[ i1 ] );
  4584. this.c.copy( points[ i2 ] );
  4585. return this;
  4586. }
  4587. clone() {
  4588. return new this.constructor().copy( this );
  4589. }
  4590. copy( triangle ) {
  4591. this.a.copy( triangle.a );
  4592. this.b.copy( triangle.b );
  4593. this.c.copy( triangle.c );
  4594. return this;
  4595. }
  4596. getArea() {
  4597. _v0$1.subVectors( this.c, this.b );
  4598. _v1$3.subVectors( this.a, this.b );
  4599. return _v0$1.cross( _v1$3 ).length() * 0.5;
  4600. }
  4601. getMidpoint( target ) {
  4602. if ( target === undefined ) {
  4603. console.warn( 'THREE.Triangle: .getMidpoint() target is now required' );
  4604. target = new Vector3();
  4605. }
  4606. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4607. }
  4608. getNormal( target ) {
  4609. return Triangle.getNormal( this.a, this.b, this.c, target );
  4610. }
  4611. getPlane( target ) {
  4612. if ( target === undefined ) {
  4613. console.warn( 'THREE.Triangle: .getPlane() target is now required' );
  4614. target = new Plane();
  4615. }
  4616. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  4617. }
  4618. getBarycoord( point, target ) {
  4619. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  4620. }
  4621. getUV( point, uv1, uv2, uv3, target ) {
  4622. return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target );
  4623. }
  4624. containsPoint( point ) {
  4625. return Triangle.containsPoint( point, this.a, this.b, this.c );
  4626. }
  4627. isFrontFacing( direction ) {
  4628. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  4629. }
  4630. intersectsBox( box ) {
  4631. return box.intersectsTriangle( this );
  4632. }
  4633. closestPointToPoint( p, target ) {
  4634. if ( target === undefined ) {
  4635. console.warn( 'THREE.Triangle: .closestPointToPoint() target is now required' );
  4636. target = new Vector3();
  4637. }
  4638. const a = this.a, b = this.b, c = this.c;
  4639. let v, w;
  4640. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  4641. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  4642. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  4643. // basically, we're distinguishing which of the voronoi regions of the triangle
  4644. // the point lies in with the minimum amount of redundant computation.
  4645. _vab.subVectors( b, a );
  4646. _vac.subVectors( c, a );
  4647. _vap.subVectors( p, a );
  4648. const d1 = _vab.dot( _vap );
  4649. const d2 = _vac.dot( _vap );
  4650. if ( d1 <= 0 && d2 <= 0 ) {
  4651. // vertex region of A; barycentric coords (1, 0, 0)
  4652. return target.copy( a );
  4653. }
  4654. _vbp.subVectors( p, b );
  4655. const d3 = _vab.dot( _vbp );
  4656. const d4 = _vac.dot( _vbp );
  4657. if ( d3 >= 0 && d4 <= d3 ) {
  4658. // vertex region of B; barycentric coords (0, 1, 0)
  4659. return target.copy( b );
  4660. }
  4661. const vc = d1 * d4 - d3 * d2;
  4662. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  4663. v = d1 / ( d1 - d3 );
  4664. // edge region of AB; barycentric coords (1-v, v, 0)
  4665. return target.copy( a ).addScaledVector( _vab, v );
  4666. }
  4667. _vcp.subVectors( p, c );
  4668. const d5 = _vab.dot( _vcp );
  4669. const d6 = _vac.dot( _vcp );
  4670. if ( d6 >= 0 && d5 <= d6 ) {
  4671. // vertex region of C; barycentric coords (0, 0, 1)
  4672. return target.copy( c );
  4673. }
  4674. const vb = d5 * d2 - d1 * d6;
  4675. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  4676. w = d2 / ( d2 - d6 );
  4677. // edge region of AC; barycentric coords (1-w, 0, w)
  4678. return target.copy( a ).addScaledVector( _vac, w );
  4679. }
  4680. const va = d3 * d6 - d5 * d4;
  4681. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  4682. _vbc.subVectors( c, b );
  4683. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  4684. // edge region of BC; barycentric coords (0, 1-w, w)
  4685. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  4686. }
  4687. // face region
  4688. const denom = 1 / ( va + vb + vc );
  4689. // u = va * denom
  4690. v = vb * denom;
  4691. w = vc * denom;
  4692. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  4693. }
  4694. equals( triangle ) {
  4695. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  4696. }
  4697. }
  4698. let materialId = 0;
  4699. function Material() {
  4700. Object.defineProperty( this, 'id', { value: materialId ++ } );
  4701. this.uuid = MathUtils.generateUUID();
  4702. this.name = '';
  4703. this.type = 'Material';
  4704. this.fog = true;
  4705. this.blending = NormalBlending;
  4706. this.side = FrontSide;
  4707. this.vertexColors = false;
  4708. this.opacity = 1;
  4709. this.transparent = false;
  4710. this.blendSrc = SrcAlphaFactor;
  4711. this.blendDst = OneMinusSrcAlphaFactor;
  4712. this.blendEquation = AddEquation;
  4713. this.blendSrcAlpha = null;
  4714. this.blendDstAlpha = null;
  4715. this.blendEquationAlpha = null;
  4716. this.depthFunc = LessEqualDepth;
  4717. this.depthTest = true;
  4718. this.depthWrite = true;
  4719. this.stencilWriteMask = 0xff;
  4720. this.stencilFunc = AlwaysStencilFunc;
  4721. this.stencilRef = 0;
  4722. this.stencilFuncMask = 0xff;
  4723. this.stencilFail = KeepStencilOp;
  4724. this.stencilZFail = KeepStencilOp;
  4725. this.stencilZPass = KeepStencilOp;
  4726. this.stencilWrite = false;
  4727. this.clippingPlanes = null;
  4728. this.clipIntersection = false;
  4729. this.clipShadows = false;
  4730. this.shadowSide = null;
  4731. this.colorWrite = true;
  4732. this.precision = null; // override the renderer's default precision for this material
  4733. this.polygonOffset = false;
  4734. this.polygonOffsetFactor = 0;
  4735. this.polygonOffsetUnits = 0;
  4736. this.dithering = false;
  4737. this.alphaTest = 0;
  4738. this.alphaToCoverage = false;
  4739. this.premultipliedAlpha = false;
  4740. this.visible = true;
  4741. this.toneMapped = true;
  4742. this.userData = {};
  4743. this.version = 0;
  4744. }
  4745. Material.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  4746. constructor: Material,
  4747. isMaterial: true,
  4748. onBeforeCompile: function ( /* shaderobject, renderer */ ) {},
  4749. customProgramCacheKey: function () {
  4750. return this.onBeforeCompile.toString();
  4751. },
  4752. setValues: function ( values ) {
  4753. if ( values === undefined ) return;
  4754. for ( const key in values ) {
  4755. const newValue = values[ key ];
  4756. if ( newValue === undefined ) {
  4757. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  4758. continue;
  4759. }
  4760. // for backward compatability if shading is set in the constructor
  4761. if ( key === 'shading' ) {
  4762. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  4763. this.flatShading = ( newValue === FlatShading ) ? true : false;
  4764. continue;
  4765. }
  4766. const currentValue = this[ key ];
  4767. if ( currentValue === undefined ) {
  4768. console.warn( 'THREE.' + this.type + ': \'' + key + '\' is not a property of this material.' );
  4769. continue;
  4770. }
  4771. if ( currentValue && currentValue.isColor ) {
  4772. currentValue.set( newValue );
  4773. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  4774. currentValue.copy( newValue );
  4775. } else {
  4776. this[ key ] = newValue;
  4777. }
  4778. }
  4779. },
  4780. toJSON: function ( meta ) {
  4781. const isRoot = ( meta === undefined || typeof meta === 'string' );
  4782. if ( isRoot ) {
  4783. meta = {
  4784. textures: {},
  4785. images: {}
  4786. };
  4787. }
  4788. const data = {
  4789. metadata: {
  4790. version: 4.5,
  4791. type: 'Material',
  4792. generator: 'Material.toJSON'
  4793. }
  4794. };
  4795. // standard Material serialization
  4796. data.uuid = this.uuid;
  4797. data.type = this.type;
  4798. if ( this.name !== '' ) data.name = this.name;
  4799. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  4800. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  4801. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  4802. if ( this.sheen && this.sheen.isColor ) data.sheen = this.sheen.getHex();
  4803. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  4804. if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  4805. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  4806. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  4807. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  4808. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  4809. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  4810. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  4811. }
  4812. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  4813. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  4814. }
  4815. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  4816. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  4817. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  4818. }
  4819. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  4820. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  4821. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  4822. if ( this.lightMap && this.lightMap.isTexture ) {
  4823. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  4824. data.lightMapIntensity = this.lightMapIntensity;
  4825. }
  4826. if ( this.aoMap && this.aoMap.isTexture ) {
  4827. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  4828. data.aoMapIntensity = this.aoMapIntensity;
  4829. }
  4830. if ( this.bumpMap && this.bumpMap.isTexture ) {
  4831. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  4832. data.bumpScale = this.bumpScale;
  4833. }
  4834. if ( this.normalMap && this.normalMap.isTexture ) {
  4835. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  4836. data.normalMapType = this.normalMapType;
  4837. data.normalScale = this.normalScale.toArray();
  4838. }
  4839. if ( this.displacementMap && this.displacementMap.isTexture ) {
  4840. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  4841. data.displacementScale = this.displacementScale;
  4842. data.displacementBias = this.displacementBias;
  4843. }
  4844. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  4845. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  4846. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  4847. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  4848. if ( this.envMap && this.envMap.isTexture ) {
  4849. data.envMap = this.envMap.toJSON( meta ).uuid;
  4850. data.reflectivity = this.reflectivity; // Scale behind envMap
  4851. data.refractionRatio = this.refractionRatio;
  4852. if ( this.combine !== undefined ) data.combine = this.combine;
  4853. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  4854. }
  4855. if ( this.gradientMap && this.gradientMap.isTexture ) {
  4856. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  4857. }
  4858. if ( this.size !== undefined ) data.size = this.size;
  4859. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  4860. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  4861. if ( this.side !== FrontSide ) data.side = this.side;
  4862. if ( this.vertexColors ) data.vertexColors = true;
  4863. if ( this.opacity < 1 ) data.opacity = this.opacity;
  4864. if ( this.transparent === true ) data.transparent = this.transparent;
  4865. data.depthFunc = this.depthFunc;
  4866. data.depthTest = this.depthTest;
  4867. data.depthWrite = this.depthWrite;
  4868. data.stencilWrite = this.stencilWrite;
  4869. data.stencilWriteMask = this.stencilWriteMask;
  4870. data.stencilFunc = this.stencilFunc;
  4871. data.stencilRef = this.stencilRef;
  4872. data.stencilFuncMask = this.stencilFuncMask;
  4873. data.stencilFail = this.stencilFail;
  4874. data.stencilZFail = this.stencilZFail;
  4875. data.stencilZPass = this.stencilZPass;
  4876. // rotation (SpriteMaterial)
  4877. if ( this.rotation && this.rotation !== 0 ) data.rotation = this.rotation;
  4878. if ( this.polygonOffset === true ) data.polygonOffset = true;
  4879. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  4880. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  4881. if ( this.linewidth && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  4882. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  4883. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  4884. if ( this.scale !== undefined ) data.scale = this.scale;
  4885. if ( this.dithering === true ) data.dithering = true;
  4886. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  4887. if ( this.alphaToCoverage === true ) data.alphaToCoverage = this.alphaToCoverage;
  4888. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  4889. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  4890. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  4891. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  4892. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  4893. if ( this.morphTargets === true ) data.morphTargets = true;
  4894. if ( this.morphNormals === true ) data.morphNormals = true;
  4895. if ( this.skinning === true ) data.skinning = true;
  4896. if ( this.flatShading === true ) data.flatShading = this.flatShading;
  4897. if ( this.visible === false ) data.visible = false;
  4898. if ( this.toneMapped === false ) data.toneMapped = false;
  4899. if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData;
  4900. // TODO: Copied from Object3D.toJSON
  4901. function extractFromCache( cache ) {
  4902. const values = [];
  4903. for ( const key in cache ) {
  4904. const data = cache[ key ];
  4905. delete data.metadata;
  4906. values.push( data );
  4907. }
  4908. return values;
  4909. }
  4910. if ( isRoot ) {
  4911. const textures = extractFromCache( meta.textures );
  4912. const images = extractFromCache( meta.images );
  4913. if ( textures.length > 0 ) data.textures = textures;
  4914. if ( images.length > 0 ) data.images = images;
  4915. }
  4916. return data;
  4917. },
  4918. clone: function () {
  4919. return new this.constructor().copy( this );
  4920. },
  4921. copy: function ( source ) {
  4922. this.name = source.name;
  4923. this.fog = source.fog;
  4924. this.blending = source.blending;
  4925. this.side = source.side;
  4926. this.vertexColors = source.vertexColors;
  4927. this.opacity = source.opacity;
  4928. this.transparent = source.transparent;
  4929. this.blendSrc = source.blendSrc;
  4930. this.blendDst = source.blendDst;
  4931. this.blendEquation = source.blendEquation;
  4932. this.blendSrcAlpha = source.blendSrcAlpha;
  4933. this.blendDstAlpha = source.blendDstAlpha;
  4934. this.blendEquationAlpha = source.blendEquationAlpha;
  4935. this.depthFunc = source.depthFunc;
  4936. this.depthTest = source.depthTest;
  4937. this.depthWrite = source.depthWrite;
  4938. this.stencilWriteMask = source.stencilWriteMask;
  4939. this.stencilFunc = source.stencilFunc;
  4940. this.stencilRef = source.stencilRef;
  4941. this.stencilFuncMask = source.stencilFuncMask;
  4942. this.stencilFail = source.stencilFail;
  4943. this.stencilZFail = source.stencilZFail;
  4944. this.stencilZPass = source.stencilZPass;
  4945. this.stencilWrite = source.stencilWrite;
  4946. const srcPlanes = source.clippingPlanes;
  4947. let dstPlanes = null;
  4948. if ( srcPlanes !== null ) {
  4949. const n = srcPlanes.length;
  4950. dstPlanes = new Array( n );
  4951. for ( let i = 0; i !== n; ++ i ) {
  4952. dstPlanes[ i ] = srcPlanes[ i ].clone();
  4953. }
  4954. }
  4955. this.clippingPlanes = dstPlanes;
  4956. this.clipIntersection = source.clipIntersection;
  4957. this.clipShadows = source.clipShadows;
  4958. this.shadowSide = source.shadowSide;
  4959. this.colorWrite = source.colorWrite;
  4960. this.precision = source.precision;
  4961. this.polygonOffset = source.polygonOffset;
  4962. this.polygonOffsetFactor = source.polygonOffsetFactor;
  4963. this.polygonOffsetUnits = source.polygonOffsetUnits;
  4964. this.dithering = source.dithering;
  4965. this.alphaTest = source.alphaTest;
  4966. this.alphaToCoverage = source.alphaToCoverage;
  4967. this.premultipliedAlpha = source.premultipliedAlpha;
  4968. this.visible = source.visible;
  4969. this.toneMapped = source.toneMapped;
  4970. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4971. return this;
  4972. },
  4973. dispose: function () {
  4974. this.dispatchEvent( { type: 'dispose' } );
  4975. }
  4976. } );
  4977. Object.defineProperty( Material.prototype, 'needsUpdate', {
  4978. set: function ( value ) {
  4979. if ( value === true ) this.version ++;
  4980. }
  4981. } );
  4982. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  4983. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  4984. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  4985. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  4986. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  4987. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  4988. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  4989. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  4990. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  4991. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  4992. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  4993. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  4994. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  4995. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  4996. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  4997. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  4998. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  4999. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  5000. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  5001. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  5002. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  5003. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  5004. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  5005. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  5006. const _hslA = { h: 0, s: 0, l: 0 };
  5007. const _hslB = { h: 0, s: 0, l: 0 };
  5008. function hue2rgb( p, q, t ) {
  5009. if ( t < 0 ) t += 1;
  5010. if ( t > 1 ) t -= 1;
  5011. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  5012. if ( t < 1 / 2 ) return q;
  5013. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  5014. return p;
  5015. }
  5016. function SRGBToLinear( c ) {
  5017. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  5018. }
  5019. function LinearToSRGB( c ) {
  5020. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  5021. }
  5022. class Color {
  5023. constructor( r, g, b ) {
  5024. if ( g === undefined && b === undefined ) {
  5025. // r is THREE.Color, hex or string
  5026. return this.set( r );
  5027. }
  5028. return this.setRGB( r, g, b );
  5029. }
  5030. set( value ) {
  5031. if ( value && value.isColor ) {
  5032. this.copy( value );
  5033. } else if ( typeof value === 'number' ) {
  5034. this.setHex( value );
  5035. } else if ( typeof value === 'string' ) {
  5036. this.setStyle( value );
  5037. }
  5038. return this;
  5039. }
  5040. setScalar( scalar ) {
  5041. this.r = scalar;
  5042. this.g = scalar;
  5043. this.b = scalar;
  5044. return this;
  5045. }
  5046. setHex( hex ) {
  5047. hex = Math.floor( hex );
  5048. this.r = ( hex >> 16 & 255 ) / 255;
  5049. this.g = ( hex >> 8 & 255 ) / 255;
  5050. this.b = ( hex & 255 ) / 255;
  5051. return this;
  5052. }
  5053. setRGB( r, g, b ) {
  5054. this.r = r;
  5055. this.g = g;
  5056. this.b = b;
  5057. return this;
  5058. }
  5059. setHSL( h, s, l ) {
  5060. // h,s,l ranges are in 0.0 - 1.0
  5061. h = MathUtils.euclideanModulo( h, 1 );
  5062. s = MathUtils.clamp( s, 0, 1 );
  5063. l = MathUtils.clamp( l, 0, 1 );
  5064. if ( s === 0 ) {
  5065. this.r = this.g = this.b = l;
  5066. } else {
  5067. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  5068. const q = ( 2 * l ) - p;
  5069. this.r = hue2rgb( q, p, h + 1 / 3 );
  5070. this.g = hue2rgb( q, p, h );
  5071. this.b = hue2rgb( q, p, h - 1 / 3 );
  5072. }
  5073. return this;
  5074. }
  5075. setStyle( style ) {
  5076. function handleAlpha( string ) {
  5077. if ( string === undefined ) return;
  5078. if ( parseFloat( string ) < 1 ) {
  5079. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  5080. }
  5081. }
  5082. let m;
  5083. if ( m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec( style ) ) {
  5084. // rgb / hsl
  5085. let color;
  5086. const name = m[ 1 ];
  5087. const components = m[ 2 ];
  5088. switch ( name ) {
  5089. case 'rgb':
  5090. case 'rgba':
  5091. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5092. // rgb(255,0,0) rgba(255,0,0,0.5)
  5093. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  5094. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  5095. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  5096. handleAlpha( color[ 4 ] );
  5097. return this;
  5098. }
  5099. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5100. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5101. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  5102. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  5103. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  5104. handleAlpha( color[ 4 ] );
  5105. return this;
  5106. }
  5107. break;
  5108. case 'hsl':
  5109. case 'hsla':
  5110. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5111. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5112. const h = parseFloat( color[ 1 ] ) / 360;
  5113. const s = parseInt( color[ 2 ], 10 ) / 100;
  5114. const l = parseInt( color[ 3 ], 10 ) / 100;
  5115. handleAlpha( color[ 4 ] );
  5116. return this.setHSL( h, s, l );
  5117. }
  5118. break;
  5119. }
  5120. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  5121. // hex color
  5122. const hex = m[ 1 ];
  5123. const size = hex.length;
  5124. if ( size === 3 ) {
  5125. // #ff0
  5126. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  5127. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  5128. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  5129. return this;
  5130. } else if ( size === 6 ) {
  5131. // #ff0000
  5132. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  5133. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  5134. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  5135. return this;
  5136. }
  5137. }
  5138. if ( style && style.length > 0 ) {
  5139. return this.setColorName( style );
  5140. }
  5141. return this;
  5142. }
  5143. setColorName( style ) {
  5144. // color keywords
  5145. const hex = _colorKeywords[ style ];
  5146. if ( hex !== undefined ) {
  5147. // red
  5148. this.setHex( hex );
  5149. } else {
  5150. // unknown color
  5151. console.warn( 'THREE.Color: Unknown color ' + style );
  5152. }
  5153. return this;
  5154. }
  5155. clone() {
  5156. return new this.constructor( this.r, this.g, this.b );
  5157. }
  5158. copy( color ) {
  5159. this.r = color.r;
  5160. this.g = color.g;
  5161. this.b = color.b;
  5162. return this;
  5163. }
  5164. copyGammaToLinear( color, gammaFactor = 2.0 ) {
  5165. this.r = Math.pow( color.r, gammaFactor );
  5166. this.g = Math.pow( color.g, gammaFactor );
  5167. this.b = Math.pow( color.b, gammaFactor );
  5168. return this;
  5169. }
  5170. copyLinearToGamma( color, gammaFactor = 2.0 ) {
  5171. const safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  5172. this.r = Math.pow( color.r, safeInverse );
  5173. this.g = Math.pow( color.g, safeInverse );
  5174. this.b = Math.pow( color.b, safeInverse );
  5175. return this;
  5176. }
  5177. convertGammaToLinear( gammaFactor ) {
  5178. this.copyGammaToLinear( this, gammaFactor );
  5179. return this;
  5180. }
  5181. convertLinearToGamma( gammaFactor ) {
  5182. this.copyLinearToGamma( this, gammaFactor );
  5183. return this;
  5184. }
  5185. copySRGBToLinear( color ) {
  5186. this.r = SRGBToLinear( color.r );
  5187. this.g = SRGBToLinear( color.g );
  5188. this.b = SRGBToLinear( color.b );
  5189. return this;
  5190. }
  5191. copyLinearToSRGB( color ) {
  5192. this.r = LinearToSRGB( color.r );
  5193. this.g = LinearToSRGB( color.g );
  5194. this.b = LinearToSRGB( color.b );
  5195. return this;
  5196. }
  5197. convertSRGBToLinear() {
  5198. this.copySRGBToLinear( this );
  5199. return this;
  5200. }
  5201. convertLinearToSRGB() {
  5202. this.copyLinearToSRGB( this );
  5203. return this;
  5204. }
  5205. getHex() {
  5206. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  5207. }
  5208. getHexString() {
  5209. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  5210. }
  5211. getHSL( target ) {
  5212. // h,s,l ranges are in 0.0 - 1.0
  5213. if ( target === undefined ) {
  5214. console.warn( 'THREE.Color: .getHSL() target is now required' );
  5215. target = { h: 0, s: 0, l: 0 };
  5216. }
  5217. const r = this.r, g = this.g, b = this.b;
  5218. const max = Math.max( r, g, b );
  5219. const min = Math.min( r, g, b );
  5220. let hue, saturation;
  5221. const lightness = ( min + max ) / 2.0;
  5222. if ( min === max ) {
  5223. hue = 0;
  5224. saturation = 0;
  5225. } else {
  5226. const delta = max - min;
  5227. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  5228. switch ( max ) {
  5229. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  5230. case g: hue = ( b - r ) / delta + 2; break;
  5231. case b: hue = ( r - g ) / delta + 4; break;
  5232. }
  5233. hue /= 6;
  5234. }
  5235. target.h = hue;
  5236. target.s = saturation;
  5237. target.l = lightness;
  5238. return target;
  5239. }
  5240. getStyle() {
  5241. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  5242. }
  5243. offsetHSL( h, s, l ) {
  5244. this.getHSL( _hslA );
  5245. _hslA.h += h; _hslA.s += s; _hslA.l += l;
  5246. this.setHSL( _hslA.h, _hslA.s, _hslA.l );
  5247. return this;
  5248. }
  5249. add( color ) {
  5250. this.r += color.r;
  5251. this.g += color.g;
  5252. this.b += color.b;
  5253. return this;
  5254. }
  5255. addColors( color1, color2 ) {
  5256. this.r = color1.r + color2.r;
  5257. this.g = color1.g + color2.g;
  5258. this.b = color1.b + color2.b;
  5259. return this;
  5260. }
  5261. addScalar( s ) {
  5262. this.r += s;
  5263. this.g += s;
  5264. this.b += s;
  5265. return this;
  5266. }
  5267. sub( color ) {
  5268. this.r = Math.max( 0, this.r - color.r );
  5269. this.g = Math.max( 0, this.g - color.g );
  5270. this.b = Math.max( 0, this.b - color.b );
  5271. return this;
  5272. }
  5273. multiply( color ) {
  5274. this.r *= color.r;
  5275. this.g *= color.g;
  5276. this.b *= color.b;
  5277. return this;
  5278. }
  5279. multiplyScalar( s ) {
  5280. this.r *= s;
  5281. this.g *= s;
  5282. this.b *= s;
  5283. return this;
  5284. }
  5285. lerp( color, alpha ) {
  5286. this.r += ( color.r - this.r ) * alpha;
  5287. this.g += ( color.g - this.g ) * alpha;
  5288. this.b += ( color.b - this.b ) * alpha;
  5289. return this;
  5290. }
  5291. lerpColors( color1, color2, alpha ) {
  5292. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  5293. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  5294. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  5295. return this;
  5296. }
  5297. lerpHSL( color, alpha ) {
  5298. this.getHSL( _hslA );
  5299. color.getHSL( _hslB );
  5300. const h = MathUtils.lerp( _hslA.h, _hslB.h, alpha );
  5301. const s = MathUtils.lerp( _hslA.s, _hslB.s, alpha );
  5302. const l = MathUtils.lerp( _hslA.l, _hslB.l, alpha );
  5303. this.setHSL( h, s, l );
  5304. return this;
  5305. }
  5306. equals( c ) {
  5307. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  5308. }
  5309. fromArray( array, offset = 0 ) {
  5310. this.r = array[ offset ];
  5311. this.g = array[ offset + 1 ];
  5312. this.b = array[ offset + 2 ];
  5313. return this;
  5314. }
  5315. toArray( array = [], offset = 0 ) {
  5316. array[ offset ] = this.r;
  5317. array[ offset + 1 ] = this.g;
  5318. array[ offset + 2 ] = this.b;
  5319. return array;
  5320. }
  5321. fromBufferAttribute( attribute, index ) {
  5322. this.r = attribute.getX( index );
  5323. this.g = attribute.getY( index );
  5324. this.b = attribute.getZ( index );
  5325. if ( attribute.normalized === true ) {
  5326. // assuming Uint8Array
  5327. this.r /= 255;
  5328. this.g /= 255;
  5329. this.b /= 255;
  5330. }
  5331. return this;
  5332. }
  5333. toJSON() {
  5334. return this.getHex();
  5335. }
  5336. }
  5337. Color.NAMES = _colorKeywords;
  5338. Color.prototype.isColor = true;
  5339. Color.prototype.r = 1;
  5340. Color.prototype.g = 1;
  5341. Color.prototype.b = 1;
  5342. /**
  5343. * parameters = {
  5344. * color: <hex>,
  5345. * opacity: <float>,
  5346. * map: new THREE.Texture( <Image> ),
  5347. *
  5348. * lightMap: new THREE.Texture( <Image> ),
  5349. * lightMapIntensity: <float>
  5350. *
  5351. * aoMap: new THREE.Texture( <Image> ),
  5352. * aoMapIntensity: <float>
  5353. *
  5354. * specularMap: new THREE.Texture( <Image> ),
  5355. *
  5356. * alphaMap: new THREE.Texture( <Image> ),
  5357. *
  5358. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  5359. * combine: THREE.Multiply,
  5360. * reflectivity: <float>,
  5361. * refractionRatio: <float>,
  5362. *
  5363. * depthTest: <bool>,
  5364. * depthWrite: <bool>,
  5365. *
  5366. * wireframe: <boolean>,
  5367. * wireframeLinewidth: <float>,
  5368. *
  5369. * skinning: <bool>,
  5370. * morphTargets: <bool>
  5371. * }
  5372. */
  5373. class MeshBasicMaterial extends Material {
  5374. constructor( parameters ) {
  5375. super();
  5376. this.type = 'MeshBasicMaterial';
  5377. this.color = new Color( 0xffffff ); // emissive
  5378. this.map = null;
  5379. this.lightMap = null;
  5380. this.lightMapIntensity = 1.0;
  5381. this.aoMap = null;
  5382. this.aoMapIntensity = 1.0;
  5383. this.specularMap = null;
  5384. this.alphaMap = null;
  5385. this.envMap = null;
  5386. this.combine = MultiplyOperation;
  5387. this.reflectivity = 1;
  5388. this.refractionRatio = 0.98;
  5389. this.wireframe = false;
  5390. this.wireframeLinewidth = 1;
  5391. this.wireframeLinecap = 'round';
  5392. this.wireframeLinejoin = 'round';
  5393. this.skinning = false;
  5394. this.morphTargets = false;
  5395. this.setValues( parameters );
  5396. }
  5397. copy( source ) {
  5398. super.copy( source );
  5399. this.color.copy( source.color );
  5400. this.map = source.map;
  5401. this.lightMap = source.lightMap;
  5402. this.lightMapIntensity = source.lightMapIntensity;
  5403. this.aoMap = source.aoMap;
  5404. this.aoMapIntensity = source.aoMapIntensity;
  5405. this.specularMap = source.specularMap;
  5406. this.alphaMap = source.alphaMap;
  5407. this.envMap = source.envMap;
  5408. this.combine = source.combine;
  5409. this.reflectivity = source.reflectivity;
  5410. this.refractionRatio = source.refractionRatio;
  5411. this.wireframe = source.wireframe;
  5412. this.wireframeLinewidth = source.wireframeLinewidth;
  5413. this.wireframeLinecap = source.wireframeLinecap;
  5414. this.wireframeLinejoin = source.wireframeLinejoin;
  5415. this.skinning = source.skinning;
  5416. this.morphTargets = source.morphTargets;
  5417. return this;
  5418. }
  5419. }
  5420. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  5421. const _vector$3 = new Vector3();
  5422. const _vector2$1 = new Vector2();
  5423. function BufferAttribute( array, itemSize, normalized ) {
  5424. if ( Array.isArray( array ) ) {
  5425. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5426. }
  5427. this.name = '';
  5428. this.array = array;
  5429. this.itemSize = itemSize;
  5430. this.count = array !== undefined ? array.length / itemSize : 0;
  5431. this.normalized = normalized === true;
  5432. this.usage = StaticDrawUsage;
  5433. this.updateRange = { offset: 0, count: - 1 };
  5434. this.version = 0;
  5435. }
  5436. Object.defineProperty( BufferAttribute.prototype, 'needsUpdate', {
  5437. set: function ( value ) {
  5438. if ( value === true ) this.version ++;
  5439. }
  5440. } );
  5441. Object.assign( BufferAttribute.prototype, {
  5442. isBufferAttribute: true,
  5443. onUploadCallback: function () {},
  5444. setUsage: function ( value ) {
  5445. this.usage = value;
  5446. return this;
  5447. },
  5448. copy: function ( source ) {
  5449. this.name = source.name;
  5450. this.array = new source.array.constructor( source.array );
  5451. this.itemSize = source.itemSize;
  5452. this.count = source.count;
  5453. this.normalized = source.normalized;
  5454. this.usage = source.usage;
  5455. return this;
  5456. },
  5457. copyAt: function ( index1, attribute, index2 ) {
  5458. index1 *= this.itemSize;
  5459. index2 *= attribute.itemSize;
  5460. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  5461. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5462. }
  5463. return this;
  5464. },
  5465. copyArray: function ( array ) {
  5466. this.array.set( array );
  5467. return this;
  5468. },
  5469. copyColorsArray: function ( colors ) {
  5470. const array = this.array;
  5471. let offset = 0;
  5472. for ( let i = 0, l = colors.length; i < l; i ++ ) {
  5473. let color = colors[ i ];
  5474. if ( color === undefined ) {
  5475. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  5476. color = new Color();
  5477. }
  5478. array[ offset ++ ] = color.r;
  5479. array[ offset ++ ] = color.g;
  5480. array[ offset ++ ] = color.b;
  5481. }
  5482. return this;
  5483. },
  5484. copyVector2sArray: function ( vectors ) {
  5485. const array = this.array;
  5486. let offset = 0;
  5487. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  5488. let vector = vectors[ i ];
  5489. if ( vector === undefined ) {
  5490. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  5491. vector = new Vector2();
  5492. }
  5493. array[ offset ++ ] = vector.x;
  5494. array[ offset ++ ] = vector.y;
  5495. }
  5496. return this;
  5497. },
  5498. copyVector3sArray: function ( vectors ) {
  5499. const array = this.array;
  5500. let offset = 0;
  5501. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  5502. let vector = vectors[ i ];
  5503. if ( vector === undefined ) {
  5504. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  5505. vector = new Vector3();
  5506. }
  5507. array[ offset ++ ] = vector.x;
  5508. array[ offset ++ ] = vector.y;
  5509. array[ offset ++ ] = vector.z;
  5510. }
  5511. return this;
  5512. },
  5513. copyVector4sArray: function ( vectors ) {
  5514. const array = this.array;
  5515. let offset = 0;
  5516. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  5517. let vector = vectors[ i ];
  5518. if ( vector === undefined ) {
  5519. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  5520. vector = new Vector4();
  5521. }
  5522. array[ offset ++ ] = vector.x;
  5523. array[ offset ++ ] = vector.y;
  5524. array[ offset ++ ] = vector.z;
  5525. array[ offset ++ ] = vector.w;
  5526. }
  5527. return this;
  5528. },
  5529. applyMatrix3: function ( m ) {
  5530. if ( this.itemSize === 2 ) {
  5531. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5532. _vector2$1.fromBufferAttribute( this, i );
  5533. _vector2$1.applyMatrix3( m );
  5534. this.setXY( i, _vector2$1.x, _vector2$1.y );
  5535. }
  5536. } else if ( this.itemSize === 3 ) {
  5537. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5538. _vector$3.fromBufferAttribute( this, i );
  5539. _vector$3.applyMatrix3( m );
  5540. this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );
  5541. }
  5542. }
  5543. return this;
  5544. },
  5545. applyMatrix4: function ( m ) {
  5546. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5547. _vector$3.x = this.getX( i );
  5548. _vector$3.y = this.getY( i );
  5549. _vector$3.z = this.getZ( i );
  5550. _vector$3.applyMatrix4( m );
  5551. this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );
  5552. }
  5553. return this;
  5554. },
  5555. applyNormalMatrix: function ( m ) {
  5556. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5557. _vector$3.x = this.getX( i );
  5558. _vector$3.y = this.getY( i );
  5559. _vector$3.z = this.getZ( i );
  5560. _vector$3.applyNormalMatrix( m );
  5561. this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );
  5562. }
  5563. return this;
  5564. },
  5565. transformDirection: function ( m ) {
  5566. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5567. _vector$3.x = this.getX( i );
  5568. _vector$3.y = this.getY( i );
  5569. _vector$3.z = this.getZ( i );
  5570. _vector$3.transformDirection( m );
  5571. this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );
  5572. }
  5573. return this;
  5574. },
  5575. set: function ( value, offset = 0 ) {
  5576. this.array.set( value, offset );
  5577. return this;
  5578. },
  5579. getX: function ( index ) {
  5580. return this.array[ index * this.itemSize ];
  5581. },
  5582. setX: function ( index, x ) {
  5583. this.array[ index * this.itemSize ] = x;
  5584. return this;
  5585. },
  5586. getY: function ( index ) {
  5587. return this.array[ index * this.itemSize + 1 ];
  5588. },
  5589. setY: function ( index, y ) {
  5590. this.array[ index * this.itemSize + 1 ] = y;
  5591. return this;
  5592. },
  5593. getZ: function ( index ) {
  5594. return this.array[ index * this.itemSize + 2 ];
  5595. },
  5596. setZ: function ( index, z ) {
  5597. this.array[ index * this.itemSize + 2 ] = z;
  5598. return this;
  5599. },
  5600. getW: function ( index ) {
  5601. return this.array[ index * this.itemSize + 3 ];
  5602. },
  5603. setW: function ( index, w ) {
  5604. this.array[ index * this.itemSize + 3 ] = w;
  5605. return this;
  5606. },
  5607. setXY: function ( index, x, y ) {
  5608. index *= this.itemSize;
  5609. this.array[ index + 0 ] = x;
  5610. this.array[ index + 1 ] = y;
  5611. return this;
  5612. },
  5613. setXYZ: function ( index, x, y, z ) {
  5614. index *= this.itemSize;
  5615. this.array[ index + 0 ] = x;
  5616. this.array[ index + 1 ] = y;
  5617. this.array[ index + 2 ] = z;
  5618. return this;
  5619. },
  5620. setXYZW: function ( index, x, y, z, w ) {
  5621. index *= this.itemSize;
  5622. this.array[ index + 0 ] = x;
  5623. this.array[ index + 1 ] = y;
  5624. this.array[ index + 2 ] = z;
  5625. this.array[ index + 3 ] = w;
  5626. return this;
  5627. },
  5628. onUpload: function ( callback ) {
  5629. this.onUploadCallback = callback;
  5630. return this;
  5631. },
  5632. clone: function () {
  5633. return new this.constructor( this.array, this.itemSize ).copy( this );
  5634. },
  5635. toJSON: function () {
  5636. return {
  5637. itemSize: this.itemSize,
  5638. type: this.array.constructor.name,
  5639. array: Array.prototype.slice.call( this.array ),
  5640. normalized: this.normalized
  5641. };
  5642. }
  5643. } );
  5644. //
  5645. function Int8BufferAttribute( array, itemSize, normalized ) {
  5646. BufferAttribute.call( this, new Int8Array( array ), itemSize, normalized );
  5647. }
  5648. Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  5649. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  5650. function Uint8BufferAttribute( array, itemSize, normalized ) {
  5651. BufferAttribute.call( this, new Uint8Array( array ), itemSize, normalized );
  5652. }
  5653. Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  5654. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  5655. function Uint8ClampedBufferAttribute( array, itemSize, normalized ) {
  5656. BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize, normalized );
  5657. }
  5658. Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  5659. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  5660. function Int16BufferAttribute( array, itemSize, normalized ) {
  5661. BufferAttribute.call( this, new Int16Array( array ), itemSize, normalized );
  5662. }
  5663. Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  5664. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  5665. function Uint16BufferAttribute( array, itemSize, normalized ) {
  5666. BufferAttribute.call( this, new Uint16Array( array ), itemSize, normalized );
  5667. }
  5668. Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  5669. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  5670. function Int32BufferAttribute( array, itemSize, normalized ) {
  5671. BufferAttribute.call( this, new Int32Array( array ), itemSize, normalized );
  5672. }
  5673. Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  5674. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  5675. function Uint32BufferAttribute( array, itemSize, normalized ) {
  5676. BufferAttribute.call( this, new Uint32Array( array ), itemSize, normalized );
  5677. }
  5678. Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  5679. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  5680. function Float16BufferAttribute( array, itemSize, normalized ) {
  5681. BufferAttribute.call( this, new Uint16Array( array ), itemSize, normalized );
  5682. }
  5683. Float16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  5684. Float16BufferAttribute.prototype.constructor = Float16BufferAttribute;
  5685. Float16BufferAttribute.prototype.isFloat16BufferAttribute = true;
  5686. function Float32BufferAttribute( array, itemSize, normalized ) {
  5687. BufferAttribute.call( this, new Float32Array( array ), itemSize, normalized );
  5688. }
  5689. Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  5690. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  5691. function Float64BufferAttribute( array, itemSize, normalized ) {
  5692. BufferAttribute.call( this, new Float64Array( array ), itemSize, normalized );
  5693. }
  5694. Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  5695. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  5696. function arrayMax( array ) {
  5697. if ( array.length === 0 ) return - Infinity;
  5698. let max = array[ 0 ];
  5699. for ( let i = 1, l = array.length; i < l; ++ i ) {
  5700. if ( array[ i ] > max ) max = array[ i ];
  5701. }
  5702. return max;
  5703. }
  5704. const TYPED_ARRAYS = {
  5705. Int8Array: Int8Array,
  5706. Uint8Array: Uint8Array,
  5707. Uint8ClampedArray: Uint8ClampedArray,
  5708. Int16Array: Int16Array,
  5709. Uint16Array: Uint16Array,
  5710. Int32Array: Int32Array,
  5711. Uint32Array: Uint32Array,
  5712. Float32Array: Float32Array,
  5713. Float64Array: Float64Array
  5714. };
  5715. function getTypedArray( type, buffer ) {
  5716. return new TYPED_ARRAYS[ type ]( buffer );
  5717. }
  5718. let _id = 0;
  5719. const _m1$2 = new Matrix4();
  5720. const _obj = new Object3D();
  5721. const _offset = new Vector3();
  5722. const _box$2 = new Box3();
  5723. const _boxMorphTargets = new Box3();
  5724. const _vector$4 = new Vector3();
  5725. function BufferGeometry() {
  5726. Object.defineProperty( this, 'id', { value: _id ++ } );
  5727. this.uuid = MathUtils.generateUUID();
  5728. this.name = '';
  5729. this.type = 'BufferGeometry';
  5730. this.index = null;
  5731. this.attributes = {};
  5732. this.morphAttributes = {};
  5733. this.morphTargetsRelative = false;
  5734. this.groups = [];
  5735. this.boundingBox = null;
  5736. this.boundingSphere = null;
  5737. this.drawRange = { start: 0, count: Infinity };
  5738. this.userData = {};
  5739. }
  5740. BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  5741. constructor: BufferGeometry,
  5742. isBufferGeometry: true,
  5743. getIndex: function () {
  5744. return this.index;
  5745. },
  5746. setIndex: function ( index ) {
  5747. if ( Array.isArray( index ) ) {
  5748. this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  5749. } else {
  5750. this.index = index;
  5751. }
  5752. return this;
  5753. },
  5754. getAttribute: function ( name ) {
  5755. return this.attributes[ name ];
  5756. },
  5757. setAttribute: function ( name, attribute ) {
  5758. this.attributes[ name ] = attribute;
  5759. return this;
  5760. },
  5761. deleteAttribute: function ( name ) {
  5762. delete this.attributes[ name ];
  5763. return this;
  5764. },
  5765. hasAttribute: function ( name ) {
  5766. return this.attributes[ name ] !== undefined;
  5767. },
  5768. addGroup: function ( start, count, materialIndex = 0 ) {
  5769. this.groups.push( {
  5770. start: start,
  5771. count: count,
  5772. materialIndex: materialIndex
  5773. } );
  5774. },
  5775. clearGroups: function () {
  5776. this.groups = [];
  5777. },
  5778. setDrawRange: function ( start, count ) {
  5779. this.drawRange.start = start;
  5780. this.drawRange.count = count;
  5781. },
  5782. applyMatrix4: function ( matrix ) {
  5783. const position = this.attributes.position;
  5784. if ( position !== undefined ) {
  5785. position.applyMatrix4( matrix );
  5786. position.needsUpdate = true;
  5787. }
  5788. const normal = this.attributes.normal;
  5789. if ( normal !== undefined ) {
  5790. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  5791. normal.applyNormalMatrix( normalMatrix );
  5792. normal.needsUpdate = true;
  5793. }
  5794. const tangent = this.attributes.tangent;
  5795. if ( tangent !== undefined ) {
  5796. tangent.transformDirection( matrix );
  5797. tangent.needsUpdate = true;
  5798. }
  5799. if ( this.boundingBox !== null ) {
  5800. this.computeBoundingBox();
  5801. }
  5802. if ( this.boundingSphere !== null ) {
  5803. this.computeBoundingSphere();
  5804. }
  5805. return this;
  5806. },
  5807. rotateX: function ( angle ) {
  5808. // rotate geometry around world x-axis
  5809. _m1$2.makeRotationX( angle );
  5810. this.applyMatrix4( _m1$2 );
  5811. return this;
  5812. },
  5813. rotateY: function ( angle ) {
  5814. // rotate geometry around world y-axis
  5815. _m1$2.makeRotationY( angle );
  5816. this.applyMatrix4( _m1$2 );
  5817. return this;
  5818. },
  5819. rotateZ: function ( angle ) {
  5820. // rotate geometry around world z-axis
  5821. _m1$2.makeRotationZ( angle );
  5822. this.applyMatrix4( _m1$2 );
  5823. return this;
  5824. },
  5825. translate: function ( x, y, z ) {
  5826. // translate geometry
  5827. _m1$2.makeTranslation( x, y, z );
  5828. this.applyMatrix4( _m1$2 );
  5829. return this;
  5830. },
  5831. scale: function ( x, y, z ) {
  5832. // scale geometry
  5833. _m1$2.makeScale( x, y, z );
  5834. this.applyMatrix4( _m1$2 );
  5835. return this;
  5836. },
  5837. lookAt: function ( vector ) {
  5838. _obj.lookAt( vector );
  5839. _obj.updateMatrix();
  5840. this.applyMatrix4( _obj.matrix );
  5841. return this;
  5842. },
  5843. center: function () {
  5844. this.computeBoundingBox();
  5845. this.boundingBox.getCenter( _offset ).negate();
  5846. this.translate( _offset.x, _offset.y, _offset.z );
  5847. return this;
  5848. },
  5849. setFromPoints: function ( points ) {
  5850. const position = [];
  5851. for ( let i = 0, l = points.length; i < l; i ++ ) {
  5852. const point = points[ i ];
  5853. position.push( point.x, point.y, point.z || 0 );
  5854. }
  5855. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  5856. return this;
  5857. },
  5858. computeBoundingBox: function () {
  5859. if ( this.boundingBox === null ) {
  5860. this.boundingBox = new Box3();
  5861. }
  5862. const position = this.attributes.position;
  5863. const morphAttributesPosition = this.morphAttributes.position;
  5864. if ( position && position.isGLBufferAttribute ) {
  5865. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this );
  5866. this.boundingBox.set(
  5867. new Vector3( - Infinity, - Infinity, - Infinity ),
  5868. new Vector3( + Infinity, + Infinity, + Infinity )
  5869. );
  5870. return;
  5871. }
  5872. if ( position !== undefined ) {
  5873. this.boundingBox.setFromBufferAttribute( position );
  5874. // process morph attributes if present
  5875. if ( morphAttributesPosition ) {
  5876. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  5877. const morphAttribute = morphAttributesPosition[ i ];
  5878. _box$2.setFromBufferAttribute( morphAttribute );
  5879. if ( this.morphTargetsRelative ) {
  5880. _vector$4.addVectors( this.boundingBox.min, _box$2.min );
  5881. this.boundingBox.expandByPoint( _vector$4 );
  5882. _vector$4.addVectors( this.boundingBox.max, _box$2.max );
  5883. this.boundingBox.expandByPoint( _vector$4 );
  5884. } else {
  5885. this.boundingBox.expandByPoint( _box$2.min );
  5886. this.boundingBox.expandByPoint( _box$2.max );
  5887. }
  5888. }
  5889. }
  5890. } else {
  5891. this.boundingBox.makeEmpty();
  5892. }
  5893. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  5894. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  5895. }
  5896. },
  5897. computeBoundingSphere: function () {
  5898. if ( this.boundingSphere === null ) {
  5899. this.boundingSphere = new Sphere();
  5900. }
  5901. const position = this.attributes.position;
  5902. const morphAttributesPosition = this.morphAttributes.position;
  5903. if ( position && position.isGLBufferAttribute ) {
  5904. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this );
  5905. this.boundingSphere.set( new Vector3(), Infinity );
  5906. return;
  5907. }
  5908. if ( position ) {
  5909. // first, find the center of the bounding sphere
  5910. const center = this.boundingSphere.center;
  5911. _box$2.setFromBufferAttribute( position );
  5912. // process morph attributes if present
  5913. if ( morphAttributesPosition ) {
  5914. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  5915. const morphAttribute = morphAttributesPosition[ i ];
  5916. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  5917. if ( this.morphTargetsRelative ) {
  5918. _vector$4.addVectors( _box$2.min, _boxMorphTargets.min );
  5919. _box$2.expandByPoint( _vector$4 );
  5920. _vector$4.addVectors( _box$2.max, _boxMorphTargets.max );
  5921. _box$2.expandByPoint( _vector$4 );
  5922. } else {
  5923. _box$2.expandByPoint( _boxMorphTargets.min );
  5924. _box$2.expandByPoint( _boxMorphTargets.max );
  5925. }
  5926. }
  5927. }
  5928. _box$2.getCenter( center );
  5929. // second, try to find a boundingSphere with a radius smaller than the
  5930. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  5931. let maxRadiusSq = 0;
  5932. for ( let i = 0, il = position.count; i < il; i ++ ) {
  5933. _vector$4.fromBufferAttribute( position, i );
  5934. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$4 ) );
  5935. }
  5936. // process morph attributes if present
  5937. if ( morphAttributesPosition ) {
  5938. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  5939. const morphAttribute = morphAttributesPosition[ i ];
  5940. const morphTargetsRelative = this.morphTargetsRelative;
  5941. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  5942. _vector$4.fromBufferAttribute( morphAttribute, j );
  5943. if ( morphTargetsRelative ) {
  5944. _offset.fromBufferAttribute( position, j );
  5945. _vector$4.add( _offset );
  5946. }
  5947. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$4 ) );
  5948. }
  5949. }
  5950. }
  5951. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  5952. if ( isNaN( this.boundingSphere.radius ) ) {
  5953. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  5954. }
  5955. }
  5956. },
  5957. computeFaceNormals: function () {
  5958. // backwards compatibility
  5959. },
  5960. computeTangents: function () {
  5961. const index = this.index;
  5962. const attributes = this.attributes;
  5963. // based on http://www.terathon.com/code/tangent.html
  5964. // (per vertex tangents)
  5965. if ( index === null ||
  5966. attributes.position === undefined ||
  5967. attributes.normal === undefined ||
  5968. attributes.uv === undefined ) {
  5969. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  5970. return;
  5971. }
  5972. const indices = index.array;
  5973. const positions = attributes.position.array;
  5974. const normals = attributes.normal.array;
  5975. const uvs = attributes.uv.array;
  5976. const nVertices = positions.length / 3;
  5977. if ( attributes.tangent === undefined ) {
  5978. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) );
  5979. }
  5980. const tangents = attributes.tangent.array;
  5981. const tan1 = [], tan2 = [];
  5982. for ( let i = 0; i < nVertices; i ++ ) {
  5983. tan1[ i ] = new Vector3();
  5984. tan2[ i ] = new Vector3();
  5985. }
  5986. const vA = new Vector3(),
  5987. vB = new Vector3(),
  5988. vC = new Vector3(),
  5989. uvA = new Vector2(),
  5990. uvB = new Vector2(),
  5991. uvC = new Vector2(),
  5992. sdir = new Vector3(),
  5993. tdir = new Vector3();
  5994. function handleTriangle( a, b, c ) {
  5995. vA.fromArray( positions, a * 3 );
  5996. vB.fromArray( positions, b * 3 );
  5997. vC.fromArray( positions, c * 3 );
  5998. uvA.fromArray( uvs, a * 2 );
  5999. uvB.fromArray( uvs, b * 2 );
  6000. uvC.fromArray( uvs, c * 2 );
  6001. vB.sub( vA );
  6002. vC.sub( vA );
  6003. uvB.sub( uvA );
  6004. uvC.sub( uvA );
  6005. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6006. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6007. if ( ! isFinite( r ) ) return;
  6008. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6009. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6010. tan1[ a ].add( sdir );
  6011. tan1[ b ].add( sdir );
  6012. tan1[ c ].add( sdir );
  6013. tan2[ a ].add( tdir );
  6014. tan2[ b ].add( tdir );
  6015. tan2[ c ].add( tdir );
  6016. }
  6017. let groups = this.groups;
  6018. if ( groups.length === 0 ) {
  6019. groups = [ {
  6020. start: 0,
  6021. count: indices.length
  6022. } ];
  6023. }
  6024. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6025. const group = groups[ i ];
  6026. const start = group.start;
  6027. const count = group.count;
  6028. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6029. handleTriangle(
  6030. indices[ j + 0 ],
  6031. indices[ j + 1 ],
  6032. indices[ j + 2 ]
  6033. );
  6034. }
  6035. }
  6036. const tmp = new Vector3(), tmp2 = new Vector3();
  6037. const n = new Vector3(), n2 = new Vector3();
  6038. function handleVertex( v ) {
  6039. n.fromArray( normals, v * 3 );
  6040. n2.copy( n );
  6041. const t = tan1[ v ];
  6042. // Gram-Schmidt orthogonalize
  6043. tmp.copy( t );
  6044. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6045. // Calculate handedness
  6046. tmp2.crossVectors( n2, t );
  6047. const test = tmp2.dot( tan2[ v ] );
  6048. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6049. tangents[ v * 4 ] = tmp.x;
  6050. tangents[ v * 4 + 1 ] = tmp.y;
  6051. tangents[ v * 4 + 2 ] = tmp.z;
  6052. tangents[ v * 4 + 3 ] = w;
  6053. }
  6054. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6055. const group = groups[ i ];
  6056. const start = group.start;
  6057. const count = group.count;
  6058. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6059. handleVertex( indices[ j + 0 ] );
  6060. handleVertex( indices[ j + 1 ] );
  6061. handleVertex( indices[ j + 2 ] );
  6062. }
  6063. }
  6064. },
  6065. computeVertexNormals: function () {
  6066. const index = this.index;
  6067. const positionAttribute = this.getAttribute( 'position' );
  6068. if ( positionAttribute !== undefined ) {
  6069. let normalAttribute = this.getAttribute( 'normal' );
  6070. if ( normalAttribute === undefined ) {
  6071. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6072. this.setAttribute( 'normal', normalAttribute );
  6073. } else {
  6074. // reset existing normals to zero
  6075. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6076. normalAttribute.setXYZ( i, 0, 0, 0 );
  6077. }
  6078. }
  6079. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6080. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6081. const cb = new Vector3(), ab = new Vector3();
  6082. // indexed elements
  6083. if ( index ) {
  6084. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6085. const vA = index.getX( i + 0 );
  6086. const vB = index.getX( i + 1 );
  6087. const vC = index.getX( i + 2 );
  6088. pA.fromBufferAttribute( positionAttribute, vA );
  6089. pB.fromBufferAttribute( positionAttribute, vB );
  6090. pC.fromBufferAttribute( positionAttribute, vC );
  6091. cb.subVectors( pC, pB );
  6092. ab.subVectors( pA, pB );
  6093. cb.cross( ab );
  6094. nA.fromBufferAttribute( normalAttribute, vA );
  6095. nB.fromBufferAttribute( normalAttribute, vB );
  6096. nC.fromBufferAttribute( normalAttribute, vC );
  6097. nA.add( cb );
  6098. nB.add( cb );
  6099. nC.add( cb );
  6100. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6101. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6102. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6103. }
  6104. } else {
  6105. // non-indexed elements (unconnected triangle soup)
  6106. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6107. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6108. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6109. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6110. cb.subVectors( pC, pB );
  6111. ab.subVectors( pA, pB );
  6112. cb.cross( ab );
  6113. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6114. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6115. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6116. }
  6117. }
  6118. this.normalizeNormals();
  6119. normalAttribute.needsUpdate = true;
  6120. }
  6121. },
  6122. merge: function ( geometry, offset ) {
  6123. if ( ! ( geometry && geometry.isBufferGeometry ) ) {
  6124. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  6125. return;
  6126. }
  6127. if ( offset === undefined ) {
  6128. offset = 0;
  6129. console.warn(
  6130. 'THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. '
  6131. + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.'
  6132. );
  6133. }
  6134. const attributes = this.attributes;
  6135. for ( const key in attributes ) {
  6136. if ( geometry.attributes[ key ] === undefined ) continue;
  6137. const attribute1 = attributes[ key ];
  6138. const attributeArray1 = attribute1.array;
  6139. const attribute2 = geometry.attributes[ key ];
  6140. const attributeArray2 = attribute2.array;
  6141. const attributeOffset = attribute2.itemSize * offset;
  6142. const length = Math.min( attributeArray2.length, attributeArray1.length - attributeOffset );
  6143. for ( let i = 0, j = attributeOffset; i < length; i ++, j ++ ) {
  6144. attributeArray1[ j ] = attributeArray2[ i ];
  6145. }
  6146. }
  6147. return this;
  6148. },
  6149. normalizeNormals: function () {
  6150. const normals = this.attributes.normal;
  6151. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6152. _vector$4.fromBufferAttribute( normals, i );
  6153. _vector$4.normalize();
  6154. normals.setXYZ( i, _vector$4.x, _vector$4.y, _vector$4.z );
  6155. }
  6156. },
  6157. toNonIndexed: function () {
  6158. function convertBufferAttribute( attribute, indices ) {
  6159. const array = attribute.array;
  6160. const itemSize = attribute.itemSize;
  6161. const normalized = attribute.normalized;
  6162. const array2 = new array.constructor( indices.length * itemSize );
  6163. let index = 0, index2 = 0;
  6164. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6165. index = indices[ i ] * itemSize;
  6166. for ( let j = 0; j < itemSize; j ++ ) {
  6167. array2[ index2 ++ ] = array[ index ++ ];
  6168. }
  6169. }
  6170. return new BufferAttribute( array2, itemSize, normalized );
  6171. }
  6172. //
  6173. if ( this.index === null ) {
  6174. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6175. return this;
  6176. }
  6177. const geometry2 = new BufferGeometry();
  6178. const indices = this.index.array;
  6179. const attributes = this.attributes;
  6180. // attributes
  6181. for ( const name in attributes ) {
  6182. const attribute = attributes[ name ];
  6183. const newAttribute = convertBufferAttribute( attribute, indices );
  6184. geometry2.setAttribute( name, newAttribute );
  6185. }
  6186. // morph attributes
  6187. const morphAttributes = this.morphAttributes;
  6188. for ( const name in morphAttributes ) {
  6189. const morphArray = [];
  6190. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6191. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6192. const attribute = morphAttribute[ i ];
  6193. const newAttribute = convertBufferAttribute( attribute, indices );
  6194. morphArray.push( newAttribute );
  6195. }
  6196. geometry2.morphAttributes[ name ] = morphArray;
  6197. }
  6198. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6199. // groups
  6200. const groups = this.groups;
  6201. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6202. const group = groups[ i ];
  6203. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6204. }
  6205. return geometry2;
  6206. },
  6207. toJSON: function () {
  6208. const data = {
  6209. metadata: {
  6210. version: 4.5,
  6211. type: 'BufferGeometry',
  6212. generator: 'BufferGeometry.toJSON'
  6213. }
  6214. };
  6215. // standard BufferGeometry serialization
  6216. data.uuid = this.uuid;
  6217. data.type = this.type;
  6218. if ( this.name !== '' ) data.name = this.name;
  6219. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6220. if ( this.parameters !== undefined ) {
  6221. const parameters = this.parameters;
  6222. for ( const key in parameters ) {
  6223. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6224. }
  6225. return data;
  6226. }
  6227. data.data = { attributes: {} };
  6228. const index = this.index;
  6229. if ( index !== null ) {
  6230. data.data.index = {
  6231. type: index.array.constructor.name,
  6232. array: Array.prototype.slice.call( index.array )
  6233. };
  6234. }
  6235. const attributes = this.attributes;
  6236. for ( const key in attributes ) {
  6237. const attribute = attributes[ key ];
  6238. const attributeData = attribute.toJSON( data.data );
  6239. if ( attribute.name !== '' ) attributeData.name = attribute.name;
  6240. data.data.attributes[ key ] = attributeData;
  6241. }
  6242. const morphAttributes = {};
  6243. let hasMorphAttributes = false;
  6244. for ( const key in this.morphAttributes ) {
  6245. const attributeArray = this.morphAttributes[ key ];
  6246. const array = [];
  6247. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6248. const attribute = attributeArray[ i ];
  6249. const attributeData = attribute.toJSON( data.data );
  6250. if ( attribute.name !== '' ) attributeData.name = attribute.name;
  6251. array.push( attributeData );
  6252. }
  6253. if ( array.length > 0 ) {
  6254. morphAttributes[ key ] = array;
  6255. hasMorphAttributes = true;
  6256. }
  6257. }
  6258. if ( hasMorphAttributes ) {
  6259. data.data.morphAttributes = morphAttributes;
  6260. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6261. }
  6262. const groups = this.groups;
  6263. if ( groups.length > 0 ) {
  6264. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6265. }
  6266. const boundingSphere = this.boundingSphere;
  6267. if ( boundingSphere !== null ) {
  6268. data.data.boundingSphere = {
  6269. center: boundingSphere.center.toArray(),
  6270. radius: boundingSphere.radius
  6271. };
  6272. }
  6273. return data;
  6274. },
  6275. clone: function () {
  6276. /*
  6277. // Handle primitives
  6278. const parameters = this.parameters;
  6279. if ( parameters !== undefined ) {
  6280. const values = [];
  6281. for ( const key in parameters ) {
  6282. values.push( parameters[ key ] );
  6283. }
  6284. const geometry = Object.create( this.constructor.prototype );
  6285. this.constructor.apply( geometry, values );
  6286. return geometry;
  6287. }
  6288. return new this.constructor().copy( this );
  6289. */
  6290. return new BufferGeometry().copy( this );
  6291. },
  6292. copy: function ( source ) {
  6293. // reset
  6294. this.index = null;
  6295. this.attributes = {};
  6296. this.morphAttributes = {};
  6297. this.groups = [];
  6298. this.boundingBox = null;
  6299. this.boundingSphere = null;
  6300. // used for storing cloned, shared data
  6301. const data = {};
  6302. // name
  6303. this.name = source.name;
  6304. // index
  6305. const index = source.index;
  6306. if ( index !== null ) {
  6307. this.setIndex( index.clone( data ) );
  6308. }
  6309. // attributes
  6310. const attributes = source.attributes;
  6311. for ( const name in attributes ) {
  6312. const attribute = attributes[ name ];
  6313. this.setAttribute( name, attribute.clone( data ) );
  6314. }
  6315. // morph attributes
  6316. const morphAttributes = source.morphAttributes;
  6317. for ( const name in morphAttributes ) {
  6318. const array = [];
  6319. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6320. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6321. array.push( morphAttribute[ i ].clone( data ) );
  6322. }
  6323. this.morphAttributes[ name ] = array;
  6324. }
  6325. this.morphTargetsRelative = source.morphTargetsRelative;
  6326. // groups
  6327. const groups = source.groups;
  6328. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6329. const group = groups[ i ];
  6330. this.addGroup( group.start, group.count, group.materialIndex );
  6331. }
  6332. // bounding box
  6333. const boundingBox = source.boundingBox;
  6334. if ( boundingBox !== null ) {
  6335. this.boundingBox = boundingBox.clone();
  6336. }
  6337. // bounding sphere
  6338. const boundingSphere = source.boundingSphere;
  6339. if ( boundingSphere !== null ) {
  6340. this.boundingSphere = boundingSphere.clone();
  6341. }
  6342. // draw range
  6343. this.drawRange.start = source.drawRange.start;
  6344. this.drawRange.count = source.drawRange.count;
  6345. // user data
  6346. this.userData = source.userData;
  6347. return this;
  6348. },
  6349. dispose: function () {
  6350. this.dispatchEvent( { type: 'dispose' } );
  6351. }
  6352. } );
  6353. const _inverseMatrix = new Matrix4();
  6354. const _ray = new Ray();
  6355. const _sphere = new Sphere();
  6356. const _vA = new Vector3();
  6357. const _vB = new Vector3();
  6358. const _vC = new Vector3();
  6359. const _tempA = new Vector3();
  6360. const _tempB = new Vector3();
  6361. const _tempC = new Vector3();
  6362. const _morphA = new Vector3();
  6363. const _morphB = new Vector3();
  6364. const _morphC = new Vector3();
  6365. const _uvA = new Vector2();
  6366. const _uvB = new Vector2();
  6367. const _uvC = new Vector2();
  6368. const _intersectionPoint = new Vector3();
  6369. const _intersectionPointWorld = new Vector3();
  6370. function Mesh( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6371. Object3D.call( this );
  6372. this.type = 'Mesh';
  6373. this.geometry = geometry;
  6374. this.material = material;
  6375. this.updateMorphTargets();
  6376. }
  6377. Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
  6378. constructor: Mesh,
  6379. isMesh: true,
  6380. copy: function ( source ) {
  6381. Object3D.prototype.copy.call( this, source );
  6382. if ( source.morphTargetInfluences !== undefined ) {
  6383. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6384. }
  6385. if ( source.morphTargetDictionary !== undefined ) {
  6386. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6387. }
  6388. this.material = source.material;
  6389. this.geometry = source.geometry;
  6390. return this;
  6391. },
  6392. updateMorphTargets: function () {
  6393. const geometry = this.geometry;
  6394. if ( geometry.isBufferGeometry ) {
  6395. const morphAttributes = geometry.morphAttributes;
  6396. const keys = Object.keys( morphAttributes );
  6397. if ( keys.length > 0 ) {
  6398. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6399. if ( morphAttribute !== undefined ) {
  6400. this.morphTargetInfluences = [];
  6401. this.morphTargetDictionary = {};
  6402. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6403. const name = morphAttribute[ m ].name || String( m );
  6404. this.morphTargetInfluences.push( 0 );
  6405. this.morphTargetDictionary[ name ] = m;
  6406. }
  6407. }
  6408. }
  6409. } else {
  6410. const morphTargets = geometry.morphTargets;
  6411. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  6412. console.error( 'THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  6413. }
  6414. }
  6415. },
  6416. raycast: function ( raycaster, intersects ) {
  6417. const geometry = this.geometry;
  6418. const material = this.material;
  6419. const matrixWorld = this.matrixWorld;
  6420. if ( material === undefined ) return;
  6421. // Checking boundingSphere distance to ray
  6422. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6423. _sphere.copy( geometry.boundingSphere );
  6424. _sphere.applyMatrix4( matrixWorld );
  6425. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  6426. //
  6427. _inverseMatrix.copy( matrixWorld ).invert();
  6428. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  6429. // Check boundingBox before continuing
  6430. if ( geometry.boundingBox !== null ) {
  6431. if ( _ray.intersectsBox( geometry.boundingBox ) === false ) return;
  6432. }
  6433. let intersection;
  6434. if ( geometry.isBufferGeometry ) {
  6435. const index = geometry.index;
  6436. const position = geometry.attributes.position;
  6437. const morphPosition = geometry.morphAttributes.position;
  6438. const morphTargetsRelative = geometry.morphTargetsRelative;
  6439. const uv = geometry.attributes.uv;
  6440. const uv2 = geometry.attributes.uv2;
  6441. const groups = geometry.groups;
  6442. const drawRange = geometry.drawRange;
  6443. if ( index !== null ) {
  6444. // indexed buffer geometry
  6445. if ( Array.isArray( material ) ) {
  6446. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6447. const group = groups[ i ];
  6448. const groupMaterial = material[ group.materialIndex ];
  6449. const start = Math.max( group.start, drawRange.start );
  6450. const end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  6451. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6452. const a = index.getX( j );
  6453. const b = index.getX( j + 1 );
  6454. const c = index.getX( j + 2 );
  6455. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6456. if ( intersection ) {
  6457. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  6458. intersection.face.materialIndex = group.materialIndex;
  6459. intersects.push( intersection );
  6460. }
  6461. }
  6462. }
  6463. } else {
  6464. const start = Math.max( 0, drawRange.start );
  6465. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  6466. for ( let i = start, il = end; i < il; i += 3 ) {
  6467. const a = index.getX( i );
  6468. const b = index.getX( i + 1 );
  6469. const c = index.getX( i + 2 );
  6470. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6471. if ( intersection ) {
  6472. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  6473. intersects.push( intersection );
  6474. }
  6475. }
  6476. }
  6477. } else if ( position !== undefined ) {
  6478. // non-indexed buffer geometry
  6479. if ( Array.isArray( material ) ) {
  6480. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6481. const group = groups[ i ];
  6482. const groupMaterial = material[ group.materialIndex ];
  6483. const start = Math.max( group.start, drawRange.start );
  6484. const end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  6485. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6486. const a = j;
  6487. const b = j + 1;
  6488. const c = j + 2;
  6489. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6490. if ( intersection ) {
  6491. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  6492. intersection.face.materialIndex = group.materialIndex;
  6493. intersects.push( intersection );
  6494. }
  6495. }
  6496. }
  6497. } else {
  6498. const start = Math.max( 0, drawRange.start );
  6499. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  6500. for ( let i = start, il = end; i < il; i += 3 ) {
  6501. const a = i;
  6502. const b = i + 1;
  6503. const c = i + 2;
  6504. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6505. if ( intersection ) {
  6506. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  6507. intersects.push( intersection );
  6508. }
  6509. }
  6510. }
  6511. }
  6512. } else if ( geometry.isGeometry ) {
  6513. console.error( 'THREE.Mesh.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  6514. }
  6515. }
  6516. } );
  6517. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  6518. let intersect;
  6519. if ( material.side === BackSide ) {
  6520. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  6521. } else {
  6522. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  6523. }
  6524. if ( intersect === null ) return null;
  6525. _intersectionPointWorld.copy( point );
  6526. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  6527. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  6528. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  6529. return {
  6530. distance: distance,
  6531. point: _intersectionPointWorld.clone(),
  6532. object: object
  6533. };
  6534. }
  6535. function checkBufferGeometryIntersection( object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ) {
  6536. _vA.fromBufferAttribute( position, a );
  6537. _vB.fromBufferAttribute( position, b );
  6538. _vC.fromBufferAttribute( position, c );
  6539. const morphInfluences = object.morphTargetInfluences;
  6540. if ( material.morphTargets && morphPosition && morphInfluences ) {
  6541. _morphA.set( 0, 0, 0 );
  6542. _morphB.set( 0, 0, 0 );
  6543. _morphC.set( 0, 0, 0 );
  6544. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6545. const influence = morphInfluences[ i ];
  6546. const morphAttribute = morphPosition[ i ];
  6547. if ( influence === 0 ) continue;
  6548. _tempA.fromBufferAttribute( morphAttribute, a );
  6549. _tempB.fromBufferAttribute( morphAttribute, b );
  6550. _tempC.fromBufferAttribute( morphAttribute, c );
  6551. if ( morphTargetsRelative ) {
  6552. _morphA.addScaledVector( _tempA, influence );
  6553. _morphB.addScaledVector( _tempB, influence );
  6554. _morphC.addScaledVector( _tempC, influence );
  6555. } else {
  6556. _morphA.addScaledVector( _tempA.sub( _vA ), influence );
  6557. _morphB.addScaledVector( _tempB.sub( _vB ), influence );
  6558. _morphC.addScaledVector( _tempC.sub( _vC ), influence );
  6559. }
  6560. }
  6561. _vA.add( _morphA );
  6562. _vB.add( _morphB );
  6563. _vC.add( _morphC );
  6564. }
  6565. if ( object.isSkinnedMesh && material.skinning ) {
  6566. object.boneTransform( a, _vA );
  6567. object.boneTransform( b, _vB );
  6568. object.boneTransform( c, _vC );
  6569. }
  6570. const intersection = checkIntersection( object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint );
  6571. if ( intersection ) {
  6572. if ( uv ) {
  6573. _uvA.fromBufferAttribute( uv, a );
  6574. _uvB.fromBufferAttribute( uv, b );
  6575. _uvC.fromBufferAttribute( uv, c );
  6576. intersection.uv = Triangle.getUV( _intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() );
  6577. }
  6578. if ( uv2 ) {
  6579. _uvA.fromBufferAttribute( uv2, a );
  6580. _uvB.fromBufferAttribute( uv2, b );
  6581. _uvC.fromBufferAttribute( uv2, c );
  6582. intersection.uv2 = Triangle.getUV( _intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() );
  6583. }
  6584. const face = {
  6585. a: a,
  6586. b: b,
  6587. c: c,
  6588. normal: new Vector3(),
  6589. materialIndex: 0
  6590. };
  6591. Triangle.getNormal( _vA, _vB, _vC, face.normal );
  6592. intersection.face = face;
  6593. }
  6594. return intersection;
  6595. }
  6596. class BoxGeometry extends BufferGeometry {
  6597. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  6598. super();
  6599. this.type = 'BoxGeometry';
  6600. this.parameters = {
  6601. width: width,
  6602. height: height,
  6603. depth: depth,
  6604. widthSegments: widthSegments,
  6605. heightSegments: heightSegments,
  6606. depthSegments: depthSegments
  6607. };
  6608. const scope = this;
  6609. // segments
  6610. widthSegments = Math.floor( widthSegments );
  6611. heightSegments = Math.floor( heightSegments );
  6612. depthSegments = Math.floor( depthSegments );
  6613. // buffers
  6614. const indices = [];
  6615. const vertices = [];
  6616. const normals = [];
  6617. const uvs = [];
  6618. // helper variables
  6619. let numberOfVertices = 0;
  6620. let groupStart = 0;
  6621. // build each side of the box geometry
  6622. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  6623. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  6624. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  6625. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  6626. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  6627. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  6628. // build geometry
  6629. this.setIndex( indices );
  6630. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  6631. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  6632. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  6633. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  6634. const segmentWidth = width / gridX;
  6635. const segmentHeight = height / gridY;
  6636. const widthHalf = width / 2;
  6637. const heightHalf = height / 2;
  6638. const depthHalf = depth / 2;
  6639. const gridX1 = gridX + 1;
  6640. const gridY1 = gridY + 1;
  6641. let vertexCounter = 0;
  6642. let groupCount = 0;
  6643. const vector = new Vector3();
  6644. // generate vertices, normals and uvs
  6645. for ( let iy = 0; iy < gridY1; iy ++ ) {
  6646. const y = iy * segmentHeight - heightHalf;
  6647. for ( let ix = 0; ix < gridX1; ix ++ ) {
  6648. const x = ix * segmentWidth - widthHalf;
  6649. // set values to correct vector component
  6650. vector[ u ] = x * udir;
  6651. vector[ v ] = y * vdir;
  6652. vector[ w ] = depthHalf;
  6653. // now apply vector to vertex buffer
  6654. vertices.push( vector.x, vector.y, vector.z );
  6655. // set values to correct vector component
  6656. vector[ u ] = 0;
  6657. vector[ v ] = 0;
  6658. vector[ w ] = depth > 0 ? 1 : - 1;
  6659. // now apply vector to normal buffer
  6660. normals.push( vector.x, vector.y, vector.z );
  6661. // uvs
  6662. uvs.push( ix / gridX );
  6663. uvs.push( 1 - ( iy / gridY ) );
  6664. // counters
  6665. vertexCounter += 1;
  6666. }
  6667. }
  6668. // indices
  6669. // 1. you need three indices to draw a single face
  6670. // 2. a single segment consists of two faces
  6671. // 3. so we need to generate six (2*3) indices per segment
  6672. for ( let iy = 0; iy < gridY; iy ++ ) {
  6673. for ( let ix = 0; ix < gridX; ix ++ ) {
  6674. const a = numberOfVertices + ix + gridX1 * iy;
  6675. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  6676. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  6677. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  6678. // faces
  6679. indices.push( a, b, d );
  6680. indices.push( b, c, d );
  6681. // increase counter
  6682. groupCount += 6;
  6683. }
  6684. }
  6685. // add a group to the geometry. this will ensure multi material support
  6686. scope.addGroup( groupStart, groupCount, materialIndex );
  6687. // calculate new start value for groups
  6688. groupStart += groupCount;
  6689. // update total number of vertices
  6690. numberOfVertices += vertexCounter;
  6691. }
  6692. }
  6693. }
  6694. /**
  6695. * Uniform Utilities
  6696. */
  6697. function cloneUniforms( src ) {
  6698. const dst = {};
  6699. for ( const u in src ) {
  6700. dst[ u ] = {};
  6701. for ( const p in src[ u ] ) {
  6702. const property = src[ u ][ p ];
  6703. if ( property && ( property.isColor ||
  6704. property.isMatrix3 || property.isMatrix4 ||
  6705. property.isVector2 || property.isVector3 || property.isVector4 ||
  6706. property.isTexture || property.isQuaternion ) ) {
  6707. dst[ u ][ p ] = property.clone();
  6708. } else if ( Array.isArray( property ) ) {
  6709. dst[ u ][ p ] = property.slice();
  6710. } else {
  6711. dst[ u ][ p ] = property;
  6712. }
  6713. }
  6714. }
  6715. return dst;
  6716. }
  6717. function mergeUniforms( uniforms ) {
  6718. const merged = {};
  6719. for ( let u = 0; u < uniforms.length; u ++ ) {
  6720. const tmp = cloneUniforms( uniforms[ u ] );
  6721. for ( const p in tmp ) {
  6722. merged[ p ] = tmp[ p ];
  6723. }
  6724. }
  6725. return merged;
  6726. }
  6727. // Legacy
  6728. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  6729. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  6730. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  6731. /**
  6732. * parameters = {
  6733. * defines: { "label" : "value" },
  6734. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  6735. *
  6736. * fragmentShader: <string>,
  6737. * vertexShader: <string>,
  6738. *
  6739. * wireframe: <boolean>,
  6740. * wireframeLinewidth: <float>,
  6741. *
  6742. * lights: <bool>,
  6743. *
  6744. * skinning: <bool>,
  6745. * morphTargets: <bool>,
  6746. * morphNormals: <bool>
  6747. * }
  6748. */
  6749. function ShaderMaterial( parameters ) {
  6750. Material.call( this );
  6751. this.type = 'ShaderMaterial';
  6752. this.defines = {};
  6753. this.uniforms = {};
  6754. this.vertexShader = default_vertex;
  6755. this.fragmentShader = default_fragment;
  6756. this.linewidth = 1;
  6757. this.wireframe = false;
  6758. this.wireframeLinewidth = 1;
  6759. this.fog = false; // set to use scene fog
  6760. this.lights = false; // set to use scene lights
  6761. this.clipping = false; // set to use user-defined clipping planes
  6762. this.skinning = false; // set to use skinning attribute streams
  6763. this.morphTargets = false; // set to use morph targets
  6764. this.morphNormals = false; // set to use morph normals
  6765. this.extensions = {
  6766. derivatives: false, // set to use derivatives
  6767. fragDepth: false, // set to use fragment depth values
  6768. drawBuffers: false, // set to use draw buffers
  6769. shaderTextureLOD: false // set to use shader texture LOD
  6770. };
  6771. // When rendered geometry doesn't include these attributes but the material does,
  6772. // use these default values in WebGL. This avoids errors when buffer data is missing.
  6773. this.defaultAttributeValues = {
  6774. 'color': [ 1, 1, 1 ],
  6775. 'uv': [ 0, 0 ],
  6776. 'uv2': [ 0, 0 ]
  6777. };
  6778. this.index0AttributeName = undefined;
  6779. this.uniformsNeedUpdate = false;
  6780. this.glslVersion = null;
  6781. if ( parameters !== undefined ) {
  6782. if ( parameters.attributes !== undefined ) {
  6783. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  6784. }
  6785. this.setValues( parameters );
  6786. }
  6787. }
  6788. ShaderMaterial.prototype = Object.create( Material.prototype );
  6789. ShaderMaterial.prototype.constructor = ShaderMaterial;
  6790. ShaderMaterial.prototype.isShaderMaterial = true;
  6791. ShaderMaterial.prototype.copy = function ( source ) {
  6792. Material.prototype.copy.call( this, source );
  6793. this.fragmentShader = source.fragmentShader;
  6794. this.vertexShader = source.vertexShader;
  6795. this.uniforms = cloneUniforms( source.uniforms );
  6796. this.defines = Object.assign( {}, source.defines );
  6797. this.wireframe = source.wireframe;
  6798. this.wireframeLinewidth = source.wireframeLinewidth;
  6799. this.lights = source.lights;
  6800. this.clipping = source.clipping;
  6801. this.skinning = source.skinning;
  6802. this.morphTargets = source.morphTargets;
  6803. this.morphNormals = source.morphNormals;
  6804. this.extensions = Object.assign( {}, source.extensions );
  6805. this.glslVersion = source.glslVersion;
  6806. return this;
  6807. };
  6808. ShaderMaterial.prototype.toJSON = function ( meta ) {
  6809. const data = Material.prototype.toJSON.call( this, meta );
  6810. data.glslVersion = this.glslVersion;
  6811. data.uniforms = {};
  6812. for ( const name in this.uniforms ) {
  6813. const uniform = this.uniforms[ name ];
  6814. const value = uniform.value;
  6815. if ( value && value.isTexture ) {
  6816. data.uniforms[ name ] = {
  6817. type: 't',
  6818. value: value.toJSON( meta ).uuid
  6819. };
  6820. } else if ( value && value.isColor ) {
  6821. data.uniforms[ name ] = {
  6822. type: 'c',
  6823. value: value.getHex()
  6824. };
  6825. } else if ( value && value.isVector2 ) {
  6826. data.uniforms[ name ] = {
  6827. type: 'v2',
  6828. value: value.toArray()
  6829. };
  6830. } else if ( value && value.isVector3 ) {
  6831. data.uniforms[ name ] = {
  6832. type: 'v3',
  6833. value: value.toArray()
  6834. };
  6835. } else if ( value && value.isVector4 ) {
  6836. data.uniforms[ name ] = {
  6837. type: 'v4',
  6838. value: value.toArray()
  6839. };
  6840. } else if ( value && value.isMatrix3 ) {
  6841. data.uniforms[ name ] = {
  6842. type: 'm3',
  6843. value: value.toArray()
  6844. };
  6845. } else if ( value && value.isMatrix4 ) {
  6846. data.uniforms[ name ] = {
  6847. type: 'm4',
  6848. value: value.toArray()
  6849. };
  6850. } else {
  6851. data.uniforms[ name ] = {
  6852. value: value
  6853. };
  6854. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  6855. }
  6856. }
  6857. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  6858. data.vertexShader = this.vertexShader;
  6859. data.fragmentShader = this.fragmentShader;
  6860. const extensions = {};
  6861. for ( const key in this.extensions ) {
  6862. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  6863. }
  6864. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  6865. return data;
  6866. };
  6867. function Camera() {
  6868. Object3D.call( this );
  6869. this.type = 'Camera';
  6870. this.matrixWorldInverse = new Matrix4();
  6871. this.projectionMatrix = new Matrix4();
  6872. this.projectionMatrixInverse = new Matrix4();
  6873. }
  6874. Camera.prototype = Object.assign( Object.create( Object3D.prototype ), {
  6875. constructor: Camera,
  6876. isCamera: true,
  6877. copy: function ( source, recursive ) {
  6878. Object3D.prototype.copy.call( this, source, recursive );
  6879. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  6880. this.projectionMatrix.copy( source.projectionMatrix );
  6881. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  6882. return this;
  6883. },
  6884. getWorldDirection: function ( target ) {
  6885. if ( target === undefined ) {
  6886. console.warn( 'THREE.Camera: .getWorldDirection() target is now required' );
  6887. target = new Vector3();
  6888. }
  6889. this.updateWorldMatrix( true, false );
  6890. const e = this.matrixWorld.elements;
  6891. return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize();
  6892. },
  6893. updateMatrixWorld: function ( force ) {
  6894. Object3D.prototype.updateMatrixWorld.call( this, force );
  6895. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  6896. },
  6897. updateWorldMatrix: function ( updateParents, updateChildren ) {
  6898. Object3D.prototype.updateWorldMatrix.call( this, updateParents, updateChildren );
  6899. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  6900. },
  6901. clone: function () {
  6902. return new this.constructor().copy( this );
  6903. }
  6904. } );
  6905. function PerspectiveCamera( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  6906. Camera.call( this );
  6907. this.type = 'PerspectiveCamera';
  6908. this.fov = fov;
  6909. this.zoom = 1;
  6910. this.near = near;
  6911. this.far = far;
  6912. this.focus = 10;
  6913. this.aspect = aspect;
  6914. this.view = null;
  6915. this.filmGauge = 35; // width of the film (default in millimeters)
  6916. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  6917. this.updateProjectionMatrix();
  6918. }
  6919. PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  6920. constructor: PerspectiveCamera,
  6921. isPerspectiveCamera: true,
  6922. copy: function ( source, recursive ) {
  6923. Camera.prototype.copy.call( this, source, recursive );
  6924. this.fov = source.fov;
  6925. this.zoom = source.zoom;
  6926. this.near = source.near;
  6927. this.far = source.far;
  6928. this.focus = source.focus;
  6929. this.aspect = source.aspect;
  6930. this.view = source.view === null ? null : Object.assign( {}, source.view );
  6931. this.filmGauge = source.filmGauge;
  6932. this.filmOffset = source.filmOffset;
  6933. return this;
  6934. },
  6935. /**
  6936. * Sets the FOV by focal length in respect to the current .filmGauge.
  6937. *
  6938. * The default film gauge is 35, so that the focal length can be specified for
  6939. * a 35mm (full frame) camera.
  6940. *
  6941. * Values for focal length and film gauge must have the same unit.
  6942. */
  6943. setFocalLength: function ( focalLength ) {
  6944. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  6945. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  6946. this.fov = MathUtils.RAD2DEG * 2 * Math.atan( vExtentSlope );
  6947. this.updateProjectionMatrix();
  6948. },
  6949. /**
  6950. * Calculates the focal length from the current .fov and .filmGauge.
  6951. */
  6952. getFocalLength: function () {
  6953. const vExtentSlope = Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov );
  6954. return 0.5 * this.getFilmHeight() / vExtentSlope;
  6955. },
  6956. getEffectiveFOV: function () {
  6957. return MathUtils.RAD2DEG * 2 * Math.atan(
  6958. Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov ) / this.zoom );
  6959. },
  6960. getFilmWidth: function () {
  6961. // film not completely covered in portrait format (aspect < 1)
  6962. return this.filmGauge * Math.min( this.aspect, 1 );
  6963. },
  6964. getFilmHeight: function () {
  6965. // film not completely covered in landscape format (aspect > 1)
  6966. return this.filmGauge / Math.max( this.aspect, 1 );
  6967. },
  6968. /**
  6969. * Sets an offset in a larger frustum. This is useful for multi-window or
  6970. * multi-monitor/multi-machine setups.
  6971. *
  6972. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  6973. * the monitors are in grid like this
  6974. *
  6975. * +---+---+---+
  6976. * | A | B | C |
  6977. * +---+---+---+
  6978. * | D | E | F |
  6979. * +---+---+---+
  6980. *
  6981. * then for each monitor you would call it like this
  6982. *
  6983. * const w = 1920;
  6984. * const h = 1080;
  6985. * const fullWidth = w * 3;
  6986. * const fullHeight = h * 2;
  6987. *
  6988. * --A--
  6989. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  6990. * --B--
  6991. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  6992. * --C--
  6993. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  6994. * --D--
  6995. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  6996. * --E--
  6997. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  6998. * --F--
  6999. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7000. *
  7001. * Note there is no reason monitors have to be the same size or in a grid.
  7002. */
  7003. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  7004. this.aspect = fullWidth / fullHeight;
  7005. if ( this.view === null ) {
  7006. this.view = {
  7007. enabled: true,
  7008. fullWidth: 1,
  7009. fullHeight: 1,
  7010. offsetX: 0,
  7011. offsetY: 0,
  7012. width: 1,
  7013. height: 1
  7014. };
  7015. }
  7016. this.view.enabled = true;
  7017. this.view.fullWidth = fullWidth;
  7018. this.view.fullHeight = fullHeight;
  7019. this.view.offsetX = x;
  7020. this.view.offsetY = y;
  7021. this.view.width = width;
  7022. this.view.height = height;
  7023. this.updateProjectionMatrix();
  7024. },
  7025. clearViewOffset: function () {
  7026. if ( this.view !== null ) {
  7027. this.view.enabled = false;
  7028. }
  7029. this.updateProjectionMatrix();
  7030. },
  7031. updateProjectionMatrix: function () {
  7032. const near = this.near;
  7033. let top = near * Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7034. let height = 2 * top;
  7035. let width = this.aspect * height;
  7036. let left = - 0.5 * width;
  7037. const view = this.view;
  7038. if ( this.view !== null && this.view.enabled ) {
  7039. const fullWidth = view.fullWidth,
  7040. fullHeight = view.fullHeight;
  7041. left += view.offsetX * width / fullWidth;
  7042. top -= view.offsetY * height / fullHeight;
  7043. width *= view.width / fullWidth;
  7044. height *= view.height / fullHeight;
  7045. }
  7046. const skew = this.filmOffset;
  7047. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7048. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  7049. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7050. },
  7051. toJSON: function ( meta ) {
  7052. const data = Object3D.prototype.toJSON.call( this, meta );
  7053. data.object.fov = this.fov;
  7054. data.object.zoom = this.zoom;
  7055. data.object.near = this.near;
  7056. data.object.far = this.far;
  7057. data.object.focus = this.focus;
  7058. data.object.aspect = this.aspect;
  7059. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7060. data.object.filmGauge = this.filmGauge;
  7061. data.object.filmOffset = this.filmOffset;
  7062. return data;
  7063. }
  7064. } );
  7065. const fov = 90, aspect = 1;
  7066. class CubeCamera extends Object3D {
  7067. constructor( near, far, renderTarget ) {
  7068. super();
  7069. this.type = 'CubeCamera';
  7070. if ( renderTarget.isWebGLCubeRenderTarget !== true ) {
  7071. console.error( 'THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.' );
  7072. return;
  7073. }
  7074. this.renderTarget = renderTarget;
  7075. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7076. cameraPX.layers = this.layers;
  7077. cameraPX.up.set( 0, - 1, 0 );
  7078. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  7079. this.add( cameraPX );
  7080. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7081. cameraNX.layers = this.layers;
  7082. cameraNX.up.set( 0, - 1, 0 );
  7083. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  7084. this.add( cameraNX );
  7085. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7086. cameraPY.layers = this.layers;
  7087. cameraPY.up.set( 0, 0, 1 );
  7088. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  7089. this.add( cameraPY );
  7090. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7091. cameraNY.layers = this.layers;
  7092. cameraNY.up.set( 0, 0, - 1 );
  7093. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  7094. this.add( cameraNY );
  7095. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7096. cameraPZ.layers = this.layers;
  7097. cameraPZ.up.set( 0, - 1, 0 );
  7098. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  7099. this.add( cameraPZ );
  7100. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7101. cameraNZ.layers = this.layers;
  7102. cameraNZ.up.set( 0, - 1, 0 );
  7103. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  7104. this.add( cameraNZ );
  7105. }
  7106. update( renderer, scene ) {
  7107. if ( this.parent === null ) this.updateMatrixWorld();
  7108. const renderTarget = this.renderTarget;
  7109. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7110. const currentXrEnabled = renderer.xr.enabled;
  7111. const currentRenderTarget = renderer.getRenderTarget();
  7112. renderer.xr.enabled = false;
  7113. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7114. renderTarget.texture.generateMipmaps = false;
  7115. renderer.setRenderTarget( renderTarget, 0 );
  7116. renderer.render( scene, cameraPX );
  7117. renderer.setRenderTarget( renderTarget, 1 );
  7118. renderer.render( scene, cameraNX );
  7119. renderer.setRenderTarget( renderTarget, 2 );
  7120. renderer.render( scene, cameraPY );
  7121. renderer.setRenderTarget( renderTarget, 3 );
  7122. renderer.render( scene, cameraNY );
  7123. renderer.setRenderTarget( renderTarget, 4 );
  7124. renderer.render( scene, cameraPZ );
  7125. renderTarget.texture.generateMipmaps = generateMipmaps;
  7126. renderer.setRenderTarget( renderTarget, 5 );
  7127. renderer.render( scene, cameraNZ );
  7128. renderer.setRenderTarget( currentRenderTarget );
  7129. renderer.xr.enabled = currentXrEnabled;
  7130. }
  7131. }
  7132. class CubeTexture extends Texture {
  7133. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  7134. images = images !== undefined ? images : [];
  7135. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7136. format = format !== undefined ? format : RGBFormat;
  7137. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  7138. // Why CubeTexture._needsFlipEnvMap is necessary:
  7139. //
  7140. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7141. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7142. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7143. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7144. // and the flag _needsFlipEnvMap controls this conversion. The flip is not required (and thus _needsFlipEnvMap is set to false)
  7145. // when using WebGLCubeRenderTarget.texture as a cube texture.
  7146. this._needsFlipEnvMap = true;
  7147. this.flipY = false;
  7148. }
  7149. get images() {
  7150. return this.image;
  7151. }
  7152. set images( value ) {
  7153. this.image = value;
  7154. }
  7155. }
  7156. CubeTexture.prototype.isCubeTexture = true;
  7157. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7158. constructor( size, options, dummy ) {
  7159. if ( Number.isInteger( options ) ) {
  7160. console.warn( 'THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )' );
  7161. options = dummy;
  7162. }
  7163. super( size, size, options );
  7164. options = options || {};
  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.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7167. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7168. this.texture._needsFlipEnvMap = false;
  7169. }
  7170. fromEquirectangularTexture( renderer, texture ) {
  7171. this.texture.type = texture.type;
  7172. this.texture.format = RGBAFormat; // see #18859
  7173. this.texture.encoding = texture.encoding;
  7174. this.texture.generateMipmaps = texture.generateMipmaps;
  7175. this.texture.minFilter = texture.minFilter;
  7176. this.texture.magFilter = texture.magFilter;
  7177. const shader = {
  7178. uniforms: {
  7179. tEquirect: { value: null },
  7180. },
  7181. vertexShader: /* glsl */`
  7182. varying vec3 vWorldDirection;
  7183. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7184. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7185. }
  7186. void main() {
  7187. vWorldDirection = transformDirection( position, modelMatrix );
  7188. #include <begin_vertex>
  7189. #include <project_vertex>
  7190. }
  7191. `,
  7192. fragmentShader: /* glsl */`
  7193. uniform sampler2D tEquirect;
  7194. varying vec3 vWorldDirection;
  7195. #include <common>
  7196. void main() {
  7197. vec3 direction = normalize( vWorldDirection );
  7198. vec2 sampleUV = equirectUv( direction );
  7199. gl_FragColor = texture2D( tEquirect, sampleUV );
  7200. }
  7201. `
  7202. };
  7203. const geometry = new BoxGeometry( 5, 5, 5 );
  7204. const material = new ShaderMaterial( {
  7205. name: 'CubemapFromEquirect',
  7206. uniforms: cloneUniforms( shader.uniforms ),
  7207. vertexShader: shader.vertexShader,
  7208. fragmentShader: shader.fragmentShader,
  7209. side: BackSide,
  7210. blending: NoBlending
  7211. } );
  7212. material.uniforms.tEquirect.value = texture;
  7213. const mesh = new Mesh( geometry, material );
  7214. const currentMinFilter = texture.minFilter;
  7215. // Avoid blurred poles
  7216. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7217. const camera = new CubeCamera( 1, 10, this );
  7218. camera.update( renderer, mesh );
  7219. texture.minFilter = currentMinFilter;
  7220. mesh.geometry.dispose();
  7221. mesh.material.dispose();
  7222. return this;
  7223. }
  7224. clear( renderer, color, depth, stencil ) {
  7225. const currentRenderTarget = renderer.getRenderTarget();
  7226. for ( let i = 0; i < 6; i ++ ) {
  7227. renderer.setRenderTarget( this, i );
  7228. renderer.clear( color, depth, stencil );
  7229. }
  7230. renderer.setRenderTarget( currentRenderTarget );
  7231. }
  7232. }
  7233. WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
  7234. class DataTexture extends Texture {
  7235. constructor( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  7236. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  7237. this.image = { data: data || null, width: width || 1, height: height || 1 };
  7238. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  7239. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  7240. this.generateMipmaps = false;
  7241. this.flipY = false;
  7242. this.unpackAlignment = 1;
  7243. this.needsUpdate = true;
  7244. }
  7245. }
  7246. DataTexture.prototype.isDataTexture = true;
  7247. const _sphere$1 = /*@__PURE__*/ new Sphere();
  7248. const _vector$5 = /*@__PURE__*/ new Vector3();
  7249. class Frustum {
  7250. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  7251. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  7252. }
  7253. set( p0, p1, p2, p3, p4, p5 ) {
  7254. const planes = this.planes;
  7255. planes[ 0 ].copy( p0 );
  7256. planes[ 1 ].copy( p1 );
  7257. planes[ 2 ].copy( p2 );
  7258. planes[ 3 ].copy( p3 );
  7259. planes[ 4 ].copy( p4 );
  7260. planes[ 5 ].copy( p5 );
  7261. return this;
  7262. }
  7263. copy( frustum ) {
  7264. const planes = this.planes;
  7265. for ( let i = 0; i < 6; i ++ ) {
  7266. planes[ i ].copy( frustum.planes[ i ] );
  7267. }
  7268. return this;
  7269. }
  7270. setFromProjectionMatrix( m ) {
  7271. const planes = this.planes;
  7272. const me = m.elements;
  7273. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  7274. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  7275. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  7276. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  7277. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  7278. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  7279. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  7280. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  7281. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  7282. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  7283. return this;
  7284. }
  7285. intersectsObject( object ) {
  7286. const geometry = object.geometry;
  7287. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7288. _sphere$1.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  7289. return this.intersectsSphere( _sphere$1 );
  7290. }
  7291. intersectsSprite( sprite ) {
  7292. _sphere$1.center.set( 0, 0, 0 );
  7293. _sphere$1.radius = 0.7071067811865476;
  7294. _sphere$1.applyMatrix4( sprite.matrixWorld );
  7295. return this.intersectsSphere( _sphere$1 );
  7296. }
  7297. intersectsSphere( sphere ) {
  7298. const planes = this.planes;
  7299. const center = sphere.center;
  7300. const negRadius = - sphere.radius;
  7301. for ( let i = 0; i < 6; i ++ ) {
  7302. const distance = planes[ i ].distanceToPoint( center );
  7303. if ( distance < negRadius ) {
  7304. return false;
  7305. }
  7306. }
  7307. return true;
  7308. }
  7309. intersectsBox( box ) {
  7310. const planes = this.planes;
  7311. for ( let i = 0; i < 6; i ++ ) {
  7312. const plane = planes[ i ];
  7313. // corner at max distance
  7314. _vector$5.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7315. _vector$5.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7316. _vector$5.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7317. if ( plane.distanceToPoint( _vector$5 ) < 0 ) {
  7318. return false;
  7319. }
  7320. }
  7321. return true;
  7322. }
  7323. containsPoint( point ) {
  7324. const planes = this.planes;
  7325. for ( let i = 0; i < 6; i ++ ) {
  7326. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  7327. return false;
  7328. }
  7329. }
  7330. return true;
  7331. }
  7332. clone() {
  7333. return new this.constructor().copy( this );
  7334. }
  7335. }
  7336. function WebGLAnimation() {
  7337. let context = null;
  7338. let isAnimating = false;
  7339. let animationLoop = null;
  7340. let requestId = null;
  7341. function onAnimationFrame( time, frame ) {
  7342. animationLoop( time, frame );
  7343. requestId = context.requestAnimationFrame( onAnimationFrame );
  7344. }
  7345. return {
  7346. start: function () {
  7347. if ( isAnimating === true ) return;
  7348. if ( animationLoop === null ) return;
  7349. requestId = context.requestAnimationFrame( onAnimationFrame );
  7350. isAnimating = true;
  7351. },
  7352. stop: function () {
  7353. context.cancelAnimationFrame( requestId );
  7354. isAnimating = false;
  7355. },
  7356. setAnimationLoop: function ( callback ) {
  7357. animationLoop = callback;
  7358. },
  7359. setContext: function ( value ) {
  7360. context = value;
  7361. }
  7362. };
  7363. }
  7364. function WebGLAttributes( gl, capabilities ) {
  7365. const isWebGL2 = capabilities.isWebGL2;
  7366. const buffers = new WeakMap();
  7367. function createBuffer( attribute, bufferType ) {
  7368. const array = attribute.array;
  7369. const usage = attribute.usage;
  7370. const buffer = gl.createBuffer();
  7371. gl.bindBuffer( bufferType, buffer );
  7372. gl.bufferData( bufferType, array, usage );
  7373. attribute.onUploadCallback();
  7374. let type = 5126;
  7375. if ( array instanceof Float32Array ) {
  7376. type = 5126;
  7377. } else if ( array instanceof Float64Array ) {
  7378. console.warn( 'THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.' );
  7379. } else if ( array instanceof Uint16Array ) {
  7380. if ( attribute.isFloat16BufferAttribute ) {
  7381. if ( isWebGL2 ) {
  7382. type = 5131;
  7383. } else {
  7384. console.warn( 'THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.' );
  7385. }
  7386. } else {
  7387. type = 5123;
  7388. }
  7389. } else if ( array instanceof Int16Array ) {
  7390. type = 5122;
  7391. } else if ( array instanceof Uint32Array ) {
  7392. type = 5125;
  7393. } else if ( array instanceof Int32Array ) {
  7394. type = 5124;
  7395. } else if ( array instanceof Int8Array ) {
  7396. type = 5120;
  7397. } else if ( array instanceof Uint8Array ) {
  7398. type = 5121;
  7399. }
  7400. return {
  7401. buffer: buffer,
  7402. type: type,
  7403. bytesPerElement: array.BYTES_PER_ELEMENT,
  7404. version: attribute.version
  7405. };
  7406. }
  7407. function updateBuffer( buffer, attribute, bufferType ) {
  7408. const array = attribute.array;
  7409. const updateRange = attribute.updateRange;
  7410. gl.bindBuffer( bufferType, buffer );
  7411. if ( updateRange.count === - 1 ) {
  7412. // Not using update ranges
  7413. gl.bufferSubData( bufferType, 0, array );
  7414. } else {
  7415. if ( isWebGL2 ) {
  7416. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7417. array, updateRange.offset, updateRange.count );
  7418. } else {
  7419. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7420. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  7421. }
  7422. updateRange.count = - 1; // reset range
  7423. }
  7424. }
  7425. //
  7426. function get( attribute ) {
  7427. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7428. return buffers.get( attribute );
  7429. }
  7430. function remove( attribute ) {
  7431. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7432. const data = buffers.get( attribute );
  7433. if ( data ) {
  7434. gl.deleteBuffer( data.buffer );
  7435. buffers.delete( attribute );
  7436. }
  7437. }
  7438. function update( attribute, bufferType ) {
  7439. if ( attribute.isGLBufferAttribute ) {
  7440. const cached = buffers.get( attribute );
  7441. if ( ! cached || cached.version < attribute.version ) {
  7442. buffers.set( attribute, {
  7443. buffer: attribute.buffer,
  7444. type: attribute.type,
  7445. bytesPerElement: attribute.elementSize,
  7446. version: attribute.version
  7447. } );
  7448. }
  7449. return;
  7450. }
  7451. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7452. const data = buffers.get( attribute );
  7453. if ( data === undefined ) {
  7454. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  7455. } else if ( data.version < attribute.version ) {
  7456. updateBuffer( data.buffer, attribute, bufferType );
  7457. data.version = attribute.version;
  7458. }
  7459. }
  7460. return {
  7461. get: get,
  7462. remove: remove,
  7463. update: update
  7464. };
  7465. }
  7466. class PlaneGeometry extends BufferGeometry {
  7467. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  7468. super();
  7469. this.type = 'PlaneGeometry';
  7470. this.parameters = {
  7471. width: width,
  7472. height: height,
  7473. widthSegments: widthSegments,
  7474. heightSegments: heightSegments
  7475. };
  7476. const width_half = width / 2;
  7477. const height_half = height / 2;
  7478. const gridX = Math.floor( widthSegments );
  7479. const gridY = Math.floor( heightSegments );
  7480. const gridX1 = gridX + 1;
  7481. const gridY1 = gridY + 1;
  7482. const segment_width = width / gridX;
  7483. const segment_height = height / gridY;
  7484. //
  7485. const indices = [];
  7486. const vertices = [];
  7487. const normals = [];
  7488. const uvs = [];
  7489. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7490. const y = iy * segment_height - height_half;
  7491. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7492. const x = ix * segment_width - width_half;
  7493. vertices.push( x, - y, 0 );
  7494. normals.push( 0, 0, 1 );
  7495. uvs.push( ix / gridX );
  7496. uvs.push( 1 - ( iy / gridY ) );
  7497. }
  7498. }
  7499. for ( let iy = 0; iy < gridY; iy ++ ) {
  7500. for ( let ix = 0; ix < gridX; ix ++ ) {
  7501. const a = ix + gridX1 * iy;
  7502. const b = ix + gridX1 * ( iy + 1 );
  7503. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  7504. const d = ( ix + 1 ) + gridX1 * iy;
  7505. indices.push( a, b, d );
  7506. indices.push( b, c, d );
  7507. }
  7508. }
  7509. this.setIndex( indices );
  7510. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7511. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7512. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7513. }
  7514. }
  7515. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  7516. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7517. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";
  7518. var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif";
  7519. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7520. var begin_vertex = "vec3 transformed = vec3( position );";
  7521. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  7522. var bsdfs = "vec2 integrateSpecularBRDF( const in float dotNV, const in float roughness ) {\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\treturn vec2( -1.04, 1.04 ) * a004 + r.zw;\n}\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n#else\n\tif( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t}\n\treturn 1.0;\n#endif\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nvec3 F_Schlick_RoughnessDependent( const in vec3 F0, const in float dotNV, const in float roughness ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotNV - 6.98316 ) * dotNV );\n\tvec3 Fr = max( vec3( 1.0 - roughness ), F0 ) - F0;\n\treturn Fr * fresnel + F0;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + viewDir );\n\tfloat dotNL = saturate( dot( normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nvec3 BRDF_Specular_GGX_Environment( const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\treturn specularColor * brdf.x + brdf.y;\n}\nvoid BRDF_Specular_Multiscattering_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tvec3 F = F_Schlick_RoughnessDependent( specularColor, dotNV, roughness );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\tvec3 FssEss = F * brdf.x + brdf.y;\n\tfloat Ess = brdf.x + brdf.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie(float roughness, float NoH) {\n\tfloat invAlpha = 1.0 / roughness;\n\tfloat cos2h = NoH * NoH;\n\tfloat sin2h = max(1.0 - cos2h, 0.0078125);\treturn (2.0 + invAlpha) * pow(sin2h, invAlpha * 0.5) / (2.0 * PI);\n}\nfloat V_Neubelt(float NoV, float NoL) {\n\treturn saturate(1.0 / (4.0 * (NoL + NoV - NoL * NoV)));\n}\nvec3 BRDF_Specular_Sheen( const in float roughness, const in vec3 L, const in GeometricContext geometry, vec3 specularColor ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 H = normalize( V + L );\n\tfloat dotNH = saturate( dot( N, H ) );\n\treturn specularColor * D_Charlie( roughness, dotNH ) * V_Neubelt( dot(N, V), dot(N, L) );\n}\n#endif";
  7523. 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";
  7524. 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";
  7525. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  7526. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  7527. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  7528. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7529. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  7530. var color_pars_vertex = "#if defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7531. var color_vertex = "#if defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor.xyz *= color.xyz;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif";
  7532. var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat max3( vec3 v ) { return max( max( v.x, v.y ), v.z ); }\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}";
  7533. 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";
  7534. 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";
  7535. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  7536. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  7537. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  7538. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  7539. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  7540. 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}";
  7541. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifndef ENVMAP_TYPE_CUBE_UV\n\t\tenvColor = envMapTexelToLinear( envColor );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";
  7542. 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";
  7543. 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";
  7544. 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";
  7545. 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";
  7546. var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = - mvPosition.z;\n#endif";
  7547. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";
  7548. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * fogDepth * fogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif";
  7549. var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float fogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif";
  7550. 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}";
  7551. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\treflectedLight.indirectDiffuse += PI * lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n#endif";
  7552. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7553. var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\nvIndirectFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n\tvIndirectBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\nvIndirectFront += getAmbientLightIrradiance( ambientLightColor );\nvIndirectFront += getLightProbeIrradiance( lightProbe, geometry );\n#ifdef DOUBLE_SIDED\n\tvIndirectBack += getAmbientLightIrradiance( ambientLightColor );\n\tvIndirectBack += getLightProbeIrradiance( lightProbe, backGeometry );\n#endif\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif";
  7554. var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in GeometricContext geometry ) {\n\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif";
  7555. var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float roughness, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat sigma = PI * roughness * roughness / ( 1.0 + roughness );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar + log2( sigma );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -viewDir, normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( roughness, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif";
  7556. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  7557. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n#define Material_LightProbeLOD( material )\t(0)";
  7558. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  7559. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)";
  7560. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.specularRoughness = max( roughnessFactor, 0.0525 );material.specularRoughness += geometryRoughness;\nmaterial.specularRoughness = min( material.specularRoughness, 1.0 );\n#ifdef REFLECTIVITY\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#endif\n#ifdef CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheen;\n#endif";
  7561. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat specularRoughness;\n\tvec3 specularColor;\n#ifdef CLEARCOAT\n\tfloat clearcoat;\n\tfloat clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tvec3 sheenColor;\n#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearcoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNL = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = ccDotNL * directLight.color;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tccIrradiance *= PI;\n\t\t#endif\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t\treflectedLight.directSpecular += ccIrradiance * material.clearcoat * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_Sheen(\n\t\t\tmaterial.specularRoughness,\n\t\t\tdirectLight.direction,\n\t\t\tgeometry,\n\t\t\tmaterial.sheenColor\n\t\t);\n\t#else\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.normal, material.specularColor, material.specularRoughness);\n\t#endif\n\treflectedLight.directDiffuse += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNV = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular += clearcoatRadiance * material.clearcoat * BRDF_Specular_GGX_Environment( geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t\tfloat ccDotNL = ccDotNV;\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\tfloat clearcoatInv = 1.0 - clearcoatDHR;\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tBRDF_Specular_Multiscattering_Environment( geometry, material.specularColor, material.specularRoughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += clearcoatInv * radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}";
  7562. var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif";
  7563. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getLightProbeIndirectIrradiance( geometry, maxMipLevel );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.normal, material.specularRoughness, maxMipLevel );\n\t#ifdef CLEARCOAT\n\t\tclearcoatRadiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness, maxMipLevel );\n\t#endif\n#endif";
  7564. 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";
  7565. 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";
  7566. 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";
  7567. 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";
  7568. 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";
  7569. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  7570. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  7571. 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";
  7572. 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";
  7573. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  7574. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  7575. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n#endif";
  7576. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifndef USE_MORPHNORMALS\n\t\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\t\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif";
  7577. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t#endif\n#endif";
  7578. 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;";
  7579. 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";
  7580. 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";
  7581. var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  7582. 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";
  7583. 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";
  7584. 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}";
  7585. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  7586. 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;";
  7587. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  7588. 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";
  7589. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  7590. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  7591. 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";
  7592. 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";
  7593. 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";
  7594. 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}";
  7595. 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";
  7596. 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";
  7597. 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";
  7598. 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";
  7599. 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";
  7600. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  7601. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  7602. 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; }";
  7603. var transmissionmap_fragment = "#ifdef USE_TRANSMISSIONMAP\n\ttotalTransmission *= texture2D( transmissionMap, vUv ).r;\n#endif";
  7604. var transmissionmap_pars_fragment = "#ifdef USE_TRANSMISSIONMAP\n\tuniform sampler2D transmissionMap;\n#endif";
  7605. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  7606. 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";
  7607. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  7608. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  7609. 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";
  7610. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  7611. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif";
  7612. var background_frag = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7613. var background_vert = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}";
  7614. var cube_frag = "#include <envmap_common_pars_fragment>\nuniform float opacity;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\tvec3 vReflect = vWorldDirection;\n\t#include <envmap_fragment>\n\tgl_FragColor = envColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7615. var cube_vert = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}";
  7616. var depth_frag = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}";
  7617. var depth_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvHighPrecisionZW = gl_Position.zw;\n}";
  7618. var distanceRGBA_frag = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}";
  7619. var distanceRGBA_vert = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}";
  7620. var equirect_frag = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tvec4 texColor = texture2D( tEquirect, sampleUV );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7621. var equirect_vert = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}";
  7622. var linedashed_frag = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  7623. var linedashed_vert = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  7624. var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7625. var meshbasic_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_ENVMAP\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";
  7626. var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack;\n\t#else\n\t\treflectedLight.indirectDiffuse += vIndirectFront;\n\t#endif\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7627. var meshlambert_vert = "#define LAMBERT\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7628. var meshmatcap_frag = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t\tmatcapColor = matcapTexelToLinear( matcapColor );\n\t#else\n\t\tvec4 matcapColor = vec4( 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7629. var meshmatcap_vert = "#define MATCAP\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#ifndef FLAT_SHADED\n\t\tvNormal = normalize( transformedNormal );\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";
  7630. var meshtoon_frag = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7631. var meshtoon_vert = "#define TOON\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7632. var meshphong_frag = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7633. var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7634. var meshphysical_frag = "#define STANDARD\n#ifdef PHYSICAL\n\t#define REFLECTIVITY\n\t#define CLEARCOAT\n\t#define TRANSMISSION\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef TRANSMISSION\n\tuniform float transmission;\n#endif\n#ifdef REFLECTIVITY\n\tuniform float reflectivity;\n#endif\n#ifdef CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheen;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <transmissionmap_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <lights_physical_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#ifdef TRANSMISSION\n\t\tfloat totalTransmission = transmission;\n\t#endif\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <transmissionmap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#ifdef TRANSMISSION\n\t\tdiffuseColor.a *= mix( saturate( 1. - totalTransmission + linearToRelativeLuminance( reflectedLight.directSpecular + reflectedLight.indirectSpecular ) ), 1.0, metalness );\n\t#endif\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7635. var meshphysical_vert = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7636. var normal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}";
  7637. var normal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
  7638. var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  7639. var points_vert = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n}";
  7640. var shadow_frag = "uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  7641. var shadow_vert = "#include <common>\n#include <fog_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7642. var sprite_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  7643. var sprite_vert = "uniform float rotation;\nuniform vec2 center;\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  7644. const ShaderChunk = {
  7645. alphamap_fragment: alphamap_fragment,
  7646. alphamap_pars_fragment: alphamap_pars_fragment,
  7647. alphatest_fragment: alphatest_fragment,
  7648. aomap_fragment: aomap_fragment,
  7649. aomap_pars_fragment: aomap_pars_fragment,
  7650. begin_vertex: begin_vertex,
  7651. beginnormal_vertex: beginnormal_vertex,
  7652. bsdfs: bsdfs,
  7653. bumpmap_pars_fragment: bumpmap_pars_fragment,
  7654. clipping_planes_fragment: clipping_planes_fragment,
  7655. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  7656. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  7657. clipping_planes_vertex: clipping_planes_vertex,
  7658. color_fragment: color_fragment,
  7659. color_pars_fragment: color_pars_fragment,
  7660. color_pars_vertex: color_pars_vertex,
  7661. color_vertex: color_vertex,
  7662. common: common,
  7663. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  7664. defaultnormal_vertex: defaultnormal_vertex,
  7665. displacementmap_pars_vertex: displacementmap_pars_vertex,
  7666. displacementmap_vertex: displacementmap_vertex,
  7667. emissivemap_fragment: emissivemap_fragment,
  7668. emissivemap_pars_fragment: emissivemap_pars_fragment,
  7669. encodings_fragment: encodings_fragment,
  7670. encodings_pars_fragment: encodings_pars_fragment,
  7671. envmap_fragment: envmap_fragment,
  7672. envmap_common_pars_fragment: envmap_common_pars_fragment,
  7673. envmap_pars_fragment: envmap_pars_fragment,
  7674. envmap_pars_vertex: envmap_pars_vertex,
  7675. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  7676. envmap_vertex: envmap_vertex,
  7677. fog_vertex: fog_vertex,
  7678. fog_pars_vertex: fog_pars_vertex,
  7679. fog_fragment: fog_fragment,
  7680. fog_pars_fragment: fog_pars_fragment,
  7681. gradientmap_pars_fragment: gradientmap_pars_fragment,
  7682. lightmap_fragment: lightmap_fragment,
  7683. lightmap_pars_fragment: lightmap_pars_fragment,
  7684. lights_lambert_vertex: lights_lambert_vertex,
  7685. lights_pars_begin: lights_pars_begin,
  7686. lights_toon_fragment: lights_toon_fragment,
  7687. lights_toon_pars_fragment: lights_toon_pars_fragment,
  7688. lights_phong_fragment: lights_phong_fragment,
  7689. lights_phong_pars_fragment: lights_phong_pars_fragment,
  7690. lights_physical_fragment: lights_physical_fragment,
  7691. lights_physical_pars_fragment: lights_physical_pars_fragment,
  7692. lights_fragment_begin: lights_fragment_begin,
  7693. lights_fragment_maps: lights_fragment_maps,
  7694. lights_fragment_end: lights_fragment_end,
  7695. logdepthbuf_fragment: logdepthbuf_fragment,
  7696. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  7697. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  7698. logdepthbuf_vertex: logdepthbuf_vertex,
  7699. map_fragment: map_fragment,
  7700. map_pars_fragment: map_pars_fragment,
  7701. map_particle_fragment: map_particle_fragment,
  7702. map_particle_pars_fragment: map_particle_pars_fragment,
  7703. metalnessmap_fragment: metalnessmap_fragment,
  7704. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  7705. morphnormal_vertex: morphnormal_vertex,
  7706. morphtarget_pars_vertex: morphtarget_pars_vertex,
  7707. morphtarget_vertex: morphtarget_vertex,
  7708. normal_fragment_begin: normal_fragment_begin,
  7709. normal_fragment_maps: normal_fragment_maps,
  7710. normalmap_pars_fragment: normalmap_pars_fragment,
  7711. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  7712. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  7713. clearcoat_pars_fragment: clearcoat_pars_fragment,
  7714. packing: packing,
  7715. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  7716. project_vertex: project_vertex,
  7717. dithering_fragment: dithering_fragment,
  7718. dithering_pars_fragment: dithering_pars_fragment,
  7719. roughnessmap_fragment: roughnessmap_fragment,
  7720. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  7721. shadowmap_pars_fragment: shadowmap_pars_fragment,
  7722. shadowmap_pars_vertex: shadowmap_pars_vertex,
  7723. shadowmap_vertex: shadowmap_vertex,
  7724. shadowmask_pars_fragment: shadowmask_pars_fragment,
  7725. skinbase_vertex: skinbase_vertex,
  7726. skinning_pars_vertex: skinning_pars_vertex,
  7727. skinning_vertex: skinning_vertex,
  7728. skinnormal_vertex: skinnormal_vertex,
  7729. specularmap_fragment: specularmap_fragment,
  7730. specularmap_pars_fragment: specularmap_pars_fragment,
  7731. tonemapping_fragment: tonemapping_fragment,
  7732. tonemapping_pars_fragment: tonemapping_pars_fragment,
  7733. transmissionmap_fragment: transmissionmap_fragment,
  7734. transmissionmap_pars_fragment: transmissionmap_pars_fragment,
  7735. uv_pars_fragment: uv_pars_fragment,
  7736. uv_pars_vertex: uv_pars_vertex,
  7737. uv_vertex: uv_vertex,
  7738. uv2_pars_fragment: uv2_pars_fragment,
  7739. uv2_pars_vertex: uv2_pars_vertex,
  7740. uv2_vertex: uv2_vertex,
  7741. worldpos_vertex: worldpos_vertex,
  7742. background_frag: background_frag,
  7743. background_vert: background_vert,
  7744. cube_frag: cube_frag,
  7745. cube_vert: cube_vert,
  7746. depth_frag: depth_frag,
  7747. depth_vert: depth_vert,
  7748. distanceRGBA_frag: distanceRGBA_frag,
  7749. distanceRGBA_vert: distanceRGBA_vert,
  7750. equirect_frag: equirect_frag,
  7751. equirect_vert: equirect_vert,
  7752. linedashed_frag: linedashed_frag,
  7753. linedashed_vert: linedashed_vert,
  7754. meshbasic_frag: meshbasic_frag,
  7755. meshbasic_vert: meshbasic_vert,
  7756. meshlambert_frag: meshlambert_frag,
  7757. meshlambert_vert: meshlambert_vert,
  7758. meshmatcap_frag: meshmatcap_frag,
  7759. meshmatcap_vert: meshmatcap_vert,
  7760. meshtoon_frag: meshtoon_frag,
  7761. meshtoon_vert: meshtoon_vert,
  7762. meshphong_frag: meshphong_frag,
  7763. meshphong_vert: meshphong_vert,
  7764. meshphysical_frag: meshphysical_frag,
  7765. meshphysical_vert: meshphysical_vert,
  7766. normal_frag: normal_frag,
  7767. normal_vert: normal_vert,
  7768. points_frag: points_frag,
  7769. points_vert: points_vert,
  7770. shadow_frag: shadow_frag,
  7771. shadow_vert: shadow_vert,
  7772. sprite_frag: sprite_frag,
  7773. sprite_vert: sprite_vert
  7774. };
  7775. /**
  7776. * Uniforms library for shared webgl shaders
  7777. */
  7778. const UniformsLib = {
  7779. common: {
  7780. diffuse: { value: new Color( 0xeeeeee ) },
  7781. opacity: { value: 1.0 },
  7782. map: { value: null },
  7783. uvTransform: { value: new Matrix3() },
  7784. uv2Transform: { value: new Matrix3() },
  7785. alphaMap: { value: null },
  7786. },
  7787. specularmap: {
  7788. specularMap: { value: null },
  7789. },
  7790. envmap: {
  7791. envMap: { value: null },
  7792. flipEnvMap: { value: - 1 },
  7793. reflectivity: { value: 1.0 },
  7794. refractionRatio: { value: 0.98 },
  7795. maxMipLevel: { value: 0 }
  7796. },
  7797. aomap: {
  7798. aoMap: { value: null },
  7799. aoMapIntensity: { value: 1 }
  7800. },
  7801. lightmap: {
  7802. lightMap: { value: null },
  7803. lightMapIntensity: { value: 1 }
  7804. },
  7805. emissivemap: {
  7806. emissiveMap: { value: null }
  7807. },
  7808. bumpmap: {
  7809. bumpMap: { value: null },
  7810. bumpScale: { value: 1 }
  7811. },
  7812. normalmap: {
  7813. normalMap: { value: null },
  7814. normalScale: { value: new Vector2( 1, 1 ) }
  7815. },
  7816. displacementmap: {
  7817. displacementMap: { value: null },
  7818. displacementScale: { value: 1 },
  7819. displacementBias: { value: 0 }
  7820. },
  7821. roughnessmap: {
  7822. roughnessMap: { value: null }
  7823. },
  7824. metalnessmap: {
  7825. metalnessMap: { value: null }
  7826. },
  7827. gradientmap: {
  7828. gradientMap: { value: null }
  7829. },
  7830. fog: {
  7831. fogDensity: { value: 0.00025 },
  7832. fogNear: { value: 1 },
  7833. fogFar: { value: 2000 },
  7834. fogColor: { value: new Color( 0xffffff ) }
  7835. },
  7836. lights: {
  7837. ambientLightColor: { value: [] },
  7838. lightProbe: { value: [] },
  7839. directionalLights: { value: [], properties: {
  7840. direction: {},
  7841. color: {}
  7842. } },
  7843. directionalLightShadows: { value: [], properties: {
  7844. shadowBias: {},
  7845. shadowNormalBias: {},
  7846. shadowRadius: {},
  7847. shadowMapSize: {}
  7848. } },
  7849. directionalShadowMap: { value: [] },
  7850. directionalShadowMatrix: { value: [] },
  7851. spotLights: { value: [], properties: {
  7852. color: {},
  7853. position: {},
  7854. direction: {},
  7855. distance: {},
  7856. coneCos: {},
  7857. penumbraCos: {},
  7858. decay: {}
  7859. } },
  7860. spotLightShadows: { value: [], properties: {
  7861. shadowBias: {},
  7862. shadowNormalBias: {},
  7863. shadowRadius: {},
  7864. shadowMapSize: {}
  7865. } },
  7866. spotShadowMap: { value: [] },
  7867. spotShadowMatrix: { value: [] },
  7868. pointLights: { value: [], properties: {
  7869. color: {},
  7870. position: {},
  7871. decay: {},
  7872. distance: {}
  7873. } },
  7874. pointLightShadows: { value: [], properties: {
  7875. shadowBias: {},
  7876. shadowNormalBias: {},
  7877. shadowRadius: {},
  7878. shadowMapSize: {},
  7879. shadowCameraNear: {},
  7880. shadowCameraFar: {}
  7881. } },
  7882. pointShadowMap: { value: [] },
  7883. pointShadowMatrix: { value: [] },
  7884. hemisphereLights: { value: [], properties: {
  7885. direction: {},
  7886. skyColor: {},
  7887. groundColor: {}
  7888. } },
  7889. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  7890. rectAreaLights: { value: [], properties: {
  7891. color: {},
  7892. position: {},
  7893. width: {},
  7894. height: {}
  7895. } },
  7896. ltc_1: { value: null },
  7897. ltc_2: { value: null }
  7898. },
  7899. points: {
  7900. diffuse: { value: new Color( 0xeeeeee ) },
  7901. opacity: { value: 1.0 },
  7902. size: { value: 1.0 },
  7903. scale: { value: 1.0 },
  7904. map: { value: null },
  7905. alphaMap: { value: null },
  7906. uvTransform: { value: new Matrix3() }
  7907. },
  7908. sprite: {
  7909. diffuse: { value: new Color( 0xeeeeee ) },
  7910. opacity: { value: 1.0 },
  7911. center: { value: new Vector2( 0.5, 0.5 ) },
  7912. rotation: { value: 0.0 },
  7913. map: { value: null },
  7914. alphaMap: { value: null },
  7915. uvTransform: { value: new Matrix3() }
  7916. }
  7917. };
  7918. const ShaderLib = {
  7919. basic: {
  7920. uniforms: mergeUniforms( [
  7921. UniformsLib.common,
  7922. UniformsLib.specularmap,
  7923. UniformsLib.envmap,
  7924. UniformsLib.aomap,
  7925. UniformsLib.lightmap,
  7926. UniformsLib.fog
  7927. ] ),
  7928. vertexShader: ShaderChunk.meshbasic_vert,
  7929. fragmentShader: ShaderChunk.meshbasic_frag
  7930. },
  7931. lambert: {
  7932. uniforms: mergeUniforms( [
  7933. UniformsLib.common,
  7934. UniformsLib.specularmap,
  7935. UniformsLib.envmap,
  7936. UniformsLib.aomap,
  7937. UniformsLib.lightmap,
  7938. UniformsLib.emissivemap,
  7939. UniformsLib.fog,
  7940. UniformsLib.lights,
  7941. {
  7942. emissive: { value: new Color( 0x000000 ) }
  7943. }
  7944. ] ),
  7945. vertexShader: ShaderChunk.meshlambert_vert,
  7946. fragmentShader: ShaderChunk.meshlambert_frag
  7947. },
  7948. phong: {
  7949. uniforms: mergeUniforms( [
  7950. UniformsLib.common,
  7951. UniformsLib.specularmap,
  7952. UniformsLib.envmap,
  7953. UniformsLib.aomap,
  7954. UniformsLib.lightmap,
  7955. UniformsLib.emissivemap,
  7956. UniformsLib.bumpmap,
  7957. UniformsLib.normalmap,
  7958. UniformsLib.displacementmap,
  7959. UniformsLib.fog,
  7960. UniformsLib.lights,
  7961. {
  7962. emissive: { value: new Color( 0x000000 ) },
  7963. specular: { value: new Color( 0x111111 ) },
  7964. shininess: { value: 30 }
  7965. }
  7966. ] ),
  7967. vertexShader: ShaderChunk.meshphong_vert,
  7968. fragmentShader: ShaderChunk.meshphong_frag
  7969. },
  7970. standard: {
  7971. uniforms: mergeUniforms( [
  7972. UniformsLib.common,
  7973. UniformsLib.envmap,
  7974. UniformsLib.aomap,
  7975. UniformsLib.lightmap,
  7976. UniformsLib.emissivemap,
  7977. UniformsLib.bumpmap,
  7978. UniformsLib.normalmap,
  7979. UniformsLib.displacementmap,
  7980. UniformsLib.roughnessmap,
  7981. UniformsLib.metalnessmap,
  7982. UniformsLib.fog,
  7983. UniformsLib.lights,
  7984. {
  7985. emissive: { value: new Color( 0x000000 ) },
  7986. roughness: { value: 1.0 },
  7987. metalness: { value: 0.0 },
  7988. envMapIntensity: { value: 1 } // temporary
  7989. }
  7990. ] ),
  7991. vertexShader: ShaderChunk.meshphysical_vert,
  7992. fragmentShader: ShaderChunk.meshphysical_frag
  7993. },
  7994. toon: {
  7995. uniforms: mergeUniforms( [
  7996. UniformsLib.common,
  7997. UniformsLib.aomap,
  7998. UniformsLib.lightmap,
  7999. UniformsLib.emissivemap,
  8000. UniformsLib.bumpmap,
  8001. UniformsLib.normalmap,
  8002. UniformsLib.displacementmap,
  8003. UniformsLib.gradientmap,
  8004. UniformsLib.fog,
  8005. UniformsLib.lights,
  8006. {
  8007. emissive: { value: new Color( 0x000000 ) }
  8008. }
  8009. ] ),
  8010. vertexShader: ShaderChunk.meshtoon_vert,
  8011. fragmentShader: ShaderChunk.meshtoon_frag
  8012. },
  8013. matcap: {
  8014. uniforms: mergeUniforms( [
  8015. UniformsLib.common,
  8016. UniformsLib.bumpmap,
  8017. UniformsLib.normalmap,
  8018. UniformsLib.displacementmap,
  8019. UniformsLib.fog,
  8020. {
  8021. matcap: { value: null }
  8022. }
  8023. ] ),
  8024. vertexShader: ShaderChunk.meshmatcap_vert,
  8025. fragmentShader: ShaderChunk.meshmatcap_frag
  8026. },
  8027. points: {
  8028. uniforms: mergeUniforms( [
  8029. UniformsLib.points,
  8030. UniformsLib.fog
  8031. ] ),
  8032. vertexShader: ShaderChunk.points_vert,
  8033. fragmentShader: ShaderChunk.points_frag
  8034. },
  8035. dashed: {
  8036. uniforms: mergeUniforms( [
  8037. UniformsLib.common,
  8038. UniformsLib.fog,
  8039. {
  8040. scale: { value: 1 },
  8041. dashSize: { value: 1 },
  8042. totalSize: { value: 2 }
  8043. }
  8044. ] ),
  8045. vertexShader: ShaderChunk.linedashed_vert,
  8046. fragmentShader: ShaderChunk.linedashed_frag
  8047. },
  8048. depth: {
  8049. uniforms: mergeUniforms( [
  8050. UniformsLib.common,
  8051. UniformsLib.displacementmap
  8052. ] ),
  8053. vertexShader: ShaderChunk.depth_vert,
  8054. fragmentShader: ShaderChunk.depth_frag
  8055. },
  8056. normal: {
  8057. uniforms: mergeUniforms( [
  8058. UniformsLib.common,
  8059. UniformsLib.bumpmap,
  8060. UniformsLib.normalmap,
  8061. UniformsLib.displacementmap,
  8062. {
  8063. opacity: { value: 1.0 }
  8064. }
  8065. ] ),
  8066. vertexShader: ShaderChunk.normal_vert,
  8067. fragmentShader: ShaderChunk.normal_frag
  8068. },
  8069. sprite: {
  8070. uniforms: mergeUniforms( [
  8071. UniformsLib.sprite,
  8072. UniformsLib.fog
  8073. ] ),
  8074. vertexShader: ShaderChunk.sprite_vert,
  8075. fragmentShader: ShaderChunk.sprite_frag
  8076. },
  8077. background: {
  8078. uniforms: {
  8079. uvTransform: { value: new Matrix3() },
  8080. t2D: { value: null },
  8081. },
  8082. vertexShader: ShaderChunk.background_vert,
  8083. fragmentShader: ShaderChunk.background_frag
  8084. },
  8085. /* -------------------------------------------------------------------------
  8086. // Cube map shader
  8087. ------------------------------------------------------------------------- */
  8088. cube: {
  8089. uniforms: mergeUniforms( [
  8090. UniformsLib.envmap,
  8091. {
  8092. opacity: { value: 1.0 }
  8093. }
  8094. ] ),
  8095. vertexShader: ShaderChunk.cube_vert,
  8096. fragmentShader: ShaderChunk.cube_frag
  8097. },
  8098. equirect: {
  8099. uniforms: {
  8100. tEquirect: { value: null },
  8101. },
  8102. vertexShader: ShaderChunk.equirect_vert,
  8103. fragmentShader: ShaderChunk.equirect_frag
  8104. },
  8105. distanceRGBA: {
  8106. uniforms: mergeUniforms( [
  8107. UniformsLib.common,
  8108. UniformsLib.displacementmap,
  8109. {
  8110. referencePosition: { value: new Vector3() },
  8111. nearDistance: { value: 1 },
  8112. farDistance: { value: 1000 }
  8113. }
  8114. ] ),
  8115. vertexShader: ShaderChunk.distanceRGBA_vert,
  8116. fragmentShader: ShaderChunk.distanceRGBA_frag
  8117. },
  8118. shadow: {
  8119. uniforms: mergeUniforms( [
  8120. UniformsLib.lights,
  8121. UniformsLib.fog,
  8122. {
  8123. color: { value: new Color( 0x00000 ) },
  8124. opacity: { value: 1.0 }
  8125. },
  8126. ] ),
  8127. vertexShader: ShaderChunk.shadow_vert,
  8128. fragmentShader: ShaderChunk.shadow_frag
  8129. }
  8130. };
  8131. ShaderLib.physical = {
  8132. uniforms: mergeUniforms( [
  8133. ShaderLib.standard.uniforms,
  8134. {
  8135. clearcoat: { value: 0 },
  8136. clearcoatMap: { value: null },
  8137. clearcoatRoughness: { value: 0 },
  8138. clearcoatRoughnessMap: { value: null },
  8139. clearcoatNormalScale: { value: new Vector2( 1, 1 ) },
  8140. clearcoatNormalMap: { value: null },
  8141. sheen: { value: new Color( 0x000000 ) },
  8142. transmission: { value: 0 },
  8143. transmissionMap: { value: null },
  8144. }
  8145. ] ),
  8146. vertexShader: ShaderChunk.meshphysical_vert,
  8147. fragmentShader: ShaderChunk.meshphysical_frag
  8148. };
  8149. function WebGLBackground( renderer, cubemaps, state, objects, premultipliedAlpha ) {
  8150. const clearColor = new Color( 0x000000 );
  8151. let clearAlpha = 0;
  8152. let planeMesh;
  8153. let boxMesh;
  8154. let currentBackground = null;
  8155. let currentBackgroundVersion = 0;
  8156. let currentTonemapping = null;
  8157. function render( renderList, scene, camera, forceClear ) {
  8158. let background = scene.isScene === true ? scene.background : null;
  8159. if ( background && background.isTexture ) {
  8160. background = cubemaps.get( background );
  8161. }
  8162. // Ignore background in AR
  8163. // TODO: Reconsider this.
  8164. const xr = renderer.xr;
  8165. const session = xr.getSession && xr.getSession();
  8166. if ( session && session.environmentBlendMode === 'additive' ) {
  8167. background = null;
  8168. }
  8169. if ( background === null ) {
  8170. setClear( clearColor, clearAlpha );
  8171. } else if ( background && background.isColor ) {
  8172. setClear( background, 1 );
  8173. forceClear = true;
  8174. }
  8175. if ( renderer.autoClear || forceClear ) {
  8176. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  8177. }
  8178. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  8179. if ( boxMesh === undefined ) {
  8180. boxMesh = new Mesh(
  8181. new BoxGeometry( 1, 1, 1 ),
  8182. new ShaderMaterial( {
  8183. name: 'BackgroundCubeMaterial',
  8184. uniforms: cloneUniforms( ShaderLib.cube.uniforms ),
  8185. vertexShader: ShaderLib.cube.vertexShader,
  8186. fragmentShader: ShaderLib.cube.fragmentShader,
  8187. side: BackSide,
  8188. depthTest: false,
  8189. depthWrite: false,
  8190. fog: false
  8191. } )
  8192. );
  8193. boxMesh.geometry.deleteAttribute( 'normal' );
  8194. boxMesh.geometry.deleteAttribute( 'uv' );
  8195. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  8196. this.matrixWorld.copyPosition( camera.matrixWorld );
  8197. };
  8198. // enable code injection for non-built-in material
  8199. Object.defineProperty( boxMesh.material, 'envMap', {
  8200. get: function () {
  8201. return this.uniforms.envMap.value;
  8202. }
  8203. } );
  8204. objects.update( boxMesh );
  8205. }
  8206. boxMesh.material.uniforms.envMap.value = background;
  8207. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background._needsFlipEnvMap ) ? - 1 : 1;
  8208. if ( currentBackground !== background ||
  8209. currentBackgroundVersion !== background.version ||
  8210. currentTonemapping !== renderer.toneMapping ) {
  8211. boxMesh.material.needsUpdate = true;
  8212. currentBackground = background;
  8213. currentBackgroundVersion = background.version;
  8214. currentTonemapping = renderer.toneMapping;
  8215. }
  8216. // push to the pre-sorted opaque render list
  8217. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  8218. } else if ( background && background.isTexture ) {
  8219. if ( planeMesh === undefined ) {
  8220. planeMesh = new Mesh(
  8221. new PlaneGeometry( 2, 2 ),
  8222. new ShaderMaterial( {
  8223. name: 'BackgroundMaterial',
  8224. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  8225. vertexShader: ShaderLib.background.vertexShader,
  8226. fragmentShader: ShaderLib.background.fragmentShader,
  8227. side: FrontSide,
  8228. depthTest: false,
  8229. depthWrite: false,
  8230. fog: false
  8231. } )
  8232. );
  8233. planeMesh.geometry.deleteAttribute( 'normal' );
  8234. // enable code injection for non-built-in material
  8235. Object.defineProperty( planeMesh.material, 'map', {
  8236. get: function () {
  8237. return this.uniforms.t2D.value;
  8238. }
  8239. } );
  8240. objects.update( planeMesh );
  8241. }
  8242. planeMesh.material.uniforms.t2D.value = background;
  8243. if ( background.matrixAutoUpdate === true ) {
  8244. background.updateMatrix();
  8245. }
  8246. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  8247. if ( currentBackground !== background ||
  8248. currentBackgroundVersion !== background.version ||
  8249. currentTonemapping !== renderer.toneMapping ) {
  8250. planeMesh.material.needsUpdate = true;
  8251. currentBackground = background;
  8252. currentBackgroundVersion = background.version;
  8253. currentTonemapping = renderer.toneMapping;
  8254. }
  8255. // push to the pre-sorted opaque render list
  8256. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  8257. }
  8258. }
  8259. function setClear( color, alpha ) {
  8260. state.buffers.color.setClear( color.r, color.g, color.b, alpha, premultipliedAlpha );
  8261. }
  8262. return {
  8263. getClearColor: function () {
  8264. return clearColor;
  8265. },
  8266. setClearColor: function ( color, alpha = 1 ) {
  8267. clearColor.set( color );
  8268. clearAlpha = alpha;
  8269. setClear( clearColor, clearAlpha );
  8270. },
  8271. getClearAlpha: function () {
  8272. return clearAlpha;
  8273. },
  8274. setClearAlpha: function ( alpha ) {
  8275. clearAlpha = alpha;
  8276. setClear( clearColor, clearAlpha );
  8277. },
  8278. render: render
  8279. };
  8280. }
  8281. function WebGLBindingStates( gl, extensions, attributes, capabilities ) {
  8282. const maxVertexAttributes = gl.getParameter( 34921 );
  8283. const extension = capabilities.isWebGL2 ? null : extensions.get( 'OES_vertex_array_object' );
  8284. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8285. const bindingStates = {};
  8286. const defaultState = createBindingState( null );
  8287. let currentState = defaultState;
  8288. function setup( object, material, program, geometry, index ) {
  8289. let updateBuffers = false;
  8290. if ( vaoAvailable ) {
  8291. const state = getBindingState( geometry, program, material );
  8292. if ( currentState !== state ) {
  8293. currentState = state;
  8294. bindVertexArrayObject( currentState.object );
  8295. }
  8296. updateBuffers = needsUpdate( geometry, index );
  8297. if ( updateBuffers ) saveCache( geometry, index );
  8298. } else {
  8299. const wireframe = ( material.wireframe === true );
  8300. if ( currentState.geometry !== geometry.id ||
  8301. currentState.program !== program.id ||
  8302. currentState.wireframe !== wireframe ) {
  8303. currentState.geometry = geometry.id;
  8304. currentState.program = program.id;
  8305. currentState.wireframe = wireframe;
  8306. updateBuffers = true;
  8307. }
  8308. }
  8309. if ( object.isInstancedMesh === true ) {
  8310. updateBuffers = true;
  8311. }
  8312. if ( index !== null ) {
  8313. attributes.update( index, 34963 );
  8314. }
  8315. if ( updateBuffers ) {
  8316. setupVertexAttributes( object, material, program, geometry );
  8317. if ( index !== null ) {
  8318. gl.bindBuffer( 34963, attributes.get( index ).buffer );
  8319. }
  8320. }
  8321. }
  8322. function createVertexArrayObject() {
  8323. if ( capabilities.isWebGL2 ) return gl.createVertexArray();
  8324. return extension.createVertexArrayOES();
  8325. }
  8326. function bindVertexArrayObject( vao ) {
  8327. if ( capabilities.isWebGL2 ) return gl.bindVertexArray( vao );
  8328. return extension.bindVertexArrayOES( vao );
  8329. }
  8330. function deleteVertexArrayObject( vao ) {
  8331. if ( capabilities.isWebGL2 ) return gl.deleteVertexArray( vao );
  8332. return extension.deleteVertexArrayOES( vao );
  8333. }
  8334. function getBindingState( geometry, program, material ) {
  8335. const wireframe = ( material.wireframe === true );
  8336. let programMap = bindingStates[ geometry.id ];
  8337. if ( programMap === undefined ) {
  8338. programMap = {};
  8339. bindingStates[ geometry.id ] = programMap;
  8340. }
  8341. let stateMap = programMap[ program.id ];
  8342. if ( stateMap === undefined ) {
  8343. stateMap = {};
  8344. programMap[ program.id ] = stateMap;
  8345. }
  8346. let state = stateMap[ wireframe ];
  8347. if ( state === undefined ) {
  8348. state = createBindingState( createVertexArrayObject() );
  8349. stateMap[ wireframe ] = state;
  8350. }
  8351. return state;
  8352. }
  8353. function createBindingState( vao ) {
  8354. const newAttributes = [];
  8355. const enabledAttributes = [];
  8356. const attributeDivisors = [];
  8357. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  8358. newAttributes[ i ] = 0;
  8359. enabledAttributes[ i ] = 0;
  8360. attributeDivisors[ i ] = 0;
  8361. }
  8362. return {
  8363. // for backward compatibility on non-VAO support browser
  8364. geometry: null,
  8365. program: null,
  8366. wireframe: false,
  8367. newAttributes: newAttributes,
  8368. enabledAttributes: enabledAttributes,
  8369. attributeDivisors: attributeDivisors,
  8370. object: vao,
  8371. attributes: {},
  8372. index: null
  8373. };
  8374. }
  8375. function needsUpdate( geometry, index ) {
  8376. const cachedAttributes = currentState.attributes;
  8377. const geometryAttributes = geometry.attributes;
  8378. let attributesNum = 0;
  8379. for ( const key in geometryAttributes ) {
  8380. const cachedAttribute = cachedAttributes[ key ];
  8381. const geometryAttribute = geometryAttributes[ key ];
  8382. if ( cachedAttribute === undefined ) return true;
  8383. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  8384. if ( cachedAttribute.data !== geometryAttribute.data ) return true;
  8385. attributesNum ++;
  8386. }
  8387. if ( currentState.attributesNum !== attributesNum ) return true;
  8388. if ( currentState.index !== index ) return true;
  8389. return false;
  8390. }
  8391. function saveCache( geometry, index ) {
  8392. const cache = {};
  8393. const attributes = geometry.attributes;
  8394. let attributesNum = 0;
  8395. for ( const key in attributes ) {
  8396. const attribute = attributes[ key ];
  8397. const data = {};
  8398. data.attribute = attribute;
  8399. if ( attribute.data ) {
  8400. data.data = attribute.data;
  8401. }
  8402. cache[ key ] = data;
  8403. attributesNum ++;
  8404. }
  8405. currentState.attributes = cache;
  8406. currentState.attributesNum = attributesNum;
  8407. currentState.index = index;
  8408. }
  8409. function initAttributes() {
  8410. const newAttributes = currentState.newAttributes;
  8411. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  8412. newAttributes[ i ] = 0;
  8413. }
  8414. }
  8415. function enableAttribute( attribute ) {
  8416. enableAttributeAndDivisor( attribute, 0 );
  8417. }
  8418. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  8419. const newAttributes = currentState.newAttributes;
  8420. const enabledAttributes = currentState.enabledAttributes;
  8421. const attributeDivisors = currentState.attributeDivisors;
  8422. newAttributes[ attribute ] = 1;
  8423. if ( enabledAttributes[ attribute ] === 0 ) {
  8424. gl.enableVertexAttribArray( attribute );
  8425. enabledAttributes[ attribute ] = 1;
  8426. }
  8427. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  8428. const extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );
  8429. extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
  8430. attributeDivisors[ attribute ] = meshPerAttribute;
  8431. }
  8432. }
  8433. function disableUnusedAttributes() {
  8434. const newAttributes = currentState.newAttributes;
  8435. const enabledAttributes = currentState.enabledAttributes;
  8436. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  8437. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  8438. gl.disableVertexAttribArray( i );
  8439. enabledAttributes[ i ] = 0;
  8440. }
  8441. }
  8442. }
  8443. function vertexAttribPointer( index, size, type, normalized, stride, offset ) {
  8444. if ( capabilities.isWebGL2 === true && ( type === 5124 || type === 5125 ) ) {
  8445. gl.vertexAttribIPointer( index, size, type, stride, offset );
  8446. } else {
  8447. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  8448. }
  8449. }
  8450. function setupVertexAttributes( object, material, program, geometry ) {
  8451. if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {
  8452. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return;
  8453. }
  8454. initAttributes();
  8455. const geometryAttributes = geometry.attributes;
  8456. const programAttributes = program.getAttributes();
  8457. const materialDefaultAttributeValues = material.defaultAttributeValues;
  8458. for ( const name in programAttributes ) {
  8459. const programAttribute = programAttributes[ name ];
  8460. if ( programAttribute >= 0 ) {
  8461. const geometryAttribute = geometryAttributes[ name ];
  8462. if ( geometryAttribute !== undefined ) {
  8463. const normalized = geometryAttribute.normalized;
  8464. const size = geometryAttribute.itemSize;
  8465. const attribute = attributes.get( geometryAttribute );
  8466. // TODO Attribute may not be available on context restore
  8467. if ( attribute === undefined ) continue;
  8468. const buffer = attribute.buffer;
  8469. const type = attribute.type;
  8470. const bytesPerElement = attribute.bytesPerElement;
  8471. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  8472. const data = geometryAttribute.data;
  8473. const stride = data.stride;
  8474. const offset = geometryAttribute.offset;
  8475. if ( data && data.isInstancedInterleavedBuffer ) {
  8476. enableAttributeAndDivisor( programAttribute, data.meshPerAttribute );
  8477. if ( geometry._maxInstanceCount === undefined ) {
  8478. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  8479. }
  8480. } else {
  8481. enableAttribute( programAttribute );
  8482. }
  8483. gl.bindBuffer( 34962, buffer );
  8484. vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement );
  8485. } else {
  8486. if ( geometryAttribute.isInstancedBufferAttribute ) {
  8487. enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute );
  8488. if ( geometry._maxInstanceCount === undefined ) {
  8489. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  8490. }
  8491. } else {
  8492. enableAttribute( programAttribute );
  8493. }
  8494. gl.bindBuffer( 34962, buffer );
  8495. vertexAttribPointer( programAttribute, size, type, normalized, 0, 0 );
  8496. }
  8497. } else if ( name === 'instanceMatrix' ) {
  8498. const attribute = attributes.get( object.instanceMatrix );
  8499. // TODO Attribute may not be available on context restore
  8500. if ( attribute === undefined ) continue;
  8501. const buffer = attribute.buffer;
  8502. const type = attribute.type;
  8503. enableAttributeAndDivisor( programAttribute + 0, 1 );
  8504. enableAttributeAndDivisor( programAttribute + 1, 1 );
  8505. enableAttributeAndDivisor( programAttribute + 2, 1 );
  8506. enableAttributeAndDivisor( programAttribute + 3, 1 );
  8507. gl.bindBuffer( 34962, buffer );
  8508. gl.vertexAttribPointer( programAttribute + 0, 4, type, false, 64, 0 );
  8509. gl.vertexAttribPointer( programAttribute + 1, 4, type, false, 64, 16 );
  8510. gl.vertexAttribPointer( programAttribute + 2, 4, type, false, 64, 32 );
  8511. gl.vertexAttribPointer( programAttribute + 3, 4, type, false, 64, 48 );
  8512. } else if ( name === 'instanceColor' ) {
  8513. const attribute = attributes.get( object.instanceColor );
  8514. // TODO Attribute may not be available on context restore
  8515. if ( attribute === undefined ) continue;
  8516. const buffer = attribute.buffer;
  8517. const type = attribute.type;
  8518. enableAttributeAndDivisor( programAttribute, 1 );
  8519. gl.bindBuffer( 34962, buffer );
  8520. gl.vertexAttribPointer( programAttribute, 3, type, false, 12, 0 );
  8521. } else if ( materialDefaultAttributeValues !== undefined ) {
  8522. const value = materialDefaultAttributeValues[ name ];
  8523. if ( value !== undefined ) {
  8524. switch ( value.length ) {
  8525. case 2:
  8526. gl.vertexAttrib2fv( programAttribute, value );
  8527. break;
  8528. case 3:
  8529. gl.vertexAttrib3fv( programAttribute, value );
  8530. break;
  8531. case 4:
  8532. gl.vertexAttrib4fv( programAttribute, value );
  8533. break;
  8534. default:
  8535. gl.vertexAttrib1fv( programAttribute, value );
  8536. }
  8537. }
  8538. }
  8539. }
  8540. }
  8541. disableUnusedAttributes();
  8542. }
  8543. function dispose() {
  8544. reset();
  8545. for ( const geometryId in bindingStates ) {
  8546. const programMap = bindingStates[ geometryId ];
  8547. for ( const programId in programMap ) {
  8548. const stateMap = programMap[ programId ];
  8549. for ( const wireframe in stateMap ) {
  8550. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8551. delete stateMap[ wireframe ];
  8552. }
  8553. delete programMap[ programId ];
  8554. }
  8555. delete bindingStates[ geometryId ];
  8556. }
  8557. }
  8558. function releaseStatesOfGeometry( geometry ) {
  8559. if ( bindingStates[ geometry.id ] === undefined ) return;
  8560. const programMap = bindingStates[ geometry.id ];
  8561. for ( const programId in programMap ) {
  8562. const stateMap = programMap[ programId ];
  8563. for ( const wireframe in stateMap ) {
  8564. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8565. delete stateMap[ wireframe ];
  8566. }
  8567. delete programMap[ programId ];
  8568. }
  8569. delete bindingStates[ geometry.id ];
  8570. }
  8571. function releaseStatesOfProgram( program ) {
  8572. for ( const geometryId in bindingStates ) {
  8573. const programMap = bindingStates[ geometryId ];
  8574. if ( programMap[ program.id ] === undefined ) continue;
  8575. const stateMap = programMap[ program.id ];
  8576. for ( const wireframe in stateMap ) {
  8577. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8578. delete stateMap[ wireframe ];
  8579. }
  8580. delete programMap[ program.id ];
  8581. }
  8582. }
  8583. function reset() {
  8584. resetDefaultState();
  8585. if ( currentState === defaultState ) return;
  8586. currentState = defaultState;
  8587. bindVertexArrayObject( currentState.object );
  8588. }
  8589. // for backward-compatilibity
  8590. function resetDefaultState() {
  8591. defaultState.geometry = null;
  8592. defaultState.program = null;
  8593. defaultState.wireframe = false;
  8594. }
  8595. return {
  8596. setup: setup,
  8597. reset: reset,
  8598. resetDefaultState: resetDefaultState,
  8599. dispose: dispose,
  8600. releaseStatesOfGeometry: releaseStatesOfGeometry,
  8601. releaseStatesOfProgram: releaseStatesOfProgram,
  8602. initAttributes: initAttributes,
  8603. enableAttribute: enableAttribute,
  8604. disableUnusedAttributes: disableUnusedAttributes
  8605. };
  8606. }
  8607. function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
  8608. const isWebGL2 = capabilities.isWebGL2;
  8609. let mode;
  8610. function setMode( value ) {
  8611. mode = value;
  8612. }
  8613. function render( start, count ) {
  8614. gl.drawArrays( mode, start, count );
  8615. info.update( count, mode, 1 );
  8616. }
  8617. function renderInstances( start, count, primcount ) {
  8618. if ( primcount === 0 ) return;
  8619. let extension, methodName;
  8620. if ( isWebGL2 ) {
  8621. extension = gl;
  8622. methodName = 'drawArraysInstanced';
  8623. } else {
  8624. extension = extensions.get( 'ANGLE_instanced_arrays' );
  8625. methodName = 'drawArraysInstancedANGLE';
  8626. if ( extension === null ) {
  8627. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  8628. return;
  8629. }
  8630. }
  8631. extension[ methodName ]( mode, start, count, primcount );
  8632. info.update( count, mode, primcount );
  8633. }
  8634. //
  8635. this.setMode = setMode;
  8636. this.render = render;
  8637. this.renderInstances = renderInstances;
  8638. }
  8639. function WebGLCapabilities( gl, extensions, parameters ) {
  8640. let maxAnisotropy;
  8641. function getMaxAnisotropy() {
  8642. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  8643. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  8644. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  8645. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  8646. } else {
  8647. maxAnisotropy = 0;
  8648. }
  8649. return maxAnisotropy;
  8650. }
  8651. function getMaxPrecision( precision ) {
  8652. if ( precision === 'highp' ) {
  8653. if ( gl.getShaderPrecisionFormat( 35633, 36338 ).precision > 0 &&
  8654. gl.getShaderPrecisionFormat( 35632, 36338 ).precision > 0 ) {
  8655. return 'highp';
  8656. }
  8657. precision = 'mediump';
  8658. }
  8659. if ( precision === 'mediump' ) {
  8660. if ( gl.getShaderPrecisionFormat( 35633, 36337 ).precision > 0 &&
  8661. gl.getShaderPrecisionFormat( 35632, 36337 ).precision > 0 ) {
  8662. return 'mediump';
  8663. }
  8664. }
  8665. return 'lowp';
  8666. }
  8667. /* eslint-disable no-undef */
  8668. const isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext ) ||
  8669. ( typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext );
  8670. /* eslint-enable no-undef */
  8671. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  8672. const maxPrecision = getMaxPrecision( precision );
  8673. if ( maxPrecision !== precision ) {
  8674. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  8675. precision = maxPrecision;
  8676. }
  8677. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  8678. const maxTextures = gl.getParameter( 34930 );
  8679. const maxVertexTextures = gl.getParameter( 35660 );
  8680. const maxTextureSize = gl.getParameter( 3379 );
  8681. const maxCubemapSize = gl.getParameter( 34076 );
  8682. const maxAttributes = gl.getParameter( 34921 );
  8683. const maxVertexUniforms = gl.getParameter( 36347 );
  8684. const maxVaryings = gl.getParameter( 36348 );
  8685. const maxFragmentUniforms = gl.getParameter( 36349 );
  8686. const vertexTextures = maxVertexTextures > 0;
  8687. const floatFragmentTextures = isWebGL2 || extensions.has( 'OES_texture_float' );
  8688. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  8689. const maxSamples = isWebGL2 ? gl.getParameter( 36183 ) : 0;
  8690. return {
  8691. isWebGL2: isWebGL2,
  8692. getMaxAnisotropy: getMaxAnisotropy,
  8693. getMaxPrecision: getMaxPrecision,
  8694. precision: precision,
  8695. logarithmicDepthBuffer: logarithmicDepthBuffer,
  8696. maxTextures: maxTextures,
  8697. maxVertexTextures: maxVertexTextures,
  8698. maxTextureSize: maxTextureSize,
  8699. maxCubemapSize: maxCubemapSize,
  8700. maxAttributes: maxAttributes,
  8701. maxVertexUniforms: maxVertexUniforms,
  8702. maxVaryings: maxVaryings,
  8703. maxFragmentUniforms: maxFragmentUniforms,
  8704. vertexTextures: vertexTextures,
  8705. floatFragmentTextures: floatFragmentTextures,
  8706. floatVertexTextures: floatVertexTextures,
  8707. maxSamples: maxSamples
  8708. };
  8709. }
  8710. function WebGLClipping( properties ) {
  8711. const scope = this;
  8712. let globalState = null,
  8713. numGlobalPlanes = 0,
  8714. localClippingEnabled = false,
  8715. renderingShadows = false;
  8716. const plane = new Plane(),
  8717. viewNormalMatrix = new Matrix3(),
  8718. uniform = { value: null, needsUpdate: false };
  8719. this.uniform = uniform;
  8720. this.numPlanes = 0;
  8721. this.numIntersection = 0;
  8722. this.init = function ( planes, enableLocalClipping, camera ) {
  8723. const enabled =
  8724. planes.length !== 0 ||
  8725. enableLocalClipping ||
  8726. // enable state of previous frame - the clipping code has to
  8727. // run another frame in order to reset the state:
  8728. numGlobalPlanes !== 0 ||
  8729. localClippingEnabled;
  8730. localClippingEnabled = enableLocalClipping;
  8731. globalState = projectPlanes( planes, camera, 0 );
  8732. numGlobalPlanes = planes.length;
  8733. return enabled;
  8734. };
  8735. this.beginShadows = function () {
  8736. renderingShadows = true;
  8737. projectPlanes( null );
  8738. };
  8739. this.endShadows = function () {
  8740. renderingShadows = false;
  8741. resetGlobalState();
  8742. };
  8743. this.setState = function ( material, camera, useCache ) {
  8744. const planes = material.clippingPlanes,
  8745. clipIntersection = material.clipIntersection,
  8746. clipShadows = material.clipShadows;
  8747. const materialProperties = properties.get( material );
  8748. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  8749. // there's no local clipping
  8750. if ( renderingShadows ) {
  8751. // there's no global clipping
  8752. projectPlanes( null );
  8753. } else {
  8754. resetGlobalState();
  8755. }
  8756. } else {
  8757. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  8758. lGlobal = nGlobal * 4;
  8759. let dstArray = materialProperties.clippingState || null;
  8760. uniform.value = dstArray; // ensure unique state
  8761. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  8762. for ( let i = 0; i !== lGlobal; ++ i ) {
  8763. dstArray[ i ] = globalState[ i ];
  8764. }
  8765. materialProperties.clippingState = dstArray;
  8766. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  8767. this.numPlanes += nGlobal;
  8768. }
  8769. };
  8770. function resetGlobalState() {
  8771. if ( uniform.value !== globalState ) {
  8772. uniform.value = globalState;
  8773. uniform.needsUpdate = numGlobalPlanes > 0;
  8774. }
  8775. scope.numPlanes = numGlobalPlanes;
  8776. scope.numIntersection = 0;
  8777. }
  8778. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  8779. const nPlanes = planes !== null ? planes.length : 0;
  8780. let dstArray = null;
  8781. if ( nPlanes !== 0 ) {
  8782. dstArray = uniform.value;
  8783. if ( skipTransform !== true || dstArray === null ) {
  8784. const flatSize = dstOffset + nPlanes * 4,
  8785. viewMatrix = camera.matrixWorldInverse;
  8786. viewNormalMatrix.getNormalMatrix( viewMatrix );
  8787. if ( dstArray === null || dstArray.length < flatSize ) {
  8788. dstArray = new Float32Array( flatSize );
  8789. }
  8790. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  8791. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  8792. plane.normal.toArray( dstArray, i4 );
  8793. dstArray[ i4 + 3 ] = plane.constant;
  8794. }
  8795. }
  8796. uniform.value = dstArray;
  8797. uniform.needsUpdate = true;
  8798. }
  8799. scope.numPlanes = nPlanes;
  8800. scope.numIntersection = 0;
  8801. return dstArray;
  8802. }
  8803. }
  8804. function WebGLCubeMaps( renderer ) {
  8805. let cubemaps = new WeakMap();
  8806. function mapTextureMapping( texture, mapping ) {
  8807. if ( mapping === EquirectangularReflectionMapping ) {
  8808. texture.mapping = CubeReflectionMapping;
  8809. } else if ( mapping === EquirectangularRefractionMapping ) {
  8810. texture.mapping = CubeRefractionMapping;
  8811. }
  8812. return texture;
  8813. }
  8814. function get( texture ) {
  8815. if ( texture && texture.isTexture ) {
  8816. const mapping = texture.mapping;
  8817. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  8818. if ( cubemaps.has( texture ) ) {
  8819. const cubemap = cubemaps.get( texture ).texture;
  8820. return mapTextureMapping( cubemap, texture.mapping );
  8821. } else {
  8822. const image = texture.image;
  8823. if ( image && image.height > 0 ) {
  8824. const currentRenderTarget = renderer.getRenderTarget();
  8825. const renderTarget = new WebGLCubeRenderTarget( image.height / 2 );
  8826. renderTarget.fromEquirectangularTexture( renderer, texture );
  8827. cubemaps.set( texture, renderTarget );
  8828. renderer.setRenderTarget( currentRenderTarget );
  8829. texture.addEventListener( 'dispose', onTextureDispose );
  8830. return mapTextureMapping( renderTarget.texture, texture.mapping );
  8831. } else {
  8832. // image not yet ready. try the conversion next frame
  8833. return null;
  8834. }
  8835. }
  8836. }
  8837. }
  8838. return texture;
  8839. }
  8840. function onTextureDispose( event ) {
  8841. const texture = event.target;
  8842. texture.removeEventListener( 'dispose', onTextureDispose );
  8843. const cubemap = cubemaps.get( texture );
  8844. if ( cubemap !== undefined ) {
  8845. cubemaps.delete( texture );
  8846. cubemap.dispose();
  8847. }
  8848. }
  8849. function dispose() {
  8850. cubemaps = new WeakMap();
  8851. }
  8852. return {
  8853. get: get,
  8854. dispose: dispose
  8855. };
  8856. }
  8857. function WebGLExtensions( gl ) {
  8858. const extensions = {};
  8859. function getExtension( name ) {
  8860. if ( extensions[ name ] !== undefined ) {
  8861. return extensions[ name ];
  8862. }
  8863. let extension;
  8864. switch ( name ) {
  8865. case 'WEBGL_depth_texture':
  8866. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  8867. break;
  8868. case 'EXT_texture_filter_anisotropic':
  8869. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  8870. break;
  8871. case 'WEBGL_compressed_texture_s3tc':
  8872. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  8873. break;
  8874. case 'WEBGL_compressed_texture_pvrtc':
  8875. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  8876. break;
  8877. default:
  8878. extension = gl.getExtension( name );
  8879. }
  8880. extensions[ name ] = extension;
  8881. return extension;
  8882. }
  8883. return {
  8884. has: function ( name ) {
  8885. return getExtension( name ) !== null;
  8886. },
  8887. init: function ( capabilities ) {
  8888. if ( capabilities.isWebGL2 ) {
  8889. getExtension( 'EXT_color_buffer_float' );
  8890. } else {
  8891. getExtension( 'WEBGL_depth_texture' );
  8892. getExtension( 'OES_texture_float' );
  8893. getExtension( 'OES_texture_half_float' );
  8894. getExtension( 'OES_texture_half_float_linear' );
  8895. getExtension( 'OES_standard_derivatives' );
  8896. getExtension( 'OES_element_index_uint' );
  8897. getExtension( 'OES_vertex_array_object' );
  8898. getExtension( 'ANGLE_instanced_arrays' );
  8899. }
  8900. getExtension( 'OES_texture_float_linear' );
  8901. getExtension( 'EXT_color_buffer_half_float' );
  8902. },
  8903. get: function ( name ) {
  8904. const extension = getExtension( name );
  8905. if ( extension === null ) {
  8906. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  8907. }
  8908. return extension;
  8909. }
  8910. };
  8911. }
  8912. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  8913. const geometries = {};
  8914. const wireframeAttributes = new WeakMap();
  8915. function onGeometryDispose( event ) {
  8916. const geometry = event.target;
  8917. if ( geometry.index !== null ) {
  8918. attributes.remove( geometry.index );
  8919. }
  8920. for ( const name in geometry.attributes ) {
  8921. attributes.remove( geometry.attributes[ name ] );
  8922. }
  8923. geometry.removeEventListener( 'dispose', onGeometryDispose );
  8924. delete geometries[ geometry.id ];
  8925. const attribute = wireframeAttributes.get( geometry );
  8926. if ( attribute ) {
  8927. attributes.remove( attribute );
  8928. wireframeAttributes.delete( geometry );
  8929. }
  8930. bindingStates.releaseStatesOfGeometry( geometry );
  8931. if ( geometry.isInstancedBufferGeometry === true ) {
  8932. delete geometry._maxInstanceCount;
  8933. }
  8934. //
  8935. info.memory.geometries --;
  8936. }
  8937. function get( object, geometry ) {
  8938. if ( geometries[ geometry.id ] === true ) return geometry;
  8939. geometry.addEventListener( 'dispose', onGeometryDispose );
  8940. geometries[ geometry.id ] = true;
  8941. info.memory.geometries ++;
  8942. return geometry;
  8943. }
  8944. function update( geometry ) {
  8945. const geometryAttributes = geometry.attributes;
  8946. // Updating index buffer in VAO now. See WebGLBindingStates.
  8947. for ( const name in geometryAttributes ) {
  8948. attributes.update( geometryAttributes[ name ], 34962 );
  8949. }
  8950. // morph targets
  8951. const morphAttributes = geometry.morphAttributes;
  8952. for ( const name in morphAttributes ) {
  8953. const array = morphAttributes[ name ];
  8954. for ( let i = 0, l = array.length; i < l; i ++ ) {
  8955. attributes.update( array[ i ], 34962 );
  8956. }
  8957. }
  8958. }
  8959. function updateWireframeAttribute( geometry ) {
  8960. const indices = [];
  8961. const geometryIndex = geometry.index;
  8962. const geometryPosition = geometry.attributes.position;
  8963. let version = 0;
  8964. if ( geometryIndex !== null ) {
  8965. const array = geometryIndex.array;
  8966. version = geometryIndex.version;
  8967. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  8968. const a = array[ i + 0 ];
  8969. const b = array[ i + 1 ];
  8970. const c = array[ i + 2 ];
  8971. indices.push( a, b, b, c, c, a );
  8972. }
  8973. } else {
  8974. const array = geometryPosition.array;
  8975. version = geometryPosition.version;
  8976. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  8977. const a = i + 0;
  8978. const b = i + 1;
  8979. const c = i + 2;
  8980. indices.push( a, b, b, c, c, a );
  8981. }
  8982. }
  8983. const attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  8984. attribute.version = version;
  8985. // Updating index buffer in VAO now. See WebGLBindingStates
  8986. //
  8987. const previousAttribute = wireframeAttributes.get( geometry );
  8988. if ( previousAttribute ) attributes.remove( previousAttribute );
  8989. //
  8990. wireframeAttributes.set( geometry, attribute );
  8991. }
  8992. function getWireframeAttribute( geometry ) {
  8993. const currentAttribute = wireframeAttributes.get( geometry );
  8994. if ( currentAttribute ) {
  8995. const geometryIndex = geometry.index;
  8996. if ( geometryIndex !== null ) {
  8997. // if the attribute is obsolete, create a new one
  8998. if ( currentAttribute.version < geometryIndex.version ) {
  8999. updateWireframeAttribute( geometry );
  9000. }
  9001. }
  9002. } else {
  9003. updateWireframeAttribute( geometry );
  9004. }
  9005. return wireframeAttributes.get( geometry );
  9006. }
  9007. return {
  9008. get: get,
  9009. update: update,
  9010. getWireframeAttribute: getWireframeAttribute
  9011. };
  9012. }
  9013. function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {
  9014. const isWebGL2 = capabilities.isWebGL2;
  9015. let mode;
  9016. function setMode( value ) {
  9017. mode = value;
  9018. }
  9019. let type, bytesPerElement;
  9020. function setIndex( value ) {
  9021. type = value.type;
  9022. bytesPerElement = value.bytesPerElement;
  9023. }
  9024. function render( start, count ) {
  9025. gl.drawElements( mode, count, type, start * bytesPerElement );
  9026. info.update( count, mode, 1 );
  9027. }
  9028. function renderInstances( start, count, primcount ) {
  9029. if ( primcount === 0 ) return;
  9030. let extension, methodName;
  9031. if ( isWebGL2 ) {
  9032. extension = gl;
  9033. methodName = 'drawElementsInstanced';
  9034. } else {
  9035. extension = extensions.get( 'ANGLE_instanced_arrays' );
  9036. methodName = 'drawElementsInstancedANGLE';
  9037. if ( extension === null ) {
  9038. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9039. return;
  9040. }
  9041. }
  9042. extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount );
  9043. info.update( count, mode, primcount );
  9044. }
  9045. //
  9046. this.setMode = setMode;
  9047. this.setIndex = setIndex;
  9048. this.render = render;
  9049. this.renderInstances = renderInstances;
  9050. }
  9051. function WebGLInfo( gl ) {
  9052. const memory = {
  9053. geometries: 0,
  9054. textures: 0
  9055. };
  9056. const render = {
  9057. frame: 0,
  9058. calls: 0,
  9059. triangles: 0,
  9060. points: 0,
  9061. lines: 0
  9062. };
  9063. function update( count, mode, instanceCount ) {
  9064. render.calls ++;
  9065. switch ( mode ) {
  9066. case 4:
  9067. render.triangles += instanceCount * ( count / 3 );
  9068. break;
  9069. case 1:
  9070. render.lines += instanceCount * ( count / 2 );
  9071. break;
  9072. case 3:
  9073. render.lines += instanceCount * ( count - 1 );
  9074. break;
  9075. case 2:
  9076. render.lines += instanceCount * count;
  9077. break;
  9078. case 0:
  9079. render.points += instanceCount * count;
  9080. break;
  9081. default:
  9082. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  9083. break;
  9084. }
  9085. }
  9086. function reset() {
  9087. render.frame ++;
  9088. render.calls = 0;
  9089. render.triangles = 0;
  9090. render.points = 0;
  9091. render.lines = 0;
  9092. }
  9093. return {
  9094. memory: memory,
  9095. render: render,
  9096. programs: null,
  9097. autoReset: true,
  9098. reset: reset,
  9099. update: update
  9100. };
  9101. }
  9102. function numericalSort( a, b ) {
  9103. return a[ 0 ] - b[ 0 ];
  9104. }
  9105. function absNumericalSort( a, b ) {
  9106. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  9107. }
  9108. function WebGLMorphtargets( gl ) {
  9109. const influencesList = {};
  9110. const morphInfluences = new Float32Array( 8 );
  9111. const workInfluences = [];
  9112. for ( let i = 0; i < 8; i ++ ) {
  9113. workInfluences[ i ] = [ i, 0 ];
  9114. }
  9115. function update( object, geometry, material, program ) {
  9116. const objectInfluences = object.morphTargetInfluences;
  9117. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  9118. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  9119. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  9120. let influences = influencesList[ geometry.id ];
  9121. if ( influences === undefined ) {
  9122. // initialise list
  9123. influences = [];
  9124. for ( let i = 0; i < length; i ++ ) {
  9125. influences[ i ] = [ i, 0 ];
  9126. }
  9127. influencesList[ geometry.id ] = influences;
  9128. }
  9129. // Collect influences
  9130. for ( let i = 0; i < length; i ++ ) {
  9131. const influence = influences[ i ];
  9132. influence[ 0 ] = i;
  9133. influence[ 1 ] = objectInfluences[ i ];
  9134. }
  9135. influences.sort( absNumericalSort );
  9136. for ( let i = 0; i < 8; i ++ ) {
  9137. if ( i < length && influences[ i ][ 1 ] ) {
  9138. workInfluences[ i ][ 0 ] = influences[ i ][ 0 ];
  9139. workInfluences[ i ][ 1 ] = influences[ i ][ 1 ];
  9140. } else {
  9141. workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER;
  9142. workInfluences[ i ][ 1 ] = 0;
  9143. }
  9144. }
  9145. workInfluences.sort( numericalSort );
  9146. const morphTargets = material.morphTargets && geometry.morphAttributes.position;
  9147. const morphNormals = material.morphNormals && geometry.morphAttributes.normal;
  9148. let morphInfluencesSum = 0;
  9149. for ( let i = 0; i < 8; i ++ ) {
  9150. const influence = workInfluences[ i ];
  9151. const index = influence[ 0 ];
  9152. const value = influence[ 1 ];
  9153. if ( index !== Number.MAX_SAFE_INTEGER && value ) {
  9154. if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) {
  9155. geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] );
  9156. }
  9157. if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) {
  9158. geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] );
  9159. }
  9160. morphInfluences[ i ] = value;
  9161. morphInfluencesSum += value;
  9162. } else {
  9163. if ( morphTargets && geometry.hasAttribute( 'morphTarget' + i ) === true ) {
  9164. geometry.deleteAttribute( 'morphTarget' + i );
  9165. }
  9166. if ( morphNormals && geometry.hasAttribute( 'morphNormal' + i ) === true ) {
  9167. geometry.deleteAttribute( 'morphNormal' + i );
  9168. }
  9169. morphInfluences[ i ] = 0;
  9170. }
  9171. }
  9172. // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  9173. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  9174. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  9175. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  9176. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  9177. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  9178. }
  9179. return {
  9180. update: update
  9181. };
  9182. }
  9183. function WebGLObjects( gl, geometries, attributes, info ) {
  9184. let updateMap = new WeakMap();
  9185. function update( object ) {
  9186. const frame = info.render.frame;
  9187. const geometry = object.geometry;
  9188. const buffergeometry = geometries.get( object, geometry );
  9189. // Update once per frame
  9190. if ( updateMap.get( buffergeometry ) !== frame ) {
  9191. geometries.update( buffergeometry );
  9192. updateMap.set( buffergeometry, frame );
  9193. }
  9194. if ( object.isInstancedMesh ) {
  9195. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  9196. object.addEventListener( 'dispose', onInstancedMeshDispose );
  9197. }
  9198. attributes.update( object.instanceMatrix, 34962 );
  9199. if ( object.instanceColor !== null ) {
  9200. attributes.update( object.instanceColor, 34962 );
  9201. }
  9202. }
  9203. return buffergeometry;
  9204. }
  9205. function dispose() {
  9206. updateMap = new WeakMap();
  9207. }
  9208. function onInstancedMeshDispose( event ) {
  9209. const instancedMesh = event.target;
  9210. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  9211. attributes.remove( instancedMesh.instanceMatrix );
  9212. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  9213. }
  9214. return {
  9215. update: update,
  9216. dispose: dispose
  9217. };
  9218. }
  9219. class DataTexture2DArray extends Texture {
  9220. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  9221. super( null );
  9222. this.image = { data, width, height, depth };
  9223. this.magFilter = NearestFilter;
  9224. this.minFilter = NearestFilter;
  9225. this.wrapR = ClampToEdgeWrapping;
  9226. this.generateMipmaps = false;
  9227. this.flipY = false;
  9228. this.needsUpdate = true;
  9229. }
  9230. }
  9231. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  9232. class DataTexture3D extends Texture {
  9233. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  9234. // We're going to add .setXXX() methods for setting properties later.
  9235. // Users can still set in DataTexture3D directly.
  9236. //
  9237. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  9238. // texture.anisotropy = 16;
  9239. //
  9240. // See #14839
  9241. super( null );
  9242. this.image = { data, width, height, depth };
  9243. this.magFilter = NearestFilter;
  9244. this.minFilter = NearestFilter;
  9245. this.wrapR = ClampToEdgeWrapping;
  9246. this.generateMipmaps = false;
  9247. this.flipY = false;
  9248. this.needsUpdate = true;
  9249. }
  9250. }
  9251. DataTexture3D.prototype.isDataTexture3D = true;
  9252. /**
  9253. * Uniforms of a program.
  9254. * Those form a tree structure with a special top-level container for the root,
  9255. * which you get by calling 'new WebGLUniforms( gl, program )'.
  9256. *
  9257. *
  9258. * Properties of inner nodes including the top-level container:
  9259. *
  9260. * .seq - array of nested uniforms
  9261. * .map - nested uniforms by name
  9262. *
  9263. *
  9264. * Methods of all nodes except the top-level container:
  9265. *
  9266. * .setValue( gl, value, [textures] )
  9267. *
  9268. * uploads a uniform value(s)
  9269. * the 'textures' parameter is needed for sampler uniforms
  9270. *
  9271. *
  9272. * Static methods of the top-level container (textures factorizations):
  9273. *
  9274. * .upload( gl, seq, values, textures )
  9275. *
  9276. * sets uniforms in 'seq' to 'values[id].value'
  9277. *
  9278. * .seqWithValue( seq, values ) : filteredSeq
  9279. *
  9280. * filters 'seq' entries with corresponding entry in values
  9281. *
  9282. *
  9283. * Methods of the top-level container (textures factorizations):
  9284. *
  9285. * .setValue( gl, name, value, textures )
  9286. *
  9287. * sets uniform with name 'name' to 'value'
  9288. *
  9289. * .setOptional( gl, obj, prop )
  9290. *
  9291. * like .set for an optional property of the object
  9292. *
  9293. */
  9294. const emptyTexture = new Texture();
  9295. const emptyTexture2dArray = new DataTexture2DArray();
  9296. const emptyTexture3d = new DataTexture3D();
  9297. const emptyCubeTexture = new CubeTexture();
  9298. // --- Utilities ---
  9299. // Array Caches (provide typed arrays for temporary by size)
  9300. const arrayCacheF32 = [];
  9301. const arrayCacheI32 = [];
  9302. // Float32Array caches used for uploading Matrix uniforms
  9303. const mat4array = new Float32Array( 16 );
  9304. const mat3array = new Float32Array( 9 );
  9305. const mat2array = new Float32Array( 4 );
  9306. // Flattening for arrays of vectors and matrices
  9307. function flatten( array, nBlocks, blockSize ) {
  9308. const firstElem = array[ 0 ];
  9309. if ( firstElem <= 0 || firstElem > 0 ) return array;
  9310. // unoptimized: ! isNaN( firstElem )
  9311. // see http://jacksondunstan.com/articles/983
  9312. const n = nBlocks * blockSize;
  9313. let r = arrayCacheF32[ n ];
  9314. if ( r === undefined ) {
  9315. r = new Float32Array( n );
  9316. arrayCacheF32[ n ] = r;
  9317. }
  9318. if ( nBlocks !== 0 ) {
  9319. firstElem.toArray( r, 0 );
  9320. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  9321. offset += blockSize;
  9322. array[ i ].toArray( r, offset );
  9323. }
  9324. }
  9325. return r;
  9326. }
  9327. function arraysEqual( a, b ) {
  9328. if ( a.length !== b.length ) return false;
  9329. for ( let i = 0, l = a.length; i < l; i ++ ) {
  9330. if ( a[ i ] !== b[ i ] ) return false;
  9331. }
  9332. return true;
  9333. }
  9334. function copyArray( a, b ) {
  9335. for ( let i = 0, l = b.length; i < l; i ++ ) {
  9336. a[ i ] = b[ i ];
  9337. }
  9338. }
  9339. // Texture unit allocation
  9340. function allocTexUnits( textures, n ) {
  9341. let r = arrayCacheI32[ n ];
  9342. if ( r === undefined ) {
  9343. r = new Int32Array( n );
  9344. arrayCacheI32[ n ] = r;
  9345. }
  9346. for ( let i = 0; i !== n; ++ i ) {
  9347. r[ i ] = textures.allocateTextureUnit();
  9348. }
  9349. return r;
  9350. }
  9351. // --- Setters ---
  9352. // Note: Defining these methods externally, because they come in a bunch
  9353. // and this way their names minify.
  9354. // Single scalar
  9355. function setValueV1f( gl, v ) {
  9356. const cache = this.cache;
  9357. if ( cache[ 0 ] === v ) return;
  9358. gl.uniform1f( this.addr, v );
  9359. cache[ 0 ] = v;
  9360. }
  9361. // Single float vector (from flat array or THREE.VectorN)
  9362. function setValueV2f( gl, v ) {
  9363. const cache = this.cache;
  9364. if ( v.x !== undefined ) {
  9365. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  9366. gl.uniform2f( this.addr, v.x, v.y );
  9367. cache[ 0 ] = v.x;
  9368. cache[ 1 ] = v.y;
  9369. }
  9370. } else {
  9371. if ( arraysEqual( cache, v ) ) return;
  9372. gl.uniform2fv( this.addr, v );
  9373. copyArray( cache, v );
  9374. }
  9375. }
  9376. function setValueV3f( gl, v ) {
  9377. const cache = this.cache;
  9378. if ( v.x !== undefined ) {
  9379. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  9380. gl.uniform3f( this.addr, v.x, v.y, v.z );
  9381. cache[ 0 ] = v.x;
  9382. cache[ 1 ] = v.y;
  9383. cache[ 2 ] = v.z;
  9384. }
  9385. } else if ( v.r !== undefined ) {
  9386. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  9387. gl.uniform3f( this.addr, v.r, v.g, v.b );
  9388. cache[ 0 ] = v.r;
  9389. cache[ 1 ] = v.g;
  9390. cache[ 2 ] = v.b;
  9391. }
  9392. } else {
  9393. if ( arraysEqual( cache, v ) ) return;
  9394. gl.uniform3fv( this.addr, v );
  9395. copyArray( cache, v );
  9396. }
  9397. }
  9398. function setValueV4f( gl, v ) {
  9399. const cache = this.cache;
  9400. if ( v.x !== undefined ) {
  9401. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  9402. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  9403. cache[ 0 ] = v.x;
  9404. cache[ 1 ] = v.y;
  9405. cache[ 2 ] = v.z;
  9406. cache[ 3 ] = v.w;
  9407. }
  9408. } else {
  9409. if ( arraysEqual( cache, v ) ) return;
  9410. gl.uniform4fv( this.addr, v );
  9411. copyArray( cache, v );
  9412. }
  9413. }
  9414. // Single matrix (from flat array or MatrixN)
  9415. function setValueM2( gl, v ) {
  9416. const cache = this.cache;
  9417. const elements = v.elements;
  9418. if ( elements === undefined ) {
  9419. if ( arraysEqual( cache, v ) ) return;
  9420. gl.uniformMatrix2fv( this.addr, false, v );
  9421. copyArray( cache, v );
  9422. } else {
  9423. if ( arraysEqual( cache, elements ) ) return;
  9424. mat2array.set( elements );
  9425. gl.uniformMatrix2fv( this.addr, false, mat2array );
  9426. copyArray( cache, elements );
  9427. }
  9428. }
  9429. function setValueM3( gl, v ) {
  9430. const cache = this.cache;
  9431. const elements = v.elements;
  9432. if ( elements === undefined ) {
  9433. if ( arraysEqual( cache, v ) ) return;
  9434. gl.uniformMatrix3fv( this.addr, false, v );
  9435. copyArray( cache, v );
  9436. } else {
  9437. if ( arraysEqual( cache, elements ) ) return;
  9438. mat3array.set( elements );
  9439. gl.uniformMatrix3fv( this.addr, false, mat3array );
  9440. copyArray( cache, elements );
  9441. }
  9442. }
  9443. function setValueM4( gl, v ) {
  9444. const cache = this.cache;
  9445. const elements = v.elements;
  9446. if ( elements === undefined ) {
  9447. if ( arraysEqual( cache, v ) ) return;
  9448. gl.uniformMatrix4fv( this.addr, false, v );
  9449. copyArray( cache, v );
  9450. } else {
  9451. if ( arraysEqual( cache, elements ) ) return;
  9452. mat4array.set( elements );
  9453. gl.uniformMatrix4fv( this.addr, false, mat4array );
  9454. copyArray( cache, elements );
  9455. }
  9456. }
  9457. // Single texture (2D / Cube)
  9458. function setValueT1( gl, v, textures ) {
  9459. const cache = this.cache;
  9460. const unit = textures.allocateTextureUnit();
  9461. if ( cache[ 0 ] !== unit ) {
  9462. gl.uniform1i( this.addr, unit );
  9463. cache[ 0 ] = unit;
  9464. }
  9465. textures.safeSetTexture2D( v || emptyTexture, unit );
  9466. }
  9467. function setValueT2DArray1( gl, v, textures ) {
  9468. const cache = this.cache;
  9469. const unit = textures.allocateTextureUnit();
  9470. if ( cache[ 0 ] !== unit ) {
  9471. gl.uniform1i( this.addr, unit );
  9472. cache[ 0 ] = unit;
  9473. }
  9474. textures.setTexture2DArray( v || emptyTexture2dArray, unit );
  9475. }
  9476. function setValueT3D1( gl, v, textures ) {
  9477. const cache = this.cache;
  9478. const unit = textures.allocateTextureUnit();
  9479. if ( cache[ 0 ] !== unit ) {
  9480. gl.uniform1i( this.addr, unit );
  9481. cache[ 0 ] = unit;
  9482. }
  9483. textures.setTexture3D( v || emptyTexture3d, unit );
  9484. }
  9485. function setValueT6( gl, v, textures ) {
  9486. const cache = this.cache;
  9487. const unit = textures.allocateTextureUnit();
  9488. if ( cache[ 0 ] !== unit ) {
  9489. gl.uniform1i( this.addr, unit );
  9490. cache[ 0 ] = unit;
  9491. }
  9492. textures.safeSetTextureCube( v || emptyCubeTexture, unit );
  9493. }
  9494. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  9495. function setValueV1i( gl, v ) {
  9496. const cache = this.cache;
  9497. if ( cache[ 0 ] === v ) return;
  9498. gl.uniform1i( this.addr, v );
  9499. cache[ 0 ] = v;
  9500. }
  9501. function setValueV2i( gl, v ) {
  9502. const cache = this.cache;
  9503. if ( arraysEqual( cache, v ) ) return;
  9504. gl.uniform2iv( this.addr, v );
  9505. copyArray( cache, v );
  9506. }
  9507. function setValueV3i( gl, v ) {
  9508. const cache = this.cache;
  9509. if ( arraysEqual( cache, v ) ) return;
  9510. gl.uniform3iv( this.addr, v );
  9511. copyArray( cache, v );
  9512. }
  9513. function setValueV4i( gl, v ) {
  9514. const cache = this.cache;
  9515. if ( arraysEqual( cache, v ) ) return;
  9516. gl.uniform4iv( this.addr, v );
  9517. copyArray( cache, v );
  9518. }
  9519. // uint
  9520. function setValueV1ui( gl, v ) {
  9521. const cache = this.cache;
  9522. if ( cache[ 0 ] === v ) return;
  9523. gl.uniform1ui( this.addr, v );
  9524. cache[ 0 ] = v;
  9525. }
  9526. // Helper to pick the right setter for the singular case
  9527. function getSingularSetter( type ) {
  9528. switch ( type ) {
  9529. case 0x1406: return setValueV1f; // FLOAT
  9530. case 0x8b50: return setValueV2f; // _VEC2
  9531. case 0x8b51: return setValueV3f; // _VEC3
  9532. case 0x8b52: return setValueV4f; // _VEC4
  9533. case 0x8b5a: return setValueM2; // _MAT2
  9534. case 0x8b5b: return setValueM3; // _MAT3
  9535. case 0x8b5c: return setValueM4; // _MAT4
  9536. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  9537. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  9538. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  9539. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  9540. case 0x1405: return setValueV1ui; // UINT
  9541. case 0x8b5e: // SAMPLER_2D
  9542. case 0x8d66: // SAMPLER_EXTERNAL_OES
  9543. case 0x8dca: // INT_SAMPLER_2D
  9544. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  9545. case 0x8b62: // SAMPLER_2D_SHADOW
  9546. return setValueT1;
  9547. case 0x8b5f: // SAMPLER_3D
  9548. case 0x8dcb: // INT_SAMPLER_3D
  9549. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  9550. return setValueT3D1;
  9551. case 0x8b60: // SAMPLER_CUBE
  9552. case 0x8dcc: // INT_SAMPLER_CUBE
  9553. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  9554. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  9555. return setValueT6;
  9556. case 0x8dc1: // SAMPLER_2D_ARRAY
  9557. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  9558. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  9559. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  9560. return setValueT2DArray1;
  9561. }
  9562. }
  9563. // Array of scalars
  9564. function setValueV1fArray( gl, v ) {
  9565. gl.uniform1fv( this.addr, v );
  9566. }
  9567. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  9568. function setValueV1iArray( gl, v ) {
  9569. gl.uniform1iv( this.addr, v );
  9570. }
  9571. function setValueV2iArray( gl, v ) {
  9572. gl.uniform2iv( this.addr, v );
  9573. }
  9574. function setValueV3iArray( gl, v ) {
  9575. gl.uniform3iv( this.addr, v );
  9576. }
  9577. function setValueV4iArray( gl, v ) {
  9578. gl.uniform4iv( this.addr, v );
  9579. }
  9580. // Array of vectors (flat or from THREE classes)
  9581. function setValueV2fArray( gl, v ) {
  9582. const data = flatten( v, this.size, 2 );
  9583. gl.uniform2fv( this.addr, data );
  9584. }
  9585. function setValueV3fArray( gl, v ) {
  9586. const data = flatten( v, this.size, 3 );
  9587. gl.uniform3fv( this.addr, data );
  9588. }
  9589. function setValueV4fArray( gl, v ) {
  9590. const data = flatten( v, this.size, 4 );
  9591. gl.uniform4fv( this.addr, data );
  9592. }
  9593. // Array of matrices (flat or from THREE clases)
  9594. function setValueM2Array( gl, v ) {
  9595. const data = flatten( v, this.size, 4 );
  9596. gl.uniformMatrix2fv( this.addr, false, data );
  9597. }
  9598. function setValueM3Array( gl, v ) {
  9599. const data = flatten( v, this.size, 9 );
  9600. gl.uniformMatrix3fv( this.addr, false, data );
  9601. }
  9602. function setValueM4Array( gl, v ) {
  9603. const data = flatten( v, this.size, 16 );
  9604. gl.uniformMatrix4fv( this.addr, false, data );
  9605. }
  9606. // Array of textures (2D / Cube)
  9607. function setValueT1Array( gl, v, textures ) {
  9608. const n = v.length;
  9609. const units = allocTexUnits( textures, n );
  9610. gl.uniform1iv( this.addr, units );
  9611. for ( let i = 0; i !== n; ++ i ) {
  9612. textures.safeSetTexture2D( v[ i ] || emptyTexture, units[ i ] );
  9613. }
  9614. }
  9615. function setValueT6Array( gl, v, textures ) {
  9616. const n = v.length;
  9617. const units = allocTexUnits( textures, n );
  9618. gl.uniform1iv( this.addr, units );
  9619. for ( let i = 0; i !== n; ++ i ) {
  9620. textures.safeSetTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  9621. }
  9622. }
  9623. // Helper to pick the right setter for a pure (bottom-level) array
  9624. function getPureArraySetter( type ) {
  9625. switch ( type ) {
  9626. case 0x1406: return setValueV1fArray; // FLOAT
  9627. case 0x8b50: return setValueV2fArray; // _VEC2
  9628. case 0x8b51: return setValueV3fArray; // _VEC3
  9629. case 0x8b52: return setValueV4fArray; // _VEC4
  9630. case 0x8b5a: return setValueM2Array; // _MAT2
  9631. case 0x8b5b: return setValueM3Array; // _MAT3
  9632. case 0x8b5c: return setValueM4Array; // _MAT4
  9633. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  9634. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  9635. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  9636. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  9637. case 0x8b5e: // SAMPLER_2D
  9638. case 0x8d66: // SAMPLER_EXTERNAL_OES
  9639. case 0x8dca: // INT_SAMPLER_2D
  9640. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  9641. case 0x8b62: // SAMPLER_2D_SHADOW
  9642. return setValueT1Array;
  9643. case 0x8b60: // SAMPLER_CUBE
  9644. case 0x8dcc: // INT_SAMPLER_CUBE
  9645. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  9646. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  9647. return setValueT6Array;
  9648. }
  9649. }
  9650. // --- Uniform Classes ---
  9651. function SingleUniform( id, activeInfo, addr ) {
  9652. this.id = id;
  9653. this.addr = addr;
  9654. this.cache = [];
  9655. this.setValue = getSingularSetter( activeInfo.type );
  9656. // this.path = activeInfo.name; // DEBUG
  9657. }
  9658. function PureArrayUniform( id, activeInfo, addr ) {
  9659. this.id = id;
  9660. this.addr = addr;
  9661. this.cache = [];
  9662. this.size = activeInfo.size;
  9663. this.setValue = getPureArraySetter( activeInfo.type );
  9664. // this.path = activeInfo.name; // DEBUG
  9665. }
  9666. PureArrayUniform.prototype.updateCache = function ( data ) {
  9667. const cache = this.cache;
  9668. if ( data instanceof Float32Array && cache.length !== data.length ) {
  9669. this.cache = new Float32Array( data.length );
  9670. }
  9671. copyArray( cache, data );
  9672. };
  9673. function StructuredUniform( id ) {
  9674. this.id = id;
  9675. this.seq = [];
  9676. this.map = {};
  9677. }
  9678. StructuredUniform.prototype.setValue = function ( gl, value, textures ) {
  9679. const seq = this.seq;
  9680. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  9681. const u = seq[ i ];
  9682. u.setValue( gl, value[ u.id ], textures );
  9683. }
  9684. };
  9685. // --- Top-level ---
  9686. // Parser - builds up the property tree from the path strings
  9687. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  9688. // extracts
  9689. // - the identifier (member name or array index)
  9690. // - followed by an optional right bracket (found when array index)
  9691. // - followed by an optional left bracket or dot (type of subscript)
  9692. //
  9693. // Note: These portions can be read in a non-overlapping fashion and
  9694. // allow straightforward parsing of the hierarchy that WebGL encodes
  9695. // in the uniform names.
  9696. function addUniform( container, uniformObject ) {
  9697. container.seq.push( uniformObject );
  9698. container.map[ uniformObject.id ] = uniformObject;
  9699. }
  9700. function parseUniform( activeInfo, addr, container ) {
  9701. const path = activeInfo.name,
  9702. pathLength = path.length;
  9703. // reset RegExp object, because of the early exit of a previous run
  9704. RePathPart.lastIndex = 0;
  9705. while ( true ) {
  9706. const match = RePathPart.exec( path ),
  9707. matchEnd = RePathPart.lastIndex;
  9708. let id = match[ 1 ];
  9709. const idIsIndex = match[ 2 ] === ']',
  9710. subscript = match[ 3 ];
  9711. if ( idIsIndex ) id = id | 0; // convert to integer
  9712. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  9713. // bare name or "pure" bottom-level array "[0]" suffix
  9714. addUniform( container, subscript === undefined ?
  9715. new SingleUniform( id, activeInfo, addr ) :
  9716. new PureArrayUniform( id, activeInfo, addr ) );
  9717. break;
  9718. } else {
  9719. // step into inner node / create it in case it doesn't exist
  9720. const map = container.map;
  9721. let next = map[ id ];
  9722. if ( next === undefined ) {
  9723. next = new StructuredUniform( id );
  9724. addUniform( container, next );
  9725. }
  9726. container = next;
  9727. }
  9728. }
  9729. }
  9730. // Root Container
  9731. function WebGLUniforms( gl, program ) {
  9732. this.seq = [];
  9733. this.map = {};
  9734. const n = gl.getProgramParameter( program, 35718 );
  9735. for ( let i = 0; i < n; ++ i ) {
  9736. const info = gl.getActiveUniform( program, i ),
  9737. addr = gl.getUniformLocation( program, info.name );
  9738. parseUniform( info, addr, this );
  9739. }
  9740. }
  9741. WebGLUniforms.prototype.setValue = function ( gl, name, value, textures ) {
  9742. const u = this.map[ name ];
  9743. if ( u !== undefined ) u.setValue( gl, value, textures );
  9744. };
  9745. WebGLUniforms.prototype.setOptional = function ( gl, object, name ) {
  9746. const v = object[ name ];
  9747. if ( v !== undefined ) this.setValue( gl, name, v );
  9748. };
  9749. // Static interface
  9750. WebGLUniforms.upload = function ( gl, seq, values, textures ) {
  9751. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  9752. const u = seq[ i ],
  9753. v = values[ u.id ];
  9754. if ( v.needsUpdate !== false ) {
  9755. // note: always updating when .needsUpdate is undefined
  9756. u.setValue( gl, v.value, textures );
  9757. }
  9758. }
  9759. };
  9760. WebGLUniforms.seqWithValue = function ( seq, values ) {
  9761. const r = [];
  9762. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  9763. const u = seq[ i ];
  9764. if ( u.id in values ) r.push( u );
  9765. }
  9766. return r;
  9767. };
  9768. function WebGLShader( gl, type, string ) {
  9769. const shader = gl.createShader( type );
  9770. gl.shaderSource( shader, string );
  9771. gl.compileShader( shader );
  9772. return shader;
  9773. }
  9774. let programIdCount = 0;
  9775. function addLineNumbers( string ) {
  9776. const lines = string.split( '\n' );
  9777. for ( let i = 0; i < lines.length; i ++ ) {
  9778. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  9779. }
  9780. return lines.join( '\n' );
  9781. }
  9782. function getEncodingComponents( encoding ) {
  9783. switch ( encoding ) {
  9784. case LinearEncoding:
  9785. return [ 'Linear', '( value )' ];
  9786. case sRGBEncoding:
  9787. return [ 'sRGB', '( value )' ];
  9788. case RGBEEncoding:
  9789. return [ 'RGBE', '( value )' ];
  9790. case RGBM7Encoding:
  9791. return [ 'RGBM', '( value, 7.0 )' ];
  9792. case RGBM16Encoding:
  9793. return [ 'RGBM', '( value, 16.0 )' ];
  9794. case RGBDEncoding:
  9795. return [ 'RGBD', '( value, 256.0 )' ];
  9796. case GammaEncoding:
  9797. return [ 'Gamma', '( value, float( GAMMA_FACTOR ) )' ];
  9798. case LogLuvEncoding:
  9799. return [ 'LogLuv', '( value )' ];
  9800. default:
  9801. console.warn( 'THREE.WebGLProgram: Unsupported encoding:', encoding );
  9802. return [ 'Linear', '( value )' ];
  9803. }
  9804. }
  9805. function getShaderErrors( gl, shader, type ) {
  9806. const status = gl.getShaderParameter( shader, 35713 );
  9807. const log = gl.getShaderInfoLog( shader ).trim();
  9808. if ( status && log === '' ) return '';
  9809. // --enable-privileged-webgl-extension
  9810. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  9811. const source = gl.getShaderSource( shader );
  9812. return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers( source );
  9813. }
  9814. function getTexelDecodingFunction( functionName, encoding ) {
  9815. const components = getEncodingComponents( encoding );
  9816. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[ 0 ] + 'ToLinear' + components[ 1 ] + '; }';
  9817. }
  9818. function getTexelEncodingFunction( functionName, encoding ) {
  9819. const components = getEncodingComponents( encoding );
  9820. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';
  9821. }
  9822. function getToneMappingFunction( functionName, toneMapping ) {
  9823. let toneMappingName;
  9824. switch ( toneMapping ) {
  9825. case LinearToneMapping:
  9826. toneMappingName = 'Linear';
  9827. break;
  9828. case ReinhardToneMapping:
  9829. toneMappingName = 'Reinhard';
  9830. break;
  9831. case CineonToneMapping:
  9832. toneMappingName = 'OptimizedCineon';
  9833. break;
  9834. case ACESFilmicToneMapping:
  9835. toneMappingName = 'ACESFilmic';
  9836. break;
  9837. case CustomToneMapping:
  9838. toneMappingName = 'Custom';
  9839. break;
  9840. default:
  9841. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  9842. toneMappingName = 'Linear';
  9843. }
  9844. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  9845. }
  9846. function generateExtensions( parameters ) {
  9847. const chunks = [
  9848. ( parameters.extensionDerivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  9849. ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '',
  9850. ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '',
  9851. ( parameters.extensionShaderTextureLOD || parameters.envMap ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  9852. ];
  9853. return chunks.filter( filterEmptyLine ).join( '\n' );
  9854. }
  9855. function generateDefines( defines ) {
  9856. const chunks = [];
  9857. for ( const name in defines ) {
  9858. const value = defines[ name ];
  9859. if ( value === false ) continue;
  9860. chunks.push( '#define ' + name + ' ' + value );
  9861. }
  9862. return chunks.join( '\n' );
  9863. }
  9864. function fetchAttributeLocations( gl, program ) {
  9865. const attributes = {};
  9866. const n = gl.getProgramParameter( program, 35721 );
  9867. for ( let i = 0; i < n; i ++ ) {
  9868. const info = gl.getActiveAttrib( program, i );
  9869. const name = info.name;
  9870. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  9871. attributes[ name ] = gl.getAttribLocation( program, name );
  9872. }
  9873. return attributes;
  9874. }
  9875. function filterEmptyLine( string ) {
  9876. return string !== '';
  9877. }
  9878. function replaceLightNums( string, parameters ) {
  9879. return string
  9880. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  9881. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  9882. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  9883. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  9884. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  9885. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  9886. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  9887. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  9888. }
  9889. function replaceClippingPlaneNums( string, parameters ) {
  9890. return string
  9891. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  9892. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  9893. }
  9894. // Resolve Includes
  9895. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  9896. function resolveIncludes( string ) {
  9897. return string.replace( includePattern, includeReplacer );
  9898. }
  9899. function includeReplacer( match, include ) {
  9900. const string = ShaderChunk[ include ];
  9901. if ( string === undefined ) {
  9902. throw new Error( 'Can not resolve #include <' + include + '>' );
  9903. }
  9904. return resolveIncludes( string );
  9905. }
  9906. // Unroll Loops
  9907. const deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  9908. 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;
  9909. function unrollLoops( string ) {
  9910. return string
  9911. .replace( unrollLoopPattern, loopReplacer )
  9912. .replace( deprecatedUnrollLoopPattern, deprecatedLoopReplacer );
  9913. }
  9914. function deprecatedLoopReplacer( match, start, end, snippet ) {
  9915. console.warn( 'WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.' );
  9916. return loopReplacer( match, start, end, snippet );
  9917. }
  9918. function loopReplacer( match, start, end, snippet ) {
  9919. let string = '';
  9920. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  9921. string += snippet
  9922. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  9923. .replace( /UNROLLED_LOOP_INDEX/g, i );
  9924. }
  9925. return string;
  9926. }
  9927. //
  9928. function generatePrecision( parameters ) {
  9929. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  9930. if ( parameters.precision === 'highp' ) {
  9931. precisionstring += '\n#define HIGH_PRECISION';
  9932. } else if ( parameters.precision === 'mediump' ) {
  9933. precisionstring += '\n#define MEDIUM_PRECISION';
  9934. } else if ( parameters.precision === 'lowp' ) {
  9935. precisionstring += '\n#define LOW_PRECISION';
  9936. }
  9937. return precisionstring;
  9938. }
  9939. function generateShadowMapTypeDefine( parameters ) {
  9940. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  9941. if ( parameters.shadowMapType === PCFShadowMap ) {
  9942. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  9943. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  9944. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  9945. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  9946. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  9947. }
  9948. return shadowMapTypeDefine;
  9949. }
  9950. function generateEnvMapTypeDefine( parameters ) {
  9951. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  9952. if ( parameters.envMap ) {
  9953. switch ( parameters.envMapMode ) {
  9954. case CubeReflectionMapping:
  9955. case CubeRefractionMapping:
  9956. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  9957. break;
  9958. case CubeUVReflectionMapping:
  9959. case CubeUVRefractionMapping:
  9960. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  9961. break;
  9962. }
  9963. }
  9964. return envMapTypeDefine;
  9965. }
  9966. function generateEnvMapModeDefine( parameters ) {
  9967. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  9968. if ( parameters.envMap ) {
  9969. switch ( parameters.envMapMode ) {
  9970. case CubeRefractionMapping:
  9971. case CubeUVRefractionMapping:
  9972. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  9973. break;
  9974. }
  9975. }
  9976. return envMapModeDefine;
  9977. }
  9978. function generateEnvMapBlendingDefine( parameters ) {
  9979. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  9980. if ( parameters.envMap ) {
  9981. switch ( parameters.combine ) {
  9982. case MultiplyOperation:
  9983. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  9984. break;
  9985. case MixOperation:
  9986. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  9987. break;
  9988. case AddOperation:
  9989. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  9990. break;
  9991. }
  9992. }
  9993. return envMapBlendingDefine;
  9994. }
  9995. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  9996. const gl = renderer.getContext();
  9997. const defines = parameters.defines;
  9998. let vertexShader = parameters.vertexShader;
  9999. let fragmentShader = parameters.fragmentShader;
  10000. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  10001. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  10002. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  10003. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  10004. const gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  10005. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters );
  10006. const customDefines = generateDefines( defines );
  10007. const program = gl.createProgram();
  10008. let prefixVertex, prefixFragment;
  10009. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  10010. if ( parameters.isRawShaderMaterial ) {
  10011. prefixVertex = [
  10012. customDefines
  10013. ].filter( filterEmptyLine ).join( '\n' );
  10014. if ( prefixVertex.length > 0 ) {
  10015. prefixVertex += '\n';
  10016. }
  10017. prefixFragment = [
  10018. customExtensions,
  10019. customDefines
  10020. ].filter( filterEmptyLine ).join( '\n' );
  10021. if ( prefixFragment.length > 0 ) {
  10022. prefixFragment += '\n';
  10023. }
  10024. } else {
  10025. prefixVertex = [
  10026. generatePrecision( parameters ),
  10027. '#define SHADER_NAME ' + parameters.shaderName,
  10028. customDefines,
  10029. parameters.instancing ? '#define USE_INSTANCING' : '',
  10030. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  10031. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  10032. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  10033. '#define MAX_BONES ' + parameters.maxBones,
  10034. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  10035. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  10036. parameters.map ? '#define USE_MAP' : '',
  10037. parameters.envMap ? '#define USE_ENVMAP' : '',
  10038. parameters.envMap ? '#define ' + envMapModeDefine : '',
  10039. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  10040. parameters.aoMap ? '#define USE_AOMAP' : '',
  10041. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  10042. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  10043. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  10044. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  10045. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  10046. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  10047. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  10048. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  10049. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  10050. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  10051. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  10052. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  10053. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  10054. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  10055. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  10056. parameters.vertexColors ? '#define USE_COLOR' : '',
  10057. parameters.vertexUvs ? '#define USE_UV' : '',
  10058. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  10059. parameters.flatShading ? '#define FLAT_SHADED' : '',
  10060. parameters.skinning ? '#define USE_SKINNING' : '',
  10061. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  10062. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  10063. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  10064. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  10065. parameters.flipSided ? '#define FLIP_SIDED' : '',
  10066. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  10067. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  10068. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  10069. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  10070. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  10071. 'uniform mat4 modelMatrix;',
  10072. 'uniform mat4 modelViewMatrix;',
  10073. 'uniform mat4 projectionMatrix;',
  10074. 'uniform mat4 viewMatrix;',
  10075. 'uniform mat3 normalMatrix;',
  10076. 'uniform vec3 cameraPosition;',
  10077. 'uniform bool isOrthographic;',
  10078. '#ifdef USE_INSTANCING',
  10079. ' attribute mat4 instanceMatrix;',
  10080. '#endif',
  10081. '#ifdef USE_INSTANCING_COLOR',
  10082. ' attribute vec3 instanceColor;',
  10083. '#endif',
  10084. 'attribute vec3 position;',
  10085. 'attribute vec3 normal;',
  10086. 'attribute vec2 uv;',
  10087. '#ifdef USE_TANGENT',
  10088. ' attribute vec4 tangent;',
  10089. '#endif',
  10090. '#ifdef USE_COLOR',
  10091. ' attribute vec3 color;',
  10092. '#endif',
  10093. '#ifdef USE_MORPHTARGETS',
  10094. ' attribute vec3 morphTarget0;',
  10095. ' attribute vec3 morphTarget1;',
  10096. ' attribute vec3 morphTarget2;',
  10097. ' attribute vec3 morphTarget3;',
  10098. ' #ifdef USE_MORPHNORMALS',
  10099. ' attribute vec3 morphNormal0;',
  10100. ' attribute vec3 morphNormal1;',
  10101. ' attribute vec3 morphNormal2;',
  10102. ' attribute vec3 morphNormal3;',
  10103. ' #else',
  10104. ' attribute vec3 morphTarget4;',
  10105. ' attribute vec3 morphTarget5;',
  10106. ' attribute vec3 morphTarget6;',
  10107. ' attribute vec3 morphTarget7;',
  10108. ' #endif',
  10109. '#endif',
  10110. '#ifdef USE_SKINNING',
  10111. ' attribute vec4 skinIndex;',
  10112. ' attribute vec4 skinWeight;',
  10113. '#endif',
  10114. '\n'
  10115. ].filter( filterEmptyLine ).join( '\n' );
  10116. prefixFragment = [
  10117. customExtensions,
  10118. generatePrecision( parameters ),
  10119. '#define SHADER_NAME ' + parameters.shaderName,
  10120. customDefines,
  10121. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + ( parameters.alphaTest % 1 ? '' : '.0' ) : '', // add '.0' if integer
  10122. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  10123. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  10124. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  10125. parameters.map ? '#define USE_MAP' : '',
  10126. parameters.matcap ? '#define USE_MATCAP' : '',
  10127. parameters.envMap ? '#define USE_ENVMAP' : '',
  10128. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  10129. parameters.envMap ? '#define ' + envMapModeDefine : '',
  10130. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  10131. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  10132. parameters.aoMap ? '#define USE_AOMAP' : '',
  10133. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  10134. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  10135. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  10136. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  10137. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  10138. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  10139. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  10140. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  10141. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  10142. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  10143. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  10144. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  10145. parameters.sheen ? '#define USE_SHEEN' : '',
  10146. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  10147. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  10148. parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '',
  10149. parameters.vertexUvs ? '#define USE_UV' : '',
  10150. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  10151. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  10152. parameters.flatShading ? '#define FLAT_SHADED' : '',
  10153. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  10154. parameters.flipSided ? '#define FLIP_SIDED' : '',
  10155. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  10156. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  10157. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  10158. parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '',
  10159. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  10160. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  10161. ( ( parameters.extensionShaderTextureLOD || parameters.envMap ) && parameters.rendererExtensionShaderTextureLod ) ? '#define TEXTURE_LOD_EXT' : '',
  10162. 'uniform mat4 viewMatrix;',
  10163. 'uniform vec3 cameraPosition;',
  10164. 'uniform bool isOrthographic;',
  10165. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  10166. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  10167. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  10168. parameters.dithering ? '#define DITHERING' : '',
  10169. ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  10170. parameters.map ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  10171. parameters.matcap ? getTexelDecodingFunction( 'matcapTexelToLinear', parameters.matcapEncoding ) : '',
  10172. parameters.envMap ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  10173. parameters.emissiveMap ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  10174. parameters.lightMap ? getTexelDecodingFunction( 'lightMapTexelToLinear', parameters.lightMapEncoding ) : '',
  10175. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ),
  10176. parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  10177. '\n'
  10178. ].filter( filterEmptyLine ).join( '\n' );
  10179. }
  10180. vertexShader = resolveIncludes( vertexShader );
  10181. vertexShader = replaceLightNums( vertexShader, parameters );
  10182. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  10183. fragmentShader = resolveIncludes( fragmentShader );
  10184. fragmentShader = replaceLightNums( fragmentShader, parameters );
  10185. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  10186. vertexShader = unrollLoops( vertexShader );
  10187. fragmentShader = unrollLoops( fragmentShader );
  10188. if ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) {
  10189. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  10190. versionString = '#version 300 es\n';
  10191. prefixVertex = [
  10192. '#define attribute in',
  10193. '#define varying out',
  10194. '#define texture2D texture'
  10195. ].join( '\n' ) + '\n' + prefixVertex;
  10196. prefixFragment = [
  10197. '#define varying in',
  10198. ( parameters.glslVersion === GLSL3 ) ? '' : 'out highp vec4 pc_fragColor;',
  10199. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  10200. '#define gl_FragDepthEXT gl_FragDepth',
  10201. '#define texture2D texture',
  10202. '#define textureCube texture',
  10203. '#define texture2DProj textureProj',
  10204. '#define texture2DLodEXT textureLod',
  10205. '#define texture2DProjLodEXT textureProjLod',
  10206. '#define textureCubeLodEXT textureLod',
  10207. '#define texture2DGradEXT textureGrad',
  10208. '#define texture2DProjGradEXT textureProjGrad',
  10209. '#define textureCubeGradEXT textureGrad'
  10210. ].join( '\n' ) + '\n' + prefixFragment;
  10211. }
  10212. const vertexGlsl = versionString + prefixVertex + vertexShader;
  10213. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  10214. // console.log( '*VERTEX*', vertexGlsl );
  10215. // console.log( '*FRAGMENT*', fragmentGlsl );
  10216. const glVertexShader = WebGLShader( gl, 35633, vertexGlsl );
  10217. const glFragmentShader = WebGLShader( gl, 35632, fragmentGlsl );
  10218. gl.attachShader( program, glVertexShader );
  10219. gl.attachShader( program, glFragmentShader );
  10220. // Force a particular attribute to index 0.
  10221. if ( parameters.index0AttributeName !== undefined ) {
  10222. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  10223. } else if ( parameters.morphTargets === true ) {
  10224. // programs with morphTargets displace position out of attribute 0
  10225. gl.bindAttribLocation( program, 0, 'position' );
  10226. }
  10227. gl.linkProgram( program );
  10228. // check for link errors
  10229. if ( renderer.debug.checkShaderErrors ) {
  10230. const programLog = gl.getProgramInfoLog( program ).trim();
  10231. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  10232. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  10233. let runnable = true;
  10234. let haveDiagnostics = true;
  10235. if ( gl.getProgramParameter( program, 35714 ) === false ) {
  10236. runnable = false;
  10237. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  10238. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  10239. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter( program, 35715 ), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors );
  10240. } else if ( programLog !== '' ) {
  10241. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  10242. } else if ( vertexLog === '' || fragmentLog === '' ) {
  10243. haveDiagnostics = false;
  10244. }
  10245. if ( haveDiagnostics ) {
  10246. this.diagnostics = {
  10247. runnable: runnable,
  10248. programLog: programLog,
  10249. vertexShader: {
  10250. log: vertexLog,
  10251. prefix: prefixVertex
  10252. },
  10253. fragmentShader: {
  10254. log: fragmentLog,
  10255. prefix: prefixFragment
  10256. }
  10257. };
  10258. }
  10259. }
  10260. // Clean up
  10261. // Crashes in iOS9 and iOS10. #18402
  10262. // gl.detachShader( program, glVertexShader );
  10263. // gl.detachShader( program, glFragmentShader );
  10264. gl.deleteShader( glVertexShader );
  10265. gl.deleteShader( glFragmentShader );
  10266. // set up caching for uniform locations
  10267. let cachedUniforms;
  10268. this.getUniforms = function () {
  10269. if ( cachedUniforms === undefined ) {
  10270. cachedUniforms = new WebGLUniforms( gl, program );
  10271. }
  10272. return cachedUniforms;
  10273. };
  10274. // set up caching for attribute locations
  10275. let cachedAttributes;
  10276. this.getAttributes = function () {
  10277. if ( cachedAttributes === undefined ) {
  10278. cachedAttributes = fetchAttributeLocations( gl, program );
  10279. }
  10280. return cachedAttributes;
  10281. };
  10282. // free resource
  10283. this.destroy = function () {
  10284. bindingStates.releaseStatesOfProgram( this );
  10285. gl.deleteProgram( program );
  10286. this.program = undefined;
  10287. };
  10288. //
  10289. this.name = parameters.shaderName;
  10290. this.id = programIdCount ++;
  10291. this.cacheKey = cacheKey;
  10292. this.usedTimes = 1;
  10293. this.program = program;
  10294. this.vertexShader = glVertexShader;
  10295. this.fragmentShader = glFragmentShader;
  10296. return this;
  10297. }
  10298. function WebGLPrograms( renderer, cubemaps, extensions, capabilities, bindingStates, clipping ) {
  10299. const programs = [];
  10300. const isWebGL2 = capabilities.isWebGL2;
  10301. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  10302. const floatVertexTextures = capabilities.floatVertexTextures;
  10303. const maxVertexUniforms = capabilities.maxVertexUniforms;
  10304. const vertexTextures = capabilities.vertexTextures;
  10305. let precision = capabilities.precision;
  10306. const shaderIDs = {
  10307. MeshDepthMaterial: 'depth',
  10308. MeshDistanceMaterial: 'distanceRGBA',
  10309. MeshNormalMaterial: 'normal',
  10310. MeshBasicMaterial: 'basic',
  10311. MeshLambertMaterial: 'lambert',
  10312. MeshPhongMaterial: 'phong',
  10313. MeshToonMaterial: 'toon',
  10314. MeshStandardMaterial: 'physical',
  10315. MeshPhysicalMaterial: 'physical',
  10316. MeshMatcapMaterial: 'matcap',
  10317. LineBasicMaterial: 'basic',
  10318. LineDashedMaterial: 'dashed',
  10319. PointsMaterial: 'points',
  10320. ShadowMaterial: 'shadow',
  10321. SpriteMaterial: 'sprite'
  10322. };
  10323. const parameterNames = [
  10324. 'precision', 'isWebGL2', 'supportsVertexTextures', 'outputEncoding', 'instancing', 'instancingColor',
  10325. 'map', 'mapEncoding', 'matcap', 'matcapEncoding', 'envMap', 'envMapMode', 'envMapEncoding', 'envMapCubeUV',
  10326. 'lightMap', 'lightMapEncoding', 'aoMap', 'emissiveMap', 'emissiveMapEncoding', 'bumpMap', 'normalMap', 'objectSpaceNormalMap', 'tangentSpaceNormalMap', 'clearcoatMap', 'clearcoatRoughnessMap', 'clearcoatNormalMap', 'displacementMap', 'specularMap',
  10327. 'roughnessMap', 'metalnessMap', 'gradientMap',
  10328. 'alphaMap', 'combine', 'vertexColors', 'vertexTangents', 'vertexUvs', 'uvsVertexOnly', 'fog', 'useFog', 'fogExp2',
  10329. 'flatShading', 'sizeAttenuation', 'logarithmicDepthBuffer', 'skinning',
  10330. 'maxBones', 'useVertexTexture', 'morphTargets', 'morphNormals',
  10331. 'maxMorphTargets', 'maxMorphNormals', 'premultipliedAlpha',
  10332. 'numDirLights', 'numPointLights', 'numSpotLights', 'numHemiLights', 'numRectAreaLights',
  10333. 'numDirLightShadows', 'numPointLightShadows', 'numSpotLightShadows',
  10334. 'shadowMapEnabled', 'shadowMapType', 'toneMapping', 'physicallyCorrectLights',
  10335. 'alphaTest', 'doubleSided', 'flipSided', 'numClippingPlanes', 'numClipIntersection', 'depthPacking', 'dithering',
  10336. 'sheen', 'transmissionMap'
  10337. ];
  10338. function getMaxBones( object ) {
  10339. const skeleton = object.skeleton;
  10340. const bones = skeleton.bones;
  10341. if ( floatVertexTextures ) {
  10342. return 1024;
  10343. } else {
  10344. // default for when object is not specified
  10345. // ( for example when prebuilding shader to be used with multiple objects )
  10346. //
  10347. // - leave some extra space for other uniforms
  10348. // - limit here is ANGLE's 254 max uniform vectors
  10349. // (up to 54 should be safe)
  10350. const nVertexUniforms = maxVertexUniforms;
  10351. const nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  10352. const maxBones = Math.min( nVertexMatrices, bones.length );
  10353. if ( maxBones < bones.length ) {
  10354. console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' );
  10355. return 0;
  10356. }
  10357. return maxBones;
  10358. }
  10359. }
  10360. function getTextureEncodingFromMap( map ) {
  10361. let encoding;
  10362. if ( map && map.isTexture ) {
  10363. encoding = map.encoding;
  10364. } else if ( map && map.isWebGLRenderTarget ) {
  10365. console.warn( 'THREE.WebGLPrograms.getTextureEncodingFromMap: don\'t use render targets as textures. Use their .texture property instead.' );
  10366. encoding = map.texture.encoding;
  10367. } else {
  10368. encoding = LinearEncoding;
  10369. }
  10370. return encoding;
  10371. }
  10372. function getParameters( material, lights, shadows, scene, object ) {
  10373. const fog = scene.fog;
  10374. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  10375. const envMap = cubemaps.get( material.envMap || environment );
  10376. const shaderID = shaderIDs[ material.type ];
  10377. // heuristics to create shader parameters according to lights in the scene
  10378. // (not to blow over maxLights budget)
  10379. const maxBones = object.isSkinnedMesh ? getMaxBones( object ) : 0;
  10380. if ( material.precision !== null ) {
  10381. precision = capabilities.getMaxPrecision( material.precision );
  10382. if ( precision !== material.precision ) {
  10383. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  10384. }
  10385. }
  10386. let vertexShader, fragmentShader;
  10387. if ( shaderID ) {
  10388. const shader = ShaderLib[ shaderID ];
  10389. vertexShader = shader.vertexShader;
  10390. fragmentShader = shader.fragmentShader;
  10391. } else {
  10392. vertexShader = material.vertexShader;
  10393. fragmentShader = material.fragmentShader;
  10394. }
  10395. const currentRenderTarget = renderer.getRenderTarget();
  10396. const parameters = {
  10397. isWebGL2: isWebGL2,
  10398. shaderID: shaderID,
  10399. shaderName: material.type,
  10400. vertexShader: vertexShader,
  10401. fragmentShader: fragmentShader,
  10402. defines: material.defines,
  10403. isRawShaderMaterial: material.isRawShaderMaterial === true,
  10404. glslVersion: material.glslVersion,
  10405. precision: precision,
  10406. instancing: object.isInstancedMesh === true,
  10407. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  10408. supportsVertexTextures: vertexTextures,
  10409. outputEncoding: ( currentRenderTarget !== null ) ? getTextureEncodingFromMap( currentRenderTarget.texture ) : renderer.outputEncoding,
  10410. map: !! material.map,
  10411. mapEncoding: getTextureEncodingFromMap( material.map ),
  10412. matcap: !! material.matcap,
  10413. matcapEncoding: getTextureEncodingFromMap( material.matcap ),
  10414. envMap: !! envMap,
  10415. envMapMode: envMap && envMap.mapping,
  10416. envMapEncoding: getTextureEncodingFromMap( envMap ),
  10417. envMapCubeUV: ( !! envMap ) && ( ( envMap.mapping === CubeUVReflectionMapping ) || ( envMap.mapping === CubeUVRefractionMapping ) ),
  10418. lightMap: !! material.lightMap,
  10419. lightMapEncoding: getTextureEncodingFromMap( material.lightMap ),
  10420. aoMap: !! material.aoMap,
  10421. emissiveMap: !! material.emissiveMap,
  10422. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap ),
  10423. bumpMap: !! material.bumpMap,
  10424. normalMap: !! material.normalMap,
  10425. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  10426. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  10427. clearcoatMap: !! material.clearcoatMap,
  10428. clearcoatRoughnessMap: !! material.clearcoatRoughnessMap,
  10429. clearcoatNormalMap: !! material.clearcoatNormalMap,
  10430. displacementMap: !! material.displacementMap,
  10431. roughnessMap: !! material.roughnessMap,
  10432. metalnessMap: !! material.metalnessMap,
  10433. specularMap: !! material.specularMap,
  10434. alphaMap: !! material.alphaMap,
  10435. gradientMap: !! material.gradientMap,
  10436. sheen: !! material.sheen,
  10437. transmissionMap: !! material.transmissionMap,
  10438. combine: material.combine,
  10439. vertexTangents: ( material.normalMap && material.vertexTangents ),
  10440. vertexColors: material.vertexColors,
  10441. 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,
  10442. uvsVertexOnly: ! ( !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap || !! material.transmissionMap ) && !! material.displacementMap,
  10443. fog: !! fog,
  10444. useFog: material.fog,
  10445. fogExp2: ( fog && fog.isFogExp2 ),
  10446. flatShading: !! material.flatShading,
  10447. sizeAttenuation: material.sizeAttenuation,
  10448. logarithmicDepthBuffer: logarithmicDepthBuffer,
  10449. skinning: material.skinning && maxBones > 0,
  10450. maxBones: maxBones,
  10451. useVertexTexture: floatVertexTextures,
  10452. morphTargets: material.morphTargets,
  10453. morphNormals: material.morphNormals,
  10454. maxMorphTargets: renderer.maxMorphTargets,
  10455. maxMorphNormals: renderer.maxMorphNormals,
  10456. numDirLights: lights.directional.length,
  10457. numPointLights: lights.point.length,
  10458. numSpotLights: lights.spot.length,
  10459. numRectAreaLights: lights.rectArea.length,
  10460. numHemiLights: lights.hemi.length,
  10461. numDirLightShadows: lights.directionalShadowMap.length,
  10462. numPointLightShadows: lights.pointShadowMap.length,
  10463. numSpotLightShadows: lights.spotShadowMap.length,
  10464. numClippingPlanes: clipping.numPlanes,
  10465. numClipIntersection: clipping.numIntersection,
  10466. dithering: material.dithering,
  10467. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  10468. shadowMapType: renderer.shadowMap.type,
  10469. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  10470. physicallyCorrectLights: renderer.physicallyCorrectLights,
  10471. premultipliedAlpha: material.premultipliedAlpha,
  10472. alphaTest: material.alphaTest,
  10473. doubleSided: material.side === DoubleSide,
  10474. flipSided: material.side === BackSide,
  10475. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false,
  10476. index0AttributeName: material.index0AttributeName,
  10477. extensionDerivatives: material.extensions && material.extensions.derivatives,
  10478. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  10479. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  10480. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  10481. rendererExtensionFragDepth: isWebGL2 || extensions.has( 'EXT_frag_depth' ),
  10482. rendererExtensionDrawBuffers: isWebGL2 || extensions.has( 'WEBGL_draw_buffers' ),
  10483. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has( 'EXT_shader_texture_lod' ),
  10484. customProgramCacheKey: material.customProgramCacheKey()
  10485. };
  10486. return parameters;
  10487. }
  10488. function getProgramCacheKey( parameters ) {
  10489. const array = [];
  10490. if ( parameters.shaderID ) {
  10491. array.push( parameters.shaderID );
  10492. } else {
  10493. array.push( parameters.fragmentShader );
  10494. array.push( parameters.vertexShader );
  10495. }
  10496. if ( parameters.defines !== undefined ) {
  10497. for ( const name in parameters.defines ) {
  10498. array.push( name );
  10499. array.push( parameters.defines[ name ] );
  10500. }
  10501. }
  10502. if ( parameters.isRawShaderMaterial === false ) {
  10503. for ( let i = 0; i < parameterNames.length; i ++ ) {
  10504. array.push( parameters[ parameterNames[ i ] ] );
  10505. }
  10506. array.push( renderer.outputEncoding );
  10507. array.push( renderer.gammaFactor );
  10508. }
  10509. array.push( parameters.customProgramCacheKey );
  10510. return array.join();
  10511. }
  10512. function getUniforms( material ) {
  10513. const shaderID = shaderIDs[ material.type ];
  10514. let uniforms;
  10515. if ( shaderID ) {
  10516. const shader = ShaderLib[ shaderID ];
  10517. uniforms = UniformsUtils.clone( shader.uniforms );
  10518. } else {
  10519. uniforms = material.uniforms;
  10520. }
  10521. return uniforms;
  10522. }
  10523. function acquireProgram( parameters, cacheKey ) {
  10524. let program;
  10525. // Check if code has been already compiled
  10526. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  10527. const preexistingProgram = programs[ p ];
  10528. if ( preexistingProgram.cacheKey === cacheKey ) {
  10529. program = preexistingProgram;
  10530. ++ program.usedTimes;
  10531. break;
  10532. }
  10533. }
  10534. if ( program === undefined ) {
  10535. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  10536. programs.push( program );
  10537. }
  10538. return program;
  10539. }
  10540. function releaseProgram( program ) {
  10541. if ( -- program.usedTimes === 0 ) {
  10542. // Remove from unordered set
  10543. const i = programs.indexOf( program );
  10544. programs[ i ] = programs[ programs.length - 1 ];
  10545. programs.pop();
  10546. // Free WebGL resources
  10547. program.destroy();
  10548. }
  10549. }
  10550. return {
  10551. getParameters: getParameters,
  10552. getProgramCacheKey: getProgramCacheKey,
  10553. getUniforms: getUniforms,
  10554. acquireProgram: acquireProgram,
  10555. releaseProgram: releaseProgram,
  10556. // Exposed for resource monitoring & error feedback via renderer.info:
  10557. programs: programs
  10558. };
  10559. }
  10560. function WebGLProperties() {
  10561. let properties = new WeakMap();
  10562. function get( object ) {
  10563. let map = properties.get( object );
  10564. if ( map === undefined ) {
  10565. map = {};
  10566. properties.set( object, map );
  10567. }
  10568. return map;
  10569. }
  10570. function remove( object ) {
  10571. properties.delete( object );
  10572. }
  10573. function update( object, key, value ) {
  10574. properties.get( object )[ key ] = value;
  10575. }
  10576. function dispose() {
  10577. properties = new WeakMap();
  10578. }
  10579. return {
  10580. get: get,
  10581. remove: remove,
  10582. update: update,
  10583. dispose: dispose
  10584. };
  10585. }
  10586. function painterSortStable( a, b ) {
  10587. if ( a.groupOrder !== b.groupOrder ) {
  10588. return a.groupOrder - b.groupOrder;
  10589. } else if ( a.renderOrder !== b.renderOrder ) {
  10590. return a.renderOrder - b.renderOrder;
  10591. } else if ( a.program !== b.program ) {
  10592. return a.program.id - b.program.id;
  10593. } else if ( a.material.id !== b.material.id ) {
  10594. return a.material.id - b.material.id;
  10595. } else if ( a.z !== b.z ) {
  10596. return a.z - b.z;
  10597. } else {
  10598. return a.id - b.id;
  10599. }
  10600. }
  10601. function reversePainterSortStable( a, b ) {
  10602. if ( a.groupOrder !== b.groupOrder ) {
  10603. return a.groupOrder - b.groupOrder;
  10604. } else if ( a.renderOrder !== b.renderOrder ) {
  10605. return a.renderOrder - b.renderOrder;
  10606. } else if ( a.z !== b.z ) {
  10607. return b.z - a.z;
  10608. } else {
  10609. return a.id - b.id;
  10610. }
  10611. }
  10612. function WebGLRenderList( properties ) {
  10613. const renderItems = [];
  10614. let renderItemsIndex = 0;
  10615. const opaque = [];
  10616. const transparent = [];
  10617. const defaultProgram = { id: - 1 };
  10618. function init() {
  10619. renderItemsIndex = 0;
  10620. opaque.length = 0;
  10621. transparent.length = 0;
  10622. }
  10623. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  10624. let renderItem = renderItems[ renderItemsIndex ];
  10625. const materialProperties = properties.get( material );
  10626. if ( renderItem === undefined ) {
  10627. renderItem = {
  10628. id: object.id,
  10629. object: object,
  10630. geometry: geometry,
  10631. material: material,
  10632. program: materialProperties.program || defaultProgram,
  10633. groupOrder: groupOrder,
  10634. renderOrder: object.renderOrder,
  10635. z: z,
  10636. group: group
  10637. };
  10638. renderItems[ renderItemsIndex ] = renderItem;
  10639. } else {
  10640. renderItem.id = object.id;
  10641. renderItem.object = object;
  10642. renderItem.geometry = geometry;
  10643. renderItem.material = material;
  10644. renderItem.program = materialProperties.program || defaultProgram;
  10645. renderItem.groupOrder = groupOrder;
  10646. renderItem.renderOrder = object.renderOrder;
  10647. renderItem.z = z;
  10648. renderItem.group = group;
  10649. }
  10650. renderItemsIndex ++;
  10651. return renderItem;
  10652. }
  10653. function push( object, geometry, material, groupOrder, z, group ) {
  10654. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  10655. ( material.transparent === true ? transparent : opaque ).push( renderItem );
  10656. }
  10657. function unshift( object, geometry, material, groupOrder, z, group ) {
  10658. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  10659. ( material.transparent === true ? transparent : opaque ).unshift( renderItem );
  10660. }
  10661. function sort( customOpaqueSort, customTransparentSort ) {
  10662. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  10663. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  10664. }
  10665. function finish() {
  10666. // Clear references from inactive renderItems in the list
  10667. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  10668. const renderItem = renderItems[ i ];
  10669. if ( renderItem.id === null ) break;
  10670. renderItem.id = null;
  10671. renderItem.object = null;
  10672. renderItem.geometry = null;
  10673. renderItem.material = null;
  10674. renderItem.program = null;
  10675. renderItem.group = null;
  10676. }
  10677. }
  10678. return {
  10679. opaque: opaque,
  10680. transparent: transparent,
  10681. init: init,
  10682. push: push,
  10683. unshift: unshift,
  10684. finish: finish,
  10685. sort: sort
  10686. };
  10687. }
  10688. function WebGLRenderLists( properties ) {
  10689. let lists = new WeakMap();
  10690. function get( scene, renderCallDepth ) {
  10691. let list;
  10692. if ( lists.has( scene ) === false ) {
  10693. list = new WebGLRenderList( properties );
  10694. lists.set( scene, [ list ] );
  10695. } else {
  10696. if ( renderCallDepth >= lists.get( scene ).length ) {
  10697. list = new WebGLRenderList( properties );
  10698. lists.get( scene ).push( list );
  10699. } else {
  10700. list = lists.get( scene )[ renderCallDepth ];
  10701. }
  10702. }
  10703. return list;
  10704. }
  10705. function dispose() {
  10706. lists = new WeakMap();
  10707. }
  10708. return {
  10709. get: get,
  10710. dispose: dispose
  10711. };
  10712. }
  10713. function UniformsCache() {
  10714. const lights = {};
  10715. return {
  10716. get: function ( light ) {
  10717. if ( lights[ light.id ] !== undefined ) {
  10718. return lights[ light.id ];
  10719. }
  10720. let uniforms;
  10721. switch ( light.type ) {
  10722. case 'DirectionalLight':
  10723. uniforms = {
  10724. direction: new Vector3(),
  10725. color: new Color()
  10726. };
  10727. break;
  10728. case 'SpotLight':
  10729. uniforms = {
  10730. position: new Vector3(),
  10731. direction: new Vector3(),
  10732. color: new Color(),
  10733. distance: 0,
  10734. coneCos: 0,
  10735. penumbraCos: 0,
  10736. decay: 0
  10737. };
  10738. break;
  10739. case 'PointLight':
  10740. uniforms = {
  10741. position: new Vector3(),
  10742. color: new Color(),
  10743. distance: 0,
  10744. decay: 0
  10745. };
  10746. break;
  10747. case 'HemisphereLight':
  10748. uniforms = {
  10749. direction: new Vector3(),
  10750. skyColor: new Color(),
  10751. groundColor: new Color()
  10752. };
  10753. break;
  10754. case 'RectAreaLight':
  10755. uniforms = {
  10756. color: new Color(),
  10757. position: new Vector3(),
  10758. halfWidth: new Vector3(),
  10759. halfHeight: new Vector3()
  10760. };
  10761. break;
  10762. }
  10763. lights[ light.id ] = uniforms;
  10764. return uniforms;
  10765. }
  10766. };
  10767. }
  10768. function ShadowUniformsCache() {
  10769. const lights = {};
  10770. return {
  10771. get: function ( light ) {
  10772. if ( lights[ light.id ] !== undefined ) {
  10773. return lights[ light.id ];
  10774. }
  10775. let uniforms;
  10776. switch ( light.type ) {
  10777. case 'DirectionalLight':
  10778. uniforms = {
  10779. shadowBias: 0,
  10780. shadowNormalBias: 0,
  10781. shadowRadius: 1,
  10782. shadowMapSize: new Vector2()
  10783. };
  10784. break;
  10785. case 'SpotLight':
  10786. uniforms = {
  10787. shadowBias: 0,
  10788. shadowNormalBias: 0,
  10789. shadowRadius: 1,
  10790. shadowMapSize: new Vector2()
  10791. };
  10792. break;
  10793. case 'PointLight':
  10794. uniforms = {
  10795. shadowBias: 0,
  10796. shadowNormalBias: 0,
  10797. shadowRadius: 1,
  10798. shadowMapSize: new Vector2(),
  10799. shadowCameraNear: 1,
  10800. shadowCameraFar: 1000
  10801. };
  10802. break;
  10803. // TODO (abelnation): set RectAreaLight shadow uniforms
  10804. }
  10805. lights[ light.id ] = uniforms;
  10806. return uniforms;
  10807. }
  10808. };
  10809. }
  10810. let nextVersion = 0;
  10811. function shadowCastingLightsFirst( lightA, lightB ) {
  10812. return ( lightB.castShadow ? 1 : 0 ) - ( lightA.castShadow ? 1 : 0 );
  10813. }
  10814. function WebGLLights( extensions, capabilities ) {
  10815. const cache = new UniformsCache();
  10816. const shadowCache = ShadowUniformsCache();
  10817. const state = {
  10818. version: 0,
  10819. hash: {
  10820. directionalLength: - 1,
  10821. pointLength: - 1,
  10822. spotLength: - 1,
  10823. rectAreaLength: - 1,
  10824. hemiLength: - 1,
  10825. numDirectionalShadows: - 1,
  10826. numPointShadows: - 1,
  10827. numSpotShadows: - 1
  10828. },
  10829. ambient: [ 0, 0, 0 ],
  10830. probe: [],
  10831. directional: [],
  10832. directionalShadow: [],
  10833. directionalShadowMap: [],
  10834. directionalShadowMatrix: [],
  10835. spot: [],
  10836. spotShadow: [],
  10837. spotShadowMap: [],
  10838. spotShadowMatrix: [],
  10839. rectArea: [],
  10840. rectAreaLTC1: null,
  10841. rectAreaLTC2: null,
  10842. point: [],
  10843. pointShadow: [],
  10844. pointShadowMap: [],
  10845. pointShadowMatrix: [],
  10846. hemi: []
  10847. };
  10848. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  10849. const vector3 = new Vector3();
  10850. const matrix4 = new Matrix4();
  10851. const matrix42 = new Matrix4();
  10852. function setup( lights ) {
  10853. let r = 0, g = 0, b = 0;
  10854. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  10855. let directionalLength = 0;
  10856. let pointLength = 0;
  10857. let spotLength = 0;
  10858. let rectAreaLength = 0;
  10859. let hemiLength = 0;
  10860. let numDirectionalShadows = 0;
  10861. let numPointShadows = 0;
  10862. let numSpotShadows = 0;
  10863. lights.sort( shadowCastingLightsFirst );
  10864. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  10865. const light = lights[ i ];
  10866. const color = light.color;
  10867. const intensity = light.intensity;
  10868. const distance = light.distance;
  10869. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  10870. if ( light.isAmbientLight ) {
  10871. r += color.r * intensity;
  10872. g += color.g * intensity;
  10873. b += color.b * intensity;
  10874. } else if ( light.isLightProbe ) {
  10875. for ( let j = 0; j < 9; j ++ ) {
  10876. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  10877. }
  10878. } else if ( light.isDirectionalLight ) {
  10879. const uniforms = cache.get( light );
  10880. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  10881. if ( light.castShadow ) {
  10882. const shadow = light.shadow;
  10883. const shadowUniforms = shadowCache.get( light );
  10884. shadowUniforms.shadowBias = shadow.bias;
  10885. shadowUniforms.shadowNormalBias = shadow.normalBias;
  10886. shadowUniforms.shadowRadius = shadow.radius;
  10887. shadowUniforms.shadowMapSize = shadow.mapSize;
  10888. state.directionalShadow[ directionalLength ] = shadowUniforms;
  10889. state.directionalShadowMap[ directionalLength ] = shadowMap;
  10890. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  10891. numDirectionalShadows ++;
  10892. }
  10893. state.directional[ directionalLength ] = uniforms;
  10894. directionalLength ++;
  10895. } else if ( light.isSpotLight ) {
  10896. const uniforms = cache.get( light );
  10897. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  10898. uniforms.color.copy( color ).multiplyScalar( intensity );
  10899. uniforms.distance = distance;
  10900. uniforms.coneCos = Math.cos( light.angle );
  10901. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  10902. uniforms.decay = light.decay;
  10903. if ( light.castShadow ) {
  10904. const shadow = light.shadow;
  10905. const shadowUniforms = shadowCache.get( light );
  10906. shadowUniforms.shadowBias = shadow.bias;
  10907. shadowUniforms.shadowNormalBias = shadow.normalBias;
  10908. shadowUniforms.shadowRadius = shadow.radius;
  10909. shadowUniforms.shadowMapSize = shadow.mapSize;
  10910. state.spotShadow[ spotLength ] = shadowUniforms;
  10911. state.spotShadowMap[ spotLength ] = shadowMap;
  10912. state.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  10913. numSpotShadows ++;
  10914. }
  10915. state.spot[ spotLength ] = uniforms;
  10916. spotLength ++;
  10917. } else if ( light.isRectAreaLight ) {
  10918. const uniforms = cache.get( light );
  10919. // (a) intensity is the total visible light emitted
  10920. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  10921. // (b) intensity is the brightness of the light
  10922. uniforms.color.copy( color ).multiplyScalar( intensity );
  10923. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  10924. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  10925. state.rectArea[ rectAreaLength ] = uniforms;
  10926. rectAreaLength ++;
  10927. } else if ( light.isPointLight ) {
  10928. const uniforms = cache.get( light );
  10929. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  10930. uniforms.distance = light.distance;
  10931. uniforms.decay = light.decay;
  10932. if ( light.castShadow ) {
  10933. const shadow = light.shadow;
  10934. const shadowUniforms = shadowCache.get( light );
  10935. shadowUniforms.shadowBias = shadow.bias;
  10936. shadowUniforms.shadowNormalBias = shadow.normalBias;
  10937. shadowUniforms.shadowRadius = shadow.radius;
  10938. shadowUniforms.shadowMapSize = shadow.mapSize;
  10939. shadowUniforms.shadowCameraNear = shadow.camera.near;
  10940. shadowUniforms.shadowCameraFar = shadow.camera.far;
  10941. state.pointShadow[ pointLength ] = shadowUniforms;
  10942. state.pointShadowMap[ pointLength ] = shadowMap;
  10943. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  10944. numPointShadows ++;
  10945. }
  10946. state.point[ pointLength ] = uniforms;
  10947. pointLength ++;
  10948. } else if ( light.isHemisphereLight ) {
  10949. const uniforms = cache.get( light );
  10950. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  10951. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  10952. state.hemi[ hemiLength ] = uniforms;
  10953. hemiLength ++;
  10954. }
  10955. }
  10956. if ( rectAreaLength > 0 ) {
  10957. if ( capabilities.isWebGL2 ) {
  10958. // WebGL 2
  10959. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  10960. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  10961. } else {
  10962. // WebGL 1
  10963. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  10964. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  10965. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  10966. } else if ( extensions.has( 'OES_texture_half_float_linear' ) === true ) {
  10967. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  10968. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  10969. } else {
  10970. console.error( 'THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.' );
  10971. }
  10972. }
  10973. }
  10974. state.ambient[ 0 ] = r;
  10975. state.ambient[ 1 ] = g;
  10976. state.ambient[ 2 ] = b;
  10977. const hash = state.hash;
  10978. if ( hash.directionalLength !== directionalLength ||
  10979. hash.pointLength !== pointLength ||
  10980. hash.spotLength !== spotLength ||
  10981. hash.rectAreaLength !== rectAreaLength ||
  10982. hash.hemiLength !== hemiLength ||
  10983. hash.numDirectionalShadows !== numDirectionalShadows ||
  10984. hash.numPointShadows !== numPointShadows ||
  10985. hash.numSpotShadows !== numSpotShadows ) {
  10986. state.directional.length = directionalLength;
  10987. state.spot.length = spotLength;
  10988. state.rectArea.length = rectAreaLength;
  10989. state.point.length = pointLength;
  10990. state.hemi.length = hemiLength;
  10991. state.directionalShadow.length = numDirectionalShadows;
  10992. state.directionalShadowMap.length = numDirectionalShadows;
  10993. state.pointShadow.length = numPointShadows;
  10994. state.pointShadowMap.length = numPointShadows;
  10995. state.spotShadow.length = numSpotShadows;
  10996. state.spotShadowMap.length = numSpotShadows;
  10997. state.directionalShadowMatrix.length = numDirectionalShadows;
  10998. state.pointShadowMatrix.length = numPointShadows;
  10999. state.spotShadowMatrix.length = numSpotShadows;
  11000. hash.directionalLength = directionalLength;
  11001. hash.pointLength = pointLength;
  11002. hash.spotLength = spotLength;
  11003. hash.rectAreaLength = rectAreaLength;
  11004. hash.hemiLength = hemiLength;
  11005. hash.numDirectionalShadows = numDirectionalShadows;
  11006. hash.numPointShadows = numPointShadows;
  11007. hash.numSpotShadows = numSpotShadows;
  11008. state.version = nextVersion ++;
  11009. }
  11010. }
  11011. function setupView( lights, camera ) {
  11012. let directionalLength = 0;
  11013. let pointLength = 0;
  11014. let spotLength = 0;
  11015. let rectAreaLength = 0;
  11016. let hemiLength = 0;
  11017. const viewMatrix = camera.matrixWorldInverse;
  11018. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  11019. const light = lights[ i ];
  11020. if ( light.isDirectionalLight ) {
  11021. const uniforms = state.directional[ directionalLength ];
  11022. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  11023. vector3.setFromMatrixPosition( light.target.matrixWorld );
  11024. uniforms.direction.sub( vector3 );
  11025. uniforms.direction.transformDirection( viewMatrix );
  11026. directionalLength ++;
  11027. } else if ( light.isSpotLight ) {
  11028. const uniforms = state.spot[ spotLength ];
  11029. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  11030. uniforms.position.applyMatrix4( viewMatrix );
  11031. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  11032. vector3.setFromMatrixPosition( light.target.matrixWorld );
  11033. uniforms.direction.sub( vector3 );
  11034. uniforms.direction.transformDirection( viewMatrix );
  11035. spotLength ++;
  11036. } else if ( light.isRectAreaLight ) {
  11037. const uniforms = state.rectArea[ rectAreaLength ];
  11038. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  11039. uniforms.position.applyMatrix4( viewMatrix );
  11040. // extract local rotation of light to derive width/height half vectors
  11041. matrix42.identity();
  11042. matrix4.copy( light.matrixWorld );
  11043. matrix4.premultiply( viewMatrix );
  11044. matrix42.extractRotation( matrix4 );
  11045. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  11046. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  11047. uniforms.halfWidth.applyMatrix4( matrix42 );
  11048. uniforms.halfHeight.applyMatrix4( matrix42 );
  11049. rectAreaLength ++;
  11050. } else if ( light.isPointLight ) {
  11051. const uniforms = state.point[ pointLength ];
  11052. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  11053. uniforms.position.applyMatrix4( viewMatrix );
  11054. pointLength ++;
  11055. } else if ( light.isHemisphereLight ) {
  11056. const uniforms = state.hemi[ hemiLength ];
  11057. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  11058. uniforms.direction.transformDirection( viewMatrix );
  11059. uniforms.direction.normalize();
  11060. hemiLength ++;
  11061. }
  11062. }
  11063. }
  11064. return {
  11065. setup: setup,
  11066. setupView: setupView,
  11067. state: state
  11068. };
  11069. }
  11070. function WebGLRenderState( extensions, capabilities ) {
  11071. const lights = new WebGLLights( extensions, capabilities );
  11072. const lightsArray = [];
  11073. const shadowsArray = [];
  11074. function init() {
  11075. lightsArray.length = 0;
  11076. shadowsArray.length = 0;
  11077. }
  11078. function pushLight( light ) {
  11079. lightsArray.push( light );
  11080. }
  11081. function pushShadow( shadowLight ) {
  11082. shadowsArray.push( shadowLight );
  11083. }
  11084. function setupLights() {
  11085. lights.setup( lightsArray );
  11086. }
  11087. function setupLightsView( camera ) {
  11088. lights.setupView( lightsArray, camera );
  11089. }
  11090. const state = {
  11091. lightsArray: lightsArray,
  11092. shadowsArray: shadowsArray,
  11093. lights: lights
  11094. };
  11095. return {
  11096. init: init,
  11097. state: state,
  11098. setupLights: setupLights,
  11099. setupLightsView: setupLightsView,
  11100. pushLight: pushLight,
  11101. pushShadow: pushShadow
  11102. };
  11103. }
  11104. function WebGLRenderStates( extensions, capabilities ) {
  11105. let renderStates = new WeakMap();
  11106. function get( scene, renderCallDepth = 0 ) {
  11107. let renderState;
  11108. if ( renderStates.has( scene ) === false ) {
  11109. renderState = new WebGLRenderState( extensions, capabilities );
  11110. renderStates.set( scene, [ renderState ] );
  11111. } else {
  11112. if ( renderCallDepth >= renderStates.get( scene ).length ) {
  11113. renderState = new WebGLRenderState( extensions, capabilities );
  11114. renderStates.get( scene ).push( renderState );
  11115. } else {
  11116. renderState = renderStates.get( scene )[ renderCallDepth ];
  11117. }
  11118. }
  11119. return renderState;
  11120. }
  11121. function dispose() {
  11122. renderStates = new WeakMap();
  11123. }
  11124. return {
  11125. get: get,
  11126. dispose: dispose
  11127. };
  11128. }
  11129. /**
  11130. * parameters = {
  11131. *
  11132. * opacity: <float>,
  11133. *
  11134. * map: new THREE.Texture( <Image> ),
  11135. *
  11136. * alphaMap: new THREE.Texture( <Image> ),
  11137. *
  11138. * displacementMap: new THREE.Texture( <Image> ),
  11139. * displacementScale: <float>,
  11140. * displacementBias: <float>,
  11141. *
  11142. * wireframe: <boolean>,
  11143. * wireframeLinewidth: <float>
  11144. * }
  11145. */
  11146. class MeshDepthMaterial extends Material {
  11147. constructor( parameters ) {
  11148. super();
  11149. this.type = 'MeshDepthMaterial';
  11150. this.depthPacking = BasicDepthPacking;
  11151. this.skinning = false;
  11152. this.morphTargets = false;
  11153. this.map = null;
  11154. this.alphaMap = null;
  11155. this.displacementMap = null;
  11156. this.displacementScale = 1;
  11157. this.displacementBias = 0;
  11158. this.wireframe = false;
  11159. this.wireframeLinewidth = 1;
  11160. this.fog = false;
  11161. this.setValues( parameters );
  11162. }
  11163. copy( source ) {
  11164. super.copy( source );
  11165. this.depthPacking = source.depthPacking;
  11166. this.skinning = source.skinning;
  11167. this.morphTargets = source.morphTargets;
  11168. this.map = source.map;
  11169. this.alphaMap = source.alphaMap;
  11170. this.displacementMap = source.displacementMap;
  11171. this.displacementScale = source.displacementScale;
  11172. this.displacementBias = source.displacementBias;
  11173. this.wireframe = source.wireframe;
  11174. this.wireframeLinewidth = source.wireframeLinewidth;
  11175. return this;
  11176. }
  11177. }
  11178. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  11179. /**
  11180. * parameters = {
  11181. *
  11182. * referencePosition: <float>,
  11183. * nearDistance: <float>,
  11184. * farDistance: <float>,
  11185. *
  11186. * skinning: <bool>,
  11187. * morphTargets: <bool>,
  11188. *
  11189. * map: new THREE.Texture( <Image> ),
  11190. *
  11191. * alphaMap: new THREE.Texture( <Image> ),
  11192. *
  11193. * displacementMap: new THREE.Texture( <Image> ),
  11194. * displacementScale: <float>,
  11195. * displacementBias: <float>
  11196. *
  11197. * }
  11198. */
  11199. class MeshDistanceMaterial extends Material {
  11200. constructor( parameters ) {
  11201. super();
  11202. this.type = 'MeshDistanceMaterial';
  11203. this.referencePosition = new Vector3();
  11204. this.nearDistance = 1;
  11205. this.farDistance = 1000;
  11206. this.skinning = false;
  11207. this.morphTargets = false;
  11208. this.map = null;
  11209. this.alphaMap = null;
  11210. this.displacementMap = null;
  11211. this.displacementScale = 1;
  11212. this.displacementBias = 0;
  11213. this.fog = false;
  11214. this.setValues( parameters );
  11215. }
  11216. copy( source ) {
  11217. super.copy( source );
  11218. this.referencePosition.copy( source.referencePosition );
  11219. this.nearDistance = source.nearDistance;
  11220. this.farDistance = source.farDistance;
  11221. this.skinning = source.skinning;
  11222. this.morphTargets = source.morphTargets;
  11223. this.map = source.map;
  11224. this.alphaMap = source.alphaMap;
  11225. this.displacementMap = source.displacementMap;
  11226. this.displacementScale = source.displacementScale;
  11227. this.displacementBias = source.displacementBias;
  11228. return this;
  11229. }
  11230. }
  11231. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  11232. var vsm_frag = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy ) / resolution ) );\n\tfor ( float i = -1.0; i < 1.0 ; i += SAMPLE_RATE) {\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( i, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, i ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean * HALF_SAMPLE_RATE;\n\tsquared_mean = squared_mean * HALF_SAMPLE_RATE;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";
  11233. var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  11234. function WebGLShadowMap( _renderer, _objects, maxTextureSize ) {
  11235. let _frustum = new Frustum();
  11236. const _shadowMapSize = new Vector2(),
  11237. _viewportSize = new Vector2(),
  11238. _viewport = new Vector4(),
  11239. _depthMaterials = [],
  11240. _distanceMaterials = [],
  11241. _materialCache = {};
  11242. const shadowSide = { 0: BackSide, 1: FrontSide, 2: DoubleSide };
  11243. const shadowMaterialVertical = new ShaderMaterial( {
  11244. defines: {
  11245. SAMPLE_RATE: 2.0 / 8.0,
  11246. HALF_SAMPLE_RATE: 1.0 / 8.0
  11247. },
  11248. uniforms: {
  11249. shadow_pass: { value: null },
  11250. resolution: { value: new Vector2() },
  11251. radius: { value: 4.0 }
  11252. },
  11253. vertexShader: vsm_vert,
  11254. fragmentShader: vsm_frag
  11255. } );
  11256. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  11257. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  11258. const fullScreenTri = new BufferGeometry();
  11259. fullScreenTri.setAttribute(
  11260. 'position',
  11261. new BufferAttribute(
  11262. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  11263. 3
  11264. )
  11265. );
  11266. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  11267. const scope = this;
  11268. this.enabled = false;
  11269. this.autoUpdate = true;
  11270. this.needsUpdate = false;
  11271. this.type = PCFShadowMap;
  11272. this.render = function ( lights, scene, camera ) {
  11273. if ( scope.enabled === false ) return;
  11274. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  11275. if ( lights.length === 0 ) return;
  11276. const currentRenderTarget = _renderer.getRenderTarget();
  11277. const activeCubeFace = _renderer.getActiveCubeFace();
  11278. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  11279. const _state = _renderer.state;
  11280. // Set GL state for depth map.
  11281. _state.setBlending( NoBlending );
  11282. _state.buffers.color.setClear( 1, 1, 1, 1 );
  11283. _state.buffers.depth.setTest( true );
  11284. _state.setScissorTest( false );
  11285. // render depth map
  11286. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  11287. const light = lights[ i ];
  11288. const shadow = light.shadow;
  11289. if ( shadow === undefined ) {
  11290. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  11291. continue;
  11292. }
  11293. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  11294. _shadowMapSize.copy( shadow.mapSize );
  11295. const shadowFrameExtents = shadow.getFrameExtents();
  11296. _shadowMapSize.multiply( shadowFrameExtents );
  11297. _viewportSize.copy( shadow.mapSize );
  11298. if ( _shadowMapSize.x > maxTextureSize || _shadowMapSize.y > maxTextureSize ) {
  11299. if ( _shadowMapSize.x > maxTextureSize ) {
  11300. _viewportSize.x = Math.floor( maxTextureSize / shadowFrameExtents.x );
  11301. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  11302. shadow.mapSize.x = _viewportSize.x;
  11303. }
  11304. if ( _shadowMapSize.y > maxTextureSize ) {
  11305. _viewportSize.y = Math.floor( maxTextureSize / shadowFrameExtents.y );
  11306. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  11307. shadow.mapSize.y = _viewportSize.y;
  11308. }
  11309. }
  11310. if ( shadow.map === null && ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {
  11311. const pars = { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat };
  11312. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  11313. shadow.map.texture.name = light.name + '.shadowMap';
  11314. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  11315. shadow.camera.updateProjectionMatrix();
  11316. }
  11317. if ( shadow.map === null ) {
  11318. const pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  11319. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  11320. shadow.map.texture.name = light.name + '.shadowMap';
  11321. shadow.camera.updateProjectionMatrix();
  11322. }
  11323. _renderer.setRenderTarget( shadow.map );
  11324. _renderer.clear();
  11325. const viewportCount = shadow.getViewportCount();
  11326. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  11327. const viewport = shadow.getViewport( vp );
  11328. _viewport.set(
  11329. _viewportSize.x * viewport.x,
  11330. _viewportSize.y * viewport.y,
  11331. _viewportSize.x * viewport.z,
  11332. _viewportSize.y * viewport.w
  11333. );
  11334. _state.viewport( _viewport );
  11335. shadow.updateMatrices( light, vp );
  11336. _frustum = shadow.getFrustum();
  11337. renderObject( scene, camera, shadow.camera, light, this.type );
  11338. }
  11339. // do blur pass for VSM
  11340. if ( ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {
  11341. VSMPass( shadow, camera );
  11342. }
  11343. shadow.needsUpdate = false;
  11344. }
  11345. scope.needsUpdate = false;
  11346. _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  11347. };
  11348. function VSMPass( shadow, camera ) {
  11349. const geometry = _objects.update( fullScreenMesh );
  11350. // vertical pass
  11351. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  11352. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  11353. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  11354. _renderer.setRenderTarget( shadow.mapPass );
  11355. _renderer.clear();
  11356. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  11357. // horizontal pass
  11358. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  11359. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  11360. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  11361. _renderer.setRenderTarget( shadow.map );
  11362. _renderer.clear();
  11363. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  11364. }
  11365. function getDepthMaterialVariant( useMorphing, useSkinning, useInstancing ) {
  11366. const index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
  11367. let material = _depthMaterials[ index ];
  11368. if ( material === undefined ) {
  11369. material = new MeshDepthMaterial( {
  11370. depthPacking: RGBADepthPacking,
  11371. morphTargets: useMorphing,
  11372. skinning: useSkinning
  11373. } );
  11374. _depthMaterials[ index ] = material;
  11375. }
  11376. return material;
  11377. }
  11378. function getDistanceMaterialVariant( useMorphing, useSkinning, useInstancing ) {
  11379. const index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
  11380. let material = _distanceMaterials[ index ];
  11381. if ( material === undefined ) {
  11382. material = new MeshDistanceMaterial( {
  11383. morphTargets: useMorphing,
  11384. skinning: useSkinning
  11385. } );
  11386. _distanceMaterials[ index ] = material;
  11387. }
  11388. return material;
  11389. }
  11390. function getDepthMaterial( object, geometry, material, light, shadowCameraNear, shadowCameraFar, type ) {
  11391. let result = null;
  11392. let getMaterialVariant = getDepthMaterialVariant;
  11393. let customMaterial = object.customDepthMaterial;
  11394. if ( light.isPointLight === true ) {
  11395. getMaterialVariant = getDistanceMaterialVariant;
  11396. customMaterial = object.customDistanceMaterial;
  11397. }
  11398. if ( customMaterial === undefined ) {
  11399. let useMorphing = false;
  11400. if ( material.morphTargets === true ) {
  11401. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  11402. }
  11403. let useSkinning = false;
  11404. if ( object.isSkinnedMesh === true ) {
  11405. if ( material.skinning === true ) {
  11406. useSkinning = true;
  11407. } else {
  11408. console.warn( 'THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object );
  11409. }
  11410. }
  11411. const useInstancing = object.isInstancedMesh === true;
  11412. result = getMaterialVariant( useMorphing, useSkinning, useInstancing );
  11413. } else {
  11414. result = customMaterial;
  11415. }
  11416. if ( _renderer.localClippingEnabled &&
  11417. material.clipShadows === true &&
  11418. material.clippingPlanes.length !== 0 ) {
  11419. // in this case we need a unique material instance reflecting the
  11420. // appropriate state
  11421. const keyA = result.uuid, keyB = material.uuid;
  11422. let materialsForVariant = _materialCache[ keyA ];
  11423. if ( materialsForVariant === undefined ) {
  11424. materialsForVariant = {};
  11425. _materialCache[ keyA ] = materialsForVariant;
  11426. }
  11427. let cachedMaterial = materialsForVariant[ keyB ];
  11428. if ( cachedMaterial === undefined ) {
  11429. cachedMaterial = result.clone();
  11430. materialsForVariant[ keyB ] = cachedMaterial;
  11431. }
  11432. result = cachedMaterial;
  11433. }
  11434. result.visible = material.visible;
  11435. result.wireframe = material.wireframe;
  11436. if ( type === VSMShadowMap ) {
  11437. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  11438. } else {
  11439. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  11440. }
  11441. result.clipShadows = material.clipShadows;
  11442. result.clippingPlanes = material.clippingPlanes;
  11443. result.clipIntersection = material.clipIntersection;
  11444. result.wireframeLinewidth = material.wireframeLinewidth;
  11445. result.linewidth = material.linewidth;
  11446. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  11447. result.referencePosition.setFromMatrixPosition( light.matrixWorld );
  11448. result.nearDistance = shadowCameraNear;
  11449. result.farDistance = shadowCameraFar;
  11450. }
  11451. return result;
  11452. }
  11453. function renderObject( object, camera, shadowCamera, light, type ) {
  11454. if ( object.visible === false ) return;
  11455. const visible = object.layers.test( camera.layers );
  11456. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  11457. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  11458. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  11459. const geometry = _objects.update( object );
  11460. const material = object.material;
  11461. if ( Array.isArray( material ) ) {
  11462. const groups = geometry.groups;
  11463. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  11464. const group = groups[ k ];
  11465. const groupMaterial = material[ group.materialIndex ];
  11466. if ( groupMaterial && groupMaterial.visible ) {
  11467. const depthMaterial = getDepthMaterial( object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type );
  11468. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  11469. }
  11470. }
  11471. } else if ( material.visible ) {
  11472. const depthMaterial = getDepthMaterial( object, geometry, material, light, shadowCamera.near, shadowCamera.far, type );
  11473. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  11474. }
  11475. }
  11476. }
  11477. const children = object.children;
  11478. for ( let i = 0, l = children.length; i < l; i ++ ) {
  11479. renderObject( children[ i ], camera, shadowCamera, light, type );
  11480. }
  11481. }
  11482. }
  11483. function WebGLState( gl, extensions, capabilities ) {
  11484. const isWebGL2 = capabilities.isWebGL2;
  11485. function ColorBuffer() {
  11486. let locked = false;
  11487. const color = new Vector4();
  11488. let currentColorMask = null;
  11489. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  11490. return {
  11491. setMask: function ( colorMask ) {
  11492. if ( currentColorMask !== colorMask && ! locked ) {
  11493. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  11494. currentColorMask = colorMask;
  11495. }
  11496. },
  11497. setLocked: function ( lock ) {
  11498. locked = lock;
  11499. },
  11500. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  11501. if ( premultipliedAlpha === true ) {
  11502. r *= a; g *= a; b *= a;
  11503. }
  11504. color.set( r, g, b, a );
  11505. if ( currentColorClear.equals( color ) === false ) {
  11506. gl.clearColor( r, g, b, a );
  11507. currentColorClear.copy( color );
  11508. }
  11509. },
  11510. reset: function () {
  11511. locked = false;
  11512. currentColorMask = null;
  11513. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  11514. }
  11515. };
  11516. }
  11517. function DepthBuffer() {
  11518. let locked = false;
  11519. let currentDepthMask = null;
  11520. let currentDepthFunc = null;
  11521. let currentDepthClear = null;
  11522. return {
  11523. setTest: function ( depthTest ) {
  11524. if ( depthTest ) {
  11525. enable( 2929 );
  11526. } else {
  11527. disable( 2929 );
  11528. }
  11529. },
  11530. setMask: function ( depthMask ) {
  11531. if ( currentDepthMask !== depthMask && ! locked ) {
  11532. gl.depthMask( depthMask );
  11533. currentDepthMask = depthMask;
  11534. }
  11535. },
  11536. setFunc: function ( depthFunc ) {
  11537. if ( currentDepthFunc !== depthFunc ) {
  11538. if ( depthFunc ) {
  11539. switch ( depthFunc ) {
  11540. case NeverDepth:
  11541. gl.depthFunc( 512 );
  11542. break;
  11543. case AlwaysDepth:
  11544. gl.depthFunc( 519 );
  11545. break;
  11546. case LessDepth:
  11547. gl.depthFunc( 513 );
  11548. break;
  11549. case LessEqualDepth:
  11550. gl.depthFunc( 515 );
  11551. break;
  11552. case EqualDepth:
  11553. gl.depthFunc( 514 );
  11554. break;
  11555. case GreaterEqualDepth:
  11556. gl.depthFunc( 518 );
  11557. break;
  11558. case GreaterDepth:
  11559. gl.depthFunc( 516 );
  11560. break;
  11561. case NotEqualDepth:
  11562. gl.depthFunc( 517 );
  11563. break;
  11564. default:
  11565. gl.depthFunc( 515 );
  11566. }
  11567. } else {
  11568. gl.depthFunc( 515 );
  11569. }
  11570. currentDepthFunc = depthFunc;
  11571. }
  11572. },
  11573. setLocked: function ( lock ) {
  11574. locked = lock;
  11575. },
  11576. setClear: function ( depth ) {
  11577. if ( currentDepthClear !== depth ) {
  11578. gl.clearDepth( depth );
  11579. currentDepthClear = depth;
  11580. }
  11581. },
  11582. reset: function () {
  11583. locked = false;
  11584. currentDepthMask = null;
  11585. currentDepthFunc = null;
  11586. currentDepthClear = null;
  11587. }
  11588. };
  11589. }
  11590. function StencilBuffer() {
  11591. let locked = false;
  11592. let currentStencilMask = null;
  11593. let currentStencilFunc = null;
  11594. let currentStencilRef = null;
  11595. let currentStencilFuncMask = null;
  11596. let currentStencilFail = null;
  11597. let currentStencilZFail = null;
  11598. let currentStencilZPass = null;
  11599. let currentStencilClear = null;
  11600. return {
  11601. setTest: function ( stencilTest ) {
  11602. if ( ! locked ) {
  11603. if ( stencilTest ) {
  11604. enable( 2960 );
  11605. } else {
  11606. disable( 2960 );
  11607. }
  11608. }
  11609. },
  11610. setMask: function ( stencilMask ) {
  11611. if ( currentStencilMask !== stencilMask && ! locked ) {
  11612. gl.stencilMask( stencilMask );
  11613. currentStencilMask = stencilMask;
  11614. }
  11615. },
  11616. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  11617. if ( currentStencilFunc !== stencilFunc ||
  11618. currentStencilRef !== stencilRef ||
  11619. currentStencilFuncMask !== stencilMask ) {
  11620. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  11621. currentStencilFunc = stencilFunc;
  11622. currentStencilRef = stencilRef;
  11623. currentStencilFuncMask = stencilMask;
  11624. }
  11625. },
  11626. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  11627. if ( currentStencilFail !== stencilFail ||
  11628. currentStencilZFail !== stencilZFail ||
  11629. currentStencilZPass !== stencilZPass ) {
  11630. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  11631. currentStencilFail = stencilFail;
  11632. currentStencilZFail = stencilZFail;
  11633. currentStencilZPass = stencilZPass;
  11634. }
  11635. },
  11636. setLocked: function ( lock ) {
  11637. locked = lock;
  11638. },
  11639. setClear: function ( stencil ) {
  11640. if ( currentStencilClear !== stencil ) {
  11641. gl.clearStencil( stencil );
  11642. currentStencilClear = stencil;
  11643. }
  11644. },
  11645. reset: function () {
  11646. locked = false;
  11647. currentStencilMask = null;
  11648. currentStencilFunc = null;
  11649. currentStencilRef = null;
  11650. currentStencilFuncMask = null;
  11651. currentStencilFail = null;
  11652. currentStencilZFail = null;
  11653. currentStencilZPass = null;
  11654. currentStencilClear = null;
  11655. }
  11656. };
  11657. }
  11658. //
  11659. const colorBuffer = new ColorBuffer();
  11660. const depthBuffer = new DepthBuffer();
  11661. const stencilBuffer = new StencilBuffer();
  11662. let enabledCapabilities = {};
  11663. let xrFramebuffer = null;
  11664. let currentBoundFramebuffers = {};
  11665. let currentProgram = null;
  11666. let currentBlendingEnabled = false;
  11667. let currentBlending = null;
  11668. let currentBlendEquation = null;
  11669. let currentBlendSrc = null;
  11670. let currentBlendDst = null;
  11671. let currentBlendEquationAlpha = null;
  11672. let currentBlendSrcAlpha = null;
  11673. let currentBlendDstAlpha = null;
  11674. let currentPremultipledAlpha = false;
  11675. let currentFlipSided = null;
  11676. let currentCullFace = null;
  11677. let currentLineWidth = null;
  11678. let currentPolygonOffsetFactor = null;
  11679. let currentPolygonOffsetUnits = null;
  11680. const maxTextures = gl.getParameter( 35661 );
  11681. let lineWidthAvailable = false;
  11682. let version = 0;
  11683. const glVersion = gl.getParameter( 7938 );
  11684. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  11685. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  11686. lineWidthAvailable = ( version >= 1.0 );
  11687. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  11688. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  11689. lineWidthAvailable = ( version >= 2.0 );
  11690. }
  11691. let currentTextureSlot = null;
  11692. let currentBoundTextures = {};
  11693. const currentScissor = new Vector4( 0, 0, gl.canvas.width, gl.canvas.height );
  11694. const currentViewport = new Vector4( 0, 0, gl.canvas.width, gl.canvas.height );
  11695. function createTexture( type, target, count ) {
  11696. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  11697. const texture = gl.createTexture();
  11698. gl.bindTexture( type, texture );
  11699. gl.texParameteri( type, 10241, 9728 );
  11700. gl.texParameteri( type, 10240, 9728 );
  11701. for ( let i = 0; i < count; i ++ ) {
  11702. gl.texImage2D( target + i, 0, 6408, 1, 1, 0, 6408, 5121, data );
  11703. }
  11704. return texture;
  11705. }
  11706. const emptyTextures = {};
  11707. emptyTextures[ 3553 ] = createTexture( 3553, 3553, 1 );
  11708. emptyTextures[ 34067 ] = createTexture( 34067, 34069, 6 );
  11709. // init
  11710. colorBuffer.setClear( 0, 0, 0, 1 );
  11711. depthBuffer.setClear( 1 );
  11712. stencilBuffer.setClear( 0 );
  11713. enable( 2929 );
  11714. depthBuffer.setFunc( LessEqualDepth );
  11715. setFlipSided( false );
  11716. setCullFace( CullFaceBack );
  11717. enable( 2884 );
  11718. setBlending( NoBlending );
  11719. //
  11720. function enable( id ) {
  11721. if ( enabledCapabilities[ id ] !== true ) {
  11722. gl.enable( id );
  11723. enabledCapabilities[ id ] = true;
  11724. }
  11725. }
  11726. function disable( id ) {
  11727. if ( enabledCapabilities[ id ] !== false ) {
  11728. gl.disable( id );
  11729. enabledCapabilities[ id ] = false;
  11730. }
  11731. }
  11732. function bindXRFramebuffer( framebuffer ) {
  11733. if ( framebuffer !== xrFramebuffer ) {
  11734. gl.bindFramebuffer( 36160, framebuffer );
  11735. xrFramebuffer = framebuffer;
  11736. }
  11737. }
  11738. function bindFramebuffer( target, framebuffer ) {
  11739. if ( target === 36009 ) target = 36160;
  11740. if ( framebuffer === null && xrFramebuffer !== null ) framebuffer = xrFramebuffer; // use active XR framebuffer if available
  11741. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  11742. gl.bindFramebuffer( target, framebuffer );
  11743. currentBoundFramebuffers[ target ] = framebuffer;
  11744. }
  11745. }
  11746. function useProgram( program ) {
  11747. if ( currentProgram !== program ) {
  11748. gl.useProgram( program );
  11749. currentProgram = program;
  11750. return true;
  11751. }
  11752. return false;
  11753. }
  11754. const equationToGL = {
  11755. [ AddEquation ]: 32774,
  11756. [ SubtractEquation ]: 32778,
  11757. [ ReverseSubtractEquation ]: 32779
  11758. };
  11759. if ( isWebGL2 ) {
  11760. equationToGL[ MinEquation ] = 32775;
  11761. equationToGL[ MaxEquation ] = 32776;
  11762. } else {
  11763. const extension = extensions.get( 'EXT_blend_minmax' );
  11764. if ( extension !== null ) {
  11765. equationToGL[ MinEquation ] = extension.MIN_EXT;
  11766. equationToGL[ MaxEquation ] = extension.MAX_EXT;
  11767. }
  11768. }
  11769. const factorToGL = {
  11770. [ ZeroFactor ]: 0,
  11771. [ OneFactor ]: 1,
  11772. [ SrcColorFactor ]: 768,
  11773. [ SrcAlphaFactor ]: 770,
  11774. [ SrcAlphaSaturateFactor ]: 776,
  11775. [ DstColorFactor ]: 774,
  11776. [ DstAlphaFactor ]: 772,
  11777. [ OneMinusSrcColorFactor ]: 769,
  11778. [ OneMinusSrcAlphaFactor ]: 771,
  11779. [ OneMinusDstColorFactor ]: 775,
  11780. [ OneMinusDstAlphaFactor ]: 773
  11781. };
  11782. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  11783. if ( blending === NoBlending ) {
  11784. if ( currentBlendingEnabled === true ) {
  11785. disable( 3042 );
  11786. currentBlendingEnabled = false;
  11787. }
  11788. return;
  11789. }
  11790. if ( currentBlendingEnabled === false ) {
  11791. enable( 3042 );
  11792. currentBlendingEnabled = true;
  11793. }
  11794. if ( blending !== CustomBlending ) {
  11795. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  11796. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  11797. gl.blendEquation( 32774 );
  11798. currentBlendEquation = AddEquation;
  11799. currentBlendEquationAlpha = AddEquation;
  11800. }
  11801. if ( premultipliedAlpha ) {
  11802. switch ( blending ) {
  11803. case NormalBlending:
  11804. gl.blendFuncSeparate( 1, 771, 1, 771 );
  11805. break;
  11806. case AdditiveBlending:
  11807. gl.blendFunc( 1, 1 );
  11808. break;
  11809. case SubtractiveBlending:
  11810. gl.blendFuncSeparate( 0, 0, 769, 771 );
  11811. break;
  11812. case MultiplyBlending:
  11813. gl.blendFuncSeparate( 0, 768, 0, 770 );
  11814. break;
  11815. default:
  11816. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  11817. break;
  11818. }
  11819. } else {
  11820. switch ( blending ) {
  11821. case NormalBlending:
  11822. gl.blendFuncSeparate( 770, 771, 1, 771 );
  11823. break;
  11824. case AdditiveBlending:
  11825. gl.blendFunc( 770, 1 );
  11826. break;
  11827. case SubtractiveBlending:
  11828. gl.blendFunc( 0, 769 );
  11829. break;
  11830. case MultiplyBlending:
  11831. gl.blendFunc( 0, 768 );
  11832. break;
  11833. default:
  11834. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  11835. break;
  11836. }
  11837. }
  11838. currentBlendSrc = null;
  11839. currentBlendDst = null;
  11840. currentBlendSrcAlpha = null;
  11841. currentBlendDstAlpha = null;
  11842. currentBlending = blending;
  11843. currentPremultipledAlpha = premultipliedAlpha;
  11844. }
  11845. return;
  11846. }
  11847. // custom blending
  11848. blendEquationAlpha = blendEquationAlpha || blendEquation;
  11849. blendSrcAlpha = blendSrcAlpha || blendSrc;
  11850. blendDstAlpha = blendDstAlpha || blendDst;
  11851. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  11852. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  11853. currentBlendEquation = blendEquation;
  11854. currentBlendEquationAlpha = blendEquationAlpha;
  11855. }
  11856. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  11857. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  11858. currentBlendSrc = blendSrc;
  11859. currentBlendDst = blendDst;
  11860. currentBlendSrcAlpha = blendSrcAlpha;
  11861. currentBlendDstAlpha = blendDstAlpha;
  11862. }
  11863. currentBlending = blending;
  11864. currentPremultipledAlpha = null;
  11865. }
  11866. function setMaterial( material, frontFaceCW ) {
  11867. material.side === DoubleSide
  11868. ? disable( 2884 )
  11869. : enable( 2884 );
  11870. let flipSided = ( material.side === BackSide );
  11871. if ( frontFaceCW ) flipSided = ! flipSided;
  11872. setFlipSided( flipSided );
  11873. ( material.blending === NormalBlending && material.transparent === false )
  11874. ? setBlending( NoBlending )
  11875. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  11876. depthBuffer.setFunc( material.depthFunc );
  11877. depthBuffer.setTest( material.depthTest );
  11878. depthBuffer.setMask( material.depthWrite );
  11879. colorBuffer.setMask( material.colorWrite );
  11880. const stencilWrite = material.stencilWrite;
  11881. stencilBuffer.setTest( stencilWrite );
  11882. if ( stencilWrite ) {
  11883. stencilBuffer.setMask( material.stencilWriteMask );
  11884. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  11885. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  11886. }
  11887. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11888. material.alphaToCoverage === true
  11889. ? enable( 32926 )
  11890. : disable( 32926 );
  11891. }
  11892. //
  11893. function setFlipSided( flipSided ) {
  11894. if ( currentFlipSided !== flipSided ) {
  11895. if ( flipSided ) {
  11896. gl.frontFace( 2304 );
  11897. } else {
  11898. gl.frontFace( 2305 );
  11899. }
  11900. currentFlipSided = flipSided;
  11901. }
  11902. }
  11903. function setCullFace( cullFace ) {
  11904. if ( cullFace !== CullFaceNone ) {
  11905. enable( 2884 );
  11906. if ( cullFace !== currentCullFace ) {
  11907. if ( cullFace === CullFaceBack ) {
  11908. gl.cullFace( 1029 );
  11909. } else if ( cullFace === CullFaceFront ) {
  11910. gl.cullFace( 1028 );
  11911. } else {
  11912. gl.cullFace( 1032 );
  11913. }
  11914. }
  11915. } else {
  11916. disable( 2884 );
  11917. }
  11918. currentCullFace = cullFace;
  11919. }
  11920. function setLineWidth( width ) {
  11921. if ( width !== currentLineWidth ) {
  11922. if ( lineWidthAvailable ) gl.lineWidth( width );
  11923. currentLineWidth = width;
  11924. }
  11925. }
  11926. function setPolygonOffset( polygonOffset, factor, units ) {
  11927. if ( polygonOffset ) {
  11928. enable( 32823 );
  11929. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  11930. gl.polygonOffset( factor, units );
  11931. currentPolygonOffsetFactor = factor;
  11932. currentPolygonOffsetUnits = units;
  11933. }
  11934. } else {
  11935. disable( 32823 );
  11936. }
  11937. }
  11938. function setScissorTest( scissorTest ) {
  11939. if ( scissorTest ) {
  11940. enable( 3089 );
  11941. } else {
  11942. disable( 3089 );
  11943. }
  11944. }
  11945. // texture
  11946. function activeTexture( webglSlot ) {
  11947. if ( webglSlot === undefined ) webglSlot = 33984 + maxTextures - 1;
  11948. if ( currentTextureSlot !== webglSlot ) {
  11949. gl.activeTexture( webglSlot );
  11950. currentTextureSlot = webglSlot;
  11951. }
  11952. }
  11953. function bindTexture( webglType, webglTexture ) {
  11954. if ( currentTextureSlot === null ) {
  11955. activeTexture();
  11956. }
  11957. let boundTexture = currentBoundTextures[ currentTextureSlot ];
  11958. if ( boundTexture === undefined ) {
  11959. boundTexture = { type: undefined, texture: undefined };
  11960. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  11961. }
  11962. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  11963. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  11964. boundTexture.type = webglType;
  11965. boundTexture.texture = webglTexture;
  11966. }
  11967. }
  11968. function unbindTexture() {
  11969. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  11970. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  11971. gl.bindTexture( boundTexture.type, null );
  11972. boundTexture.type = undefined;
  11973. boundTexture.texture = undefined;
  11974. }
  11975. }
  11976. function compressedTexImage2D() {
  11977. try {
  11978. gl.compressedTexImage2D.apply( gl, arguments );
  11979. } catch ( error ) {
  11980. console.error( 'THREE.WebGLState:', error );
  11981. }
  11982. }
  11983. function texImage2D() {
  11984. try {
  11985. gl.texImage2D.apply( gl, arguments );
  11986. } catch ( error ) {
  11987. console.error( 'THREE.WebGLState:', error );
  11988. }
  11989. }
  11990. function texImage3D() {
  11991. try {
  11992. gl.texImage3D.apply( gl, arguments );
  11993. } catch ( error ) {
  11994. console.error( 'THREE.WebGLState:', error );
  11995. }
  11996. }
  11997. //
  11998. function scissor( scissor ) {
  11999. if ( currentScissor.equals( scissor ) === false ) {
  12000. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  12001. currentScissor.copy( scissor );
  12002. }
  12003. }
  12004. function viewport( viewport ) {
  12005. if ( currentViewport.equals( viewport ) === false ) {
  12006. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  12007. currentViewport.copy( viewport );
  12008. }
  12009. }
  12010. //
  12011. function reset() {
  12012. // reset state
  12013. gl.disable( 3042 );
  12014. gl.disable( 2884 );
  12015. gl.disable( 2929 );
  12016. gl.disable( 32823 );
  12017. gl.disable( 3089 );
  12018. gl.disable( 2960 );
  12019. gl.disable( 32926 );
  12020. gl.blendEquation( 32774 );
  12021. gl.blendFunc( 1, 0 );
  12022. gl.blendFuncSeparate( 1, 0, 1, 0 );
  12023. gl.colorMask( true, true, true, true );
  12024. gl.clearColor( 0, 0, 0, 0 );
  12025. gl.depthMask( true );
  12026. gl.depthFunc( 513 );
  12027. gl.clearDepth( 1 );
  12028. gl.stencilMask( 0xffffffff );
  12029. gl.stencilFunc( 519, 0, 0xffffffff );
  12030. gl.stencilOp( 7680, 7680, 7680 );
  12031. gl.clearStencil( 0 );
  12032. gl.cullFace( 1029 );
  12033. gl.frontFace( 2305 );
  12034. gl.polygonOffset( 0, 0 );
  12035. gl.activeTexture( 33984 );
  12036. if ( isWebGL2 === true ) {
  12037. gl.bindFramebuffer( 36009, null ); // Equivalent to 36160
  12038. gl.bindFramebuffer( 36008, null );
  12039. } else {
  12040. gl.bindFramebuffer( 36160, null );
  12041. }
  12042. gl.useProgram( null );
  12043. gl.lineWidth( 1 );
  12044. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  12045. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  12046. // reset internals
  12047. enabledCapabilities = {};
  12048. currentTextureSlot = null;
  12049. currentBoundTextures = {};
  12050. xrFramebuffer = null;
  12051. currentBoundFramebuffers = {};
  12052. currentProgram = null;
  12053. currentBlendingEnabled = false;
  12054. currentBlending = null;
  12055. currentBlendEquation = null;
  12056. currentBlendSrc = null;
  12057. currentBlendDst = null;
  12058. currentBlendEquationAlpha = null;
  12059. currentBlendSrcAlpha = null;
  12060. currentBlendDstAlpha = null;
  12061. currentPremultipledAlpha = false;
  12062. currentFlipSided = null;
  12063. currentCullFace = null;
  12064. currentLineWidth = null;
  12065. currentPolygonOffsetFactor = null;
  12066. currentPolygonOffsetUnits = null;
  12067. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  12068. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  12069. colorBuffer.reset();
  12070. depthBuffer.reset();
  12071. stencilBuffer.reset();
  12072. }
  12073. return {
  12074. buffers: {
  12075. color: colorBuffer,
  12076. depth: depthBuffer,
  12077. stencil: stencilBuffer
  12078. },
  12079. enable: enable,
  12080. disable: disable,
  12081. bindFramebuffer: bindFramebuffer,
  12082. bindXRFramebuffer: bindXRFramebuffer,
  12083. useProgram: useProgram,
  12084. setBlending: setBlending,
  12085. setMaterial: setMaterial,
  12086. setFlipSided: setFlipSided,
  12087. setCullFace: setCullFace,
  12088. setLineWidth: setLineWidth,
  12089. setPolygonOffset: setPolygonOffset,
  12090. setScissorTest: setScissorTest,
  12091. activeTexture: activeTexture,
  12092. bindTexture: bindTexture,
  12093. unbindTexture: unbindTexture,
  12094. compressedTexImage2D: compressedTexImage2D,
  12095. texImage2D: texImage2D,
  12096. texImage3D: texImage3D,
  12097. scissor: scissor,
  12098. viewport: viewport,
  12099. reset: reset
  12100. };
  12101. }
  12102. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  12103. const isWebGL2 = capabilities.isWebGL2;
  12104. const maxTextures = capabilities.maxTextures;
  12105. const maxCubemapSize = capabilities.maxCubemapSize;
  12106. const maxTextureSize = capabilities.maxTextureSize;
  12107. const maxSamples = capabilities.maxSamples;
  12108. const _videoTextures = new WeakMap();
  12109. let _canvas;
  12110. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  12111. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  12112. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  12113. let useOffscreenCanvas = false;
  12114. try {
  12115. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  12116. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  12117. } catch ( err ) {
  12118. // Ignore any errors
  12119. }
  12120. function createCanvas( width, height ) {
  12121. // Use OffscreenCanvas when available. Specially needed in web workers
  12122. return useOffscreenCanvas ?
  12123. new OffscreenCanvas( width, height ) :
  12124. document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  12125. }
  12126. function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {
  12127. let scale = 1;
  12128. // handle case if texture exceeds max size
  12129. if ( image.width > maxSize || image.height > maxSize ) {
  12130. scale = maxSize / Math.max( image.width, image.height );
  12131. }
  12132. // only perform resize if necessary
  12133. if ( scale < 1 || needsPowerOfTwo === true ) {
  12134. // only perform resize for certain image types
  12135. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  12136. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  12137. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  12138. const floor = needsPowerOfTwo ? MathUtils.floorPowerOfTwo : Math.floor;
  12139. const width = floor( scale * image.width );
  12140. const height = floor( scale * image.height );
  12141. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  12142. // cube textures can't reuse the same canvas
  12143. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  12144. canvas.width = width;
  12145. canvas.height = height;
  12146. const context = canvas.getContext( '2d' );
  12147. context.drawImage( image, 0, 0, width, height );
  12148. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );
  12149. return canvas;
  12150. } else {
  12151. if ( 'data' in image ) {
  12152. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  12153. }
  12154. return image;
  12155. }
  12156. }
  12157. return image;
  12158. }
  12159. function isPowerOfTwo( image ) {
  12160. return MathUtils.isPowerOfTwo( image.width ) && MathUtils.isPowerOfTwo( image.height );
  12161. }
  12162. function textureNeedsPowerOfTwo( texture ) {
  12163. if ( isWebGL2 ) return false;
  12164. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  12165. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  12166. }
  12167. function textureNeedsGenerateMipmaps( texture, supportsMips ) {
  12168. return texture.generateMipmaps && supportsMips &&
  12169. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  12170. }
  12171. function generateMipmap( target, texture, width, height ) {
  12172. _gl.generateMipmap( target );
  12173. const textureProperties = properties.get( texture );
  12174. textureProperties.__maxMipLevel = Math.log2( Math.max( width, height ) );
  12175. }
  12176. function getInternalFormat( internalFormatName, glFormat, glType ) {
  12177. if ( isWebGL2 === false ) return glFormat;
  12178. if ( internalFormatName !== null ) {
  12179. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  12180. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  12181. }
  12182. let internalFormat = glFormat;
  12183. if ( glFormat === 6403 ) {
  12184. if ( glType === 5126 ) internalFormat = 33326;
  12185. if ( glType === 5131 ) internalFormat = 33325;
  12186. if ( glType === 5121 ) internalFormat = 33321;
  12187. }
  12188. if ( glFormat === 6407 ) {
  12189. if ( glType === 5126 ) internalFormat = 34837;
  12190. if ( glType === 5131 ) internalFormat = 34843;
  12191. if ( glType === 5121 ) internalFormat = 32849;
  12192. }
  12193. if ( glFormat === 6408 ) {
  12194. if ( glType === 5126 ) internalFormat = 34836;
  12195. if ( glType === 5131 ) internalFormat = 34842;
  12196. if ( glType === 5121 ) internalFormat = 32856;
  12197. }
  12198. if ( internalFormat === 33325 || internalFormat === 33326 ||
  12199. internalFormat === 34842 || internalFormat === 34836 ) {
  12200. extensions.get( 'EXT_color_buffer_float' );
  12201. }
  12202. return internalFormat;
  12203. }
  12204. // Fallback filters for non-power-of-2 textures
  12205. function filterFallback( f ) {
  12206. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  12207. return 9728;
  12208. }
  12209. return 9729;
  12210. }
  12211. //
  12212. function onTextureDispose( event ) {
  12213. const texture = event.target;
  12214. texture.removeEventListener( 'dispose', onTextureDispose );
  12215. deallocateTexture( texture );
  12216. if ( texture.isVideoTexture ) {
  12217. _videoTextures.delete( texture );
  12218. }
  12219. info.memory.textures --;
  12220. }
  12221. function onRenderTargetDispose( event ) {
  12222. const renderTarget = event.target;
  12223. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  12224. deallocateRenderTarget( renderTarget );
  12225. info.memory.textures --;
  12226. }
  12227. //
  12228. function deallocateTexture( texture ) {
  12229. const textureProperties = properties.get( texture );
  12230. if ( textureProperties.__webglInit === undefined ) return;
  12231. _gl.deleteTexture( textureProperties.__webglTexture );
  12232. properties.remove( texture );
  12233. }
  12234. function deallocateRenderTarget( renderTarget ) {
  12235. const texture = renderTarget.texture;
  12236. const renderTargetProperties = properties.get( renderTarget );
  12237. const textureProperties = properties.get( texture );
  12238. if ( ! renderTarget ) return;
  12239. if ( textureProperties.__webglTexture !== undefined ) {
  12240. _gl.deleteTexture( textureProperties.__webglTexture );
  12241. }
  12242. if ( renderTarget.depthTexture ) {
  12243. renderTarget.depthTexture.dispose();
  12244. }
  12245. if ( renderTarget.isWebGLCubeRenderTarget ) {
  12246. for ( let i = 0; i < 6; i ++ ) {
  12247. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  12248. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  12249. }
  12250. } else {
  12251. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  12252. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  12253. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  12254. if ( renderTargetProperties.__webglColorRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer );
  12255. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  12256. }
  12257. properties.remove( texture );
  12258. properties.remove( renderTarget );
  12259. }
  12260. //
  12261. let textureUnits = 0;
  12262. function resetTextureUnits() {
  12263. textureUnits = 0;
  12264. }
  12265. function allocateTextureUnit() {
  12266. const textureUnit = textureUnits;
  12267. if ( textureUnit >= maxTextures ) {
  12268. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures );
  12269. }
  12270. textureUnits += 1;
  12271. return textureUnit;
  12272. }
  12273. //
  12274. function setTexture2D( texture, slot ) {
  12275. const textureProperties = properties.get( texture );
  12276. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  12277. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  12278. const image = texture.image;
  12279. if ( image === undefined ) {
  12280. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined' );
  12281. } else if ( image.complete === false ) {
  12282. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  12283. } else {
  12284. uploadTexture( textureProperties, texture, slot );
  12285. return;
  12286. }
  12287. }
  12288. state.activeTexture( 33984 + slot );
  12289. state.bindTexture( 3553, textureProperties.__webglTexture );
  12290. }
  12291. function setTexture2DArray( texture, slot ) {
  12292. const textureProperties = properties.get( texture );
  12293. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  12294. uploadTexture( textureProperties, texture, slot );
  12295. return;
  12296. }
  12297. state.activeTexture( 33984 + slot );
  12298. state.bindTexture( 35866, textureProperties.__webglTexture );
  12299. }
  12300. function setTexture3D( texture, slot ) {
  12301. const textureProperties = properties.get( texture );
  12302. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  12303. uploadTexture( textureProperties, texture, slot );
  12304. return;
  12305. }
  12306. state.activeTexture( 33984 + slot );
  12307. state.bindTexture( 32879, textureProperties.__webglTexture );
  12308. }
  12309. function setTextureCube( texture, slot ) {
  12310. const textureProperties = properties.get( texture );
  12311. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  12312. uploadCubeTexture( textureProperties, texture, slot );
  12313. return;
  12314. }
  12315. state.activeTexture( 33984 + slot );
  12316. state.bindTexture( 34067, textureProperties.__webglTexture );
  12317. }
  12318. const wrappingToGL = {
  12319. [ RepeatWrapping ]: 10497,
  12320. [ ClampToEdgeWrapping ]: 33071,
  12321. [ MirroredRepeatWrapping ]: 33648
  12322. };
  12323. const filterToGL = {
  12324. [ NearestFilter ]: 9728,
  12325. [ NearestMipmapNearestFilter ]: 9984,
  12326. [ NearestMipmapLinearFilter ]: 9986,
  12327. [ LinearFilter ]: 9729,
  12328. [ LinearMipmapNearestFilter ]: 9985,
  12329. [ LinearMipmapLinearFilter ]: 9987
  12330. };
  12331. function setTextureParameters( textureType, texture, supportsMips ) {
  12332. if ( supportsMips ) {
  12333. _gl.texParameteri( textureType, 10242, wrappingToGL[ texture.wrapS ] );
  12334. _gl.texParameteri( textureType, 10243, wrappingToGL[ texture.wrapT ] );
  12335. if ( textureType === 32879 || textureType === 35866 ) {
  12336. _gl.texParameteri( textureType, 32882, wrappingToGL[ texture.wrapR ] );
  12337. }
  12338. _gl.texParameteri( textureType, 10240, filterToGL[ texture.magFilter ] );
  12339. _gl.texParameteri( textureType, 10241, filterToGL[ texture.minFilter ] );
  12340. } else {
  12341. _gl.texParameteri( textureType, 10242, 33071 );
  12342. _gl.texParameteri( textureType, 10243, 33071 );
  12343. if ( textureType === 32879 || textureType === 35866 ) {
  12344. _gl.texParameteri( textureType, 32882, 33071 );
  12345. }
  12346. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  12347. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
  12348. }
  12349. _gl.texParameteri( textureType, 10240, filterFallback( texture.magFilter ) );
  12350. _gl.texParameteri( textureType, 10241, filterFallback( texture.minFilter ) );
  12351. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  12352. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
  12353. }
  12354. }
  12355. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  12356. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  12357. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  12358. if ( isWebGL2 === false && ( texture.type === HalfFloatType && extensions.has( 'OES_texture_half_float_linear' ) === false ) ) return; // verify extension for WebGL 1 only
  12359. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  12360. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  12361. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  12362. }
  12363. }
  12364. }
  12365. function initTexture( textureProperties, texture ) {
  12366. if ( textureProperties.__webglInit === undefined ) {
  12367. textureProperties.__webglInit = true;
  12368. texture.addEventListener( 'dispose', onTextureDispose );
  12369. textureProperties.__webglTexture = _gl.createTexture();
  12370. info.memory.textures ++;
  12371. }
  12372. }
  12373. function uploadTexture( textureProperties, texture, slot ) {
  12374. let textureType = 3553;
  12375. if ( texture.isDataTexture2DArray ) textureType = 35866;
  12376. if ( texture.isDataTexture3D ) textureType = 32879;
  12377. initTexture( textureProperties, texture );
  12378. state.activeTexture( 33984 + slot );
  12379. state.bindTexture( textureType, textureProperties.__webglTexture );
  12380. _gl.pixelStorei( 37440, texture.flipY );
  12381. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  12382. _gl.pixelStorei( 3317, texture.unpackAlignment );
  12383. _gl.pixelStorei( 37443, 0 );
  12384. const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( texture.image ) === false;
  12385. const image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );
  12386. const supportsMips = isPowerOfTwo( image ) || isWebGL2,
  12387. glFormat = utils.convert( texture.format );
  12388. let glType = utils.convert( texture.type ),
  12389. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  12390. setTextureParameters( textureType, texture, supportsMips );
  12391. let mipmap;
  12392. const mipmaps = texture.mipmaps;
  12393. if ( texture.isDepthTexture ) {
  12394. // populate depth texture with dummy data
  12395. glInternalFormat = 6402;
  12396. if ( isWebGL2 ) {
  12397. if ( texture.type === FloatType ) {
  12398. glInternalFormat = 36012;
  12399. } else if ( texture.type === UnsignedIntType ) {
  12400. glInternalFormat = 33190;
  12401. } else if ( texture.type === UnsignedInt248Type ) {
  12402. glInternalFormat = 35056;
  12403. } else {
  12404. glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D
  12405. }
  12406. } else {
  12407. if ( texture.type === FloatType ) {
  12408. console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' );
  12409. }
  12410. }
  12411. // validation checks for WebGL 1
  12412. if ( texture.format === DepthFormat && glInternalFormat === 6402 ) {
  12413. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  12414. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  12415. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  12416. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  12417. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  12418. texture.type = UnsignedShortType;
  12419. glType = utils.convert( texture.type );
  12420. }
  12421. }
  12422. if ( texture.format === DepthStencilFormat && glInternalFormat === 6402 ) {
  12423. // Depth stencil textures need the DEPTH_STENCIL internal format
  12424. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  12425. glInternalFormat = 34041;
  12426. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  12427. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  12428. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  12429. if ( texture.type !== UnsignedInt248Type ) {
  12430. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  12431. texture.type = UnsignedInt248Type;
  12432. glType = utils.convert( texture.type );
  12433. }
  12434. }
  12435. //
  12436. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  12437. } else if ( texture.isDataTexture ) {
  12438. // use manually created mipmaps if available
  12439. // if there are no manual mipmaps
  12440. // set 0 level mipmap and then use GL to generate other mipmap levels
  12441. if ( mipmaps.length > 0 && supportsMips ) {
  12442. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  12443. mipmap = mipmaps[ i ];
  12444. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  12445. }
  12446. texture.generateMipmaps = false;
  12447. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12448. } else {
  12449. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  12450. textureProperties.__maxMipLevel = 0;
  12451. }
  12452. } else if ( texture.isCompressedTexture ) {
  12453. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  12454. mipmap = mipmaps[ i ];
  12455. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  12456. if ( glFormat !== null ) {
  12457. state.compressedTexImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  12458. } else {
  12459. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  12460. }
  12461. } else {
  12462. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  12463. }
  12464. }
  12465. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12466. } else if ( texture.isDataTexture2DArray ) {
  12467. state.texImage3D( 35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  12468. textureProperties.__maxMipLevel = 0;
  12469. } else if ( texture.isDataTexture3D ) {
  12470. state.texImage3D( 32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  12471. textureProperties.__maxMipLevel = 0;
  12472. } else {
  12473. // regular Texture (image, video, canvas)
  12474. // use manually created mipmaps if available
  12475. // if there are no manual mipmaps
  12476. // set 0 level mipmap and then use GL to generate other mipmap levels
  12477. if ( mipmaps.length > 0 && supportsMips ) {
  12478. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  12479. mipmap = mipmaps[ i ];
  12480. state.texImage2D( 3553, i, glInternalFormat, glFormat, glType, mipmap );
  12481. }
  12482. texture.generateMipmaps = false;
  12483. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12484. } else {
  12485. state.texImage2D( 3553, 0, glInternalFormat, glFormat, glType, image );
  12486. textureProperties.__maxMipLevel = 0;
  12487. }
  12488. }
  12489. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  12490. generateMipmap( textureType, texture, image.width, image.height );
  12491. }
  12492. textureProperties.__version = texture.version;
  12493. if ( texture.onUpdate ) texture.onUpdate( texture );
  12494. }
  12495. function uploadCubeTexture( textureProperties, texture, slot ) {
  12496. if ( texture.image.length !== 6 ) return;
  12497. initTexture( textureProperties, texture );
  12498. state.activeTexture( 33984 + slot );
  12499. state.bindTexture( 34067, textureProperties.__webglTexture );
  12500. _gl.pixelStorei( 37440, texture.flipY );
  12501. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  12502. _gl.pixelStorei( 3317, texture.unpackAlignment );
  12503. _gl.pixelStorei( 37443, 0 );
  12504. const isCompressed = ( texture && ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture ) );
  12505. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  12506. const cubeImage = [];
  12507. for ( let i = 0; i < 6; i ++ ) {
  12508. if ( ! isCompressed && ! isDataTexture ) {
  12509. cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize );
  12510. } else {
  12511. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  12512. }
  12513. }
  12514. const image = cubeImage[ 0 ],
  12515. supportsMips = isPowerOfTwo( image ) || isWebGL2,
  12516. glFormat = utils.convert( texture.format ),
  12517. glType = utils.convert( texture.type ),
  12518. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  12519. setTextureParameters( 34067, texture, supportsMips );
  12520. let mipmaps;
  12521. if ( isCompressed ) {
  12522. for ( let i = 0; i < 6; i ++ ) {
  12523. mipmaps = cubeImage[ i ].mipmaps;
  12524. for ( let j = 0; j < mipmaps.length; j ++ ) {
  12525. const mipmap = mipmaps[ j ];
  12526. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  12527. if ( glFormat !== null ) {
  12528. state.compressedTexImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  12529. } else {
  12530. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  12531. }
  12532. } else {
  12533. state.texImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  12534. }
  12535. }
  12536. }
  12537. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12538. } else {
  12539. mipmaps = texture.mipmaps;
  12540. for ( let i = 0; i < 6; i ++ ) {
  12541. if ( isDataTexture ) {
  12542. state.texImage2D( 34069 + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  12543. for ( let j = 0; j < mipmaps.length; j ++ ) {
  12544. const mipmap = mipmaps[ j ];
  12545. const mipmapImage = mipmap.image[ i ].image;
  12546. state.texImage2D( 34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  12547. }
  12548. } else {
  12549. state.texImage2D( 34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  12550. for ( let j = 0; j < mipmaps.length; j ++ ) {
  12551. const mipmap = mipmaps[ j ];
  12552. state.texImage2D( 34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  12553. }
  12554. }
  12555. }
  12556. textureProperties.__maxMipLevel = mipmaps.length;
  12557. }
  12558. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  12559. // We assume images for cube map have the same size.
  12560. generateMipmap( 34067, texture, image.width, image.height );
  12561. }
  12562. textureProperties.__version = texture.version;
  12563. if ( texture.onUpdate ) texture.onUpdate( texture );
  12564. }
  12565. // Render targets
  12566. // Setup storage for target texture and bind it to correct framebuffer
  12567. function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {
  12568. const texture = renderTarget.texture;
  12569. const glFormat = utils.convert( texture.format );
  12570. const glType = utils.convert( texture.type );
  12571. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  12572. if ( textureTarget === 32879 || textureTarget === 35866 ) {
  12573. state.texImage3D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null );
  12574. } else {
  12575. state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  12576. }
  12577. state.bindFramebuffer( 36160, framebuffer );
  12578. _gl.framebufferTexture2D( 36160, attachment, textureTarget, properties.get( texture ).__webglTexture, 0 );
  12579. state.bindFramebuffer( 36160, null );
  12580. }
  12581. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  12582. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  12583. _gl.bindRenderbuffer( 36161, renderbuffer );
  12584. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  12585. let glInternalFormat = 33189;
  12586. if ( isMultisample ) {
  12587. const depthTexture = renderTarget.depthTexture;
  12588. if ( depthTexture && depthTexture.isDepthTexture ) {
  12589. if ( depthTexture.type === FloatType ) {
  12590. glInternalFormat = 36012;
  12591. } else if ( depthTexture.type === UnsignedIntType ) {
  12592. glInternalFormat = 33190;
  12593. }
  12594. }
  12595. const samples = getRenderTargetSamples( renderTarget );
  12596. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  12597. } else {
  12598. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  12599. }
  12600. _gl.framebufferRenderbuffer( 36160, 36096, 36161, renderbuffer );
  12601. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  12602. if ( isMultisample ) {
  12603. const samples = getRenderTargetSamples( renderTarget );
  12604. _gl.renderbufferStorageMultisample( 36161, samples, 35056, renderTarget.width, renderTarget.height );
  12605. } else {
  12606. _gl.renderbufferStorage( 36161, 34041, renderTarget.width, renderTarget.height );
  12607. }
  12608. _gl.framebufferRenderbuffer( 36160, 33306, 36161, renderbuffer );
  12609. } else {
  12610. const texture = renderTarget.texture;
  12611. const glFormat = utils.convert( texture.format );
  12612. const glType = utils.convert( texture.type );
  12613. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  12614. if ( isMultisample ) {
  12615. const samples = getRenderTargetSamples( renderTarget );
  12616. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  12617. } else {
  12618. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  12619. }
  12620. }
  12621. _gl.bindRenderbuffer( 36161, null );
  12622. }
  12623. // Setup resources for a Depth Texture for a FBO (needs an extension)
  12624. function setupDepthTexture( framebuffer, renderTarget ) {
  12625. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  12626. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  12627. state.bindFramebuffer( 36160, framebuffer );
  12628. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  12629. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  12630. }
  12631. // upload an empty depth texture with framebuffer size
  12632. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  12633. renderTarget.depthTexture.image.width !== renderTarget.width ||
  12634. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  12635. renderTarget.depthTexture.image.width = renderTarget.width;
  12636. renderTarget.depthTexture.image.height = renderTarget.height;
  12637. renderTarget.depthTexture.needsUpdate = true;
  12638. }
  12639. setTexture2D( renderTarget.depthTexture, 0 );
  12640. const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  12641. if ( renderTarget.depthTexture.format === DepthFormat ) {
  12642. _gl.framebufferTexture2D( 36160, 36096, 3553, webglDepthTexture, 0 );
  12643. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  12644. _gl.framebufferTexture2D( 36160, 33306, 3553, webglDepthTexture, 0 );
  12645. } else {
  12646. throw new Error( 'Unknown depthTexture format' );
  12647. }
  12648. }
  12649. // Setup GL resources for a non-texture depth buffer
  12650. function setupDepthRenderbuffer( renderTarget ) {
  12651. const renderTargetProperties = properties.get( renderTarget );
  12652. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  12653. if ( renderTarget.depthTexture ) {
  12654. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  12655. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  12656. } else {
  12657. if ( isCube ) {
  12658. renderTargetProperties.__webglDepthbuffer = [];
  12659. for ( let i = 0; i < 6; i ++ ) {
  12660. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer[ i ] );
  12661. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  12662. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  12663. }
  12664. } else {
  12665. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  12666. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  12667. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  12668. }
  12669. }
  12670. state.bindFramebuffer( 36160, null );
  12671. }
  12672. // Set up GL resources for the render target
  12673. function setupRenderTarget( renderTarget ) {
  12674. const texture = renderTarget.texture;
  12675. const renderTargetProperties = properties.get( renderTarget );
  12676. const textureProperties = properties.get( texture );
  12677. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  12678. textureProperties.__webglTexture = _gl.createTexture();
  12679. info.memory.textures ++;
  12680. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  12681. const isMultisample = ( renderTarget.isWebGLMultisampleRenderTarget === true );
  12682. const isRenderTarget3D = texture.isDataTexture3D || texture.isDataTexture2DArray;
  12683. const supportsMips = isPowerOfTwo( renderTarget ) || isWebGL2;
  12684. // Handles WebGL2 RGBFormat fallback - #18858
  12685. if ( isWebGL2 && texture.format === RGBFormat && ( texture.type === FloatType || texture.type === HalfFloatType ) ) {
  12686. texture.format = RGBAFormat;
  12687. console.warn( 'THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.' );
  12688. }
  12689. // Setup framebuffer
  12690. if ( isCube ) {
  12691. renderTargetProperties.__webglFramebuffer = [];
  12692. for ( let i = 0; i < 6; i ++ ) {
  12693. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  12694. }
  12695. } else {
  12696. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  12697. if ( isMultisample ) {
  12698. if ( isWebGL2 ) {
  12699. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  12700. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  12701. _gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer );
  12702. const glFormat = utils.convert( texture.format );
  12703. const glType = utils.convert( texture.type );
  12704. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  12705. const samples = getRenderTargetSamples( renderTarget );
  12706. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  12707. state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  12708. _gl.framebufferRenderbuffer( 36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer );
  12709. _gl.bindRenderbuffer( 36161, null );
  12710. if ( renderTarget.depthBuffer ) {
  12711. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  12712. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  12713. }
  12714. state.bindFramebuffer( 36160, null );
  12715. } else {
  12716. console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
  12717. }
  12718. }
  12719. }
  12720. // Setup color buffer
  12721. if ( isCube ) {
  12722. state.bindTexture( 34067, textureProperties.__webglTexture );
  12723. setTextureParameters( 34067, texture, supportsMips );
  12724. for ( let i = 0; i < 6; i ++ ) {
  12725. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, 36064, 34069 + i );
  12726. }
  12727. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  12728. generateMipmap( 34067, texture, renderTarget.width, renderTarget.height );
  12729. }
  12730. state.bindTexture( 34067, null );
  12731. } else {
  12732. let glTextureType = 3553;
  12733. if ( isRenderTarget3D ) {
  12734. // Render targets containing layers, i.e: Texture 3D and 2d arrays
  12735. if ( isWebGL2 ) {
  12736. const isTexture3D = texture.isDataTexture3D;
  12737. glTextureType = isTexture3D ? 32879 : 35866;
  12738. } else {
  12739. console.warn( 'THREE.DataTexture3D and THREE.DataTexture2DArray only supported with WebGL2.' );
  12740. }
  12741. }
  12742. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  12743. setTextureParameters( glTextureType, texture, supportsMips );
  12744. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, 36064, glTextureType );
  12745. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  12746. generateMipmap( 3553, texture, renderTarget.width, renderTarget.height );
  12747. }
  12748. state.bindTexture( 3553, null );
  12749. }
  12750. // Setup depth and stencil buffers
  12751. if ( renderTarget.depthBuffer ) {
  12752. setupDepthRenderbuffer( renderTarget );
  12753. }
  12754. }
  12755. function updateRenderTargetMipmap( renderTarget ) {
  12756. const texture = renderTarget.texture;
  12757. const supportsMips = isPowerOfTwo( renderTarget ) || isWebGL2;
  12758. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  12759. const target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553;
  12760. const webglTexture = properties.get( texture ).__webglTexture;
  12761. state.bindTexture( target, webglTexture );
  12762. generateMipmap( target, texture, renderTarget.width, renderTarget.height );
  12763. state.bindTexture( target, null );
  12764. }
  12765. }
  12766. function updateMultisampleRenderTarget( renderTarget ) {
  12767. if ( renderTarget.isWebGLMultisampleRenderTarget ) {
  12768. if ( isWebGL2 ) {
  12769. const renderTargetProperties = properties.get( renderTarget );
  12770. state.bindFramebuffer( 36008, renderTargetProperties.__webglMultisampledFramebuffer );
  12771. state.bindFramebuffer( 36009, renderTargetProperties.__webglFramebuffer );
  12772. const width = renderTarget.width;
  12773. const height = renderTarget.height;
  12774. let mask = 16384;
  12775. if ( renderTarget.depthBuffer ) mask |= 256;
  12776. if ( renderTarget.stencilBuffer ) mask |= 1024;
  12777. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 );
  12778. state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer ); // see #18905
  12779. } else {
  12780. console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
  12781. }
  12782. }
  12783. }
  12784. function getRenderTargetSamples( renderTarget ) {
  12785. return ( isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ) ?
  12786. Math.min( maxSamples, renderTarget.samples ) : 0;
  12787. }
  12788. function updateVideoTexture( texture ) {
  12789. const frame = info.render.frame;
  12790. // Check the last frame we updated the VideoTexture
  12791. if ( _videoTextures.get( texture ) !== frame ) {
  12792. _videoTextures.set( texture, frame );
  12793. texture.update();
  12794. }
  12795. }
  12796. // backwards compatibility
  12797. let warnedTexture2D = false;
  12798. let warnedTextureCube = false;
  12799. function safeSetTexture2D( texture, slot ) {
  12800. if ( texture && texture.isWebGLRenderTarget ) {
  12801. if ( warnedTexture2D === false ) {
  12802. console.warn( 'THREE.WebGLTextures.safeSetTexture2D: don\'t use render targets as textures. Use their .texture property instead.' );
  12803. warnedTexture2D = true;
  12804. }
  12805. texture = texture.texture;
  12806. }
  12807. setTexture2D( texture, slot );
  12808. }
  12809. function safeSetTextureCube( texture, slot ) {
  12810. if ( texture && texture.isWebGLCubeRenderTarget ) {
  12811. if ( warnedTextureCube === false ) {
  12812. console.warn( 'THREE.WebGLTextures.safeSetTextureCube: don\'t use cube render targets as textures. Use their .texture property instead.' );
  12813. warnedTextureCube = true;
  12814. }
  12815. texture = texture.texture;
  12816. }
  12817. setTextureCube( texture, slot );
  12818. }
  12819. //
  12820. this.allocateTextureUnit = allocateTextureUnit;
  12821. this.resetTextureUnits = resetTextureUnits;
  12822. this.setTexture2D = setTexture2D;
  12823. this.setTexture2DArray = setTexture2DArray;
  12824. this.setTexture3D = setTexture3D;
  12825. this.setTextureCube = setTextureCube;
  12826. this.setupRenderTarget = setupRenderTarget;
  12827. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  12828. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  12829. this.safeSetTexture2D = safeSetTexture2D;
  12830. this.safeSetTextureCube = safeSetTextureCube;
  12831. }
  12832. function WebGLUtils( gl, extensions, capabilities ) {
  12833. const isWebGL2 = capabilities.isWebGL2;
  12834. function convert( p ) {
  12835. let extension;
  12836. if ( p === UnsignedByteType ) return 5121;
  12837. if ( p === UnsignedShort4444Type ) return 32819;
  12838. if ( p === UnsignedShort5551Type ) return 32820;
  12839. if ( p === UnsignedShort565Type ) return 33635;
  12840. if ( p === ByteType ) return 5120;
  12841. if ( p === ShortType ) return 5122;
  12842. if ( p === UnsignedShortType ) return 5123;
  12843. if ( p === IntType ) return 5124;
  12844. if ( p === UnsignedIntType ) return 5125;
  12845. if ( p === FloatType ) return 5126;
  12846. if ( p === HalfFloatType ) {
  12847. if ( isWebGL2 ) return 5131;
  12848. extension = extensions.get( 'OES_texture_half_float' );
  12849. if ( extension !== null ) {
  12850. return extension.HALF_FLOAT_OES;
  12851. } else {
  12852. return null;
  12853. }
  12854. }
  12855. if ( p === AlphaFormat ) return 6406;
  12856. if ( p === RGBFormat ) return 6407;
  12857. if ( p === RGBAFormat ) return 6408;
  12858. if ( p === LuminanceFormat ) return 6409;
  12859. if ( p === LuminanceAlphaFormat ) return 6410;
  12860. if ( p === DepthFormat ) return 6402;
  12861. if ( p === DepthStencilFormat ) return 34041;
  12862. if ( p === RedFormat ) return 6403;
  12863. // WebGL2 formats.
  12864. if ( p === RedIntegerFormat ) return 36244;
  12865. if ( p === RGFormat ) return 33319;
  12866. if ( p === RGIntegerFormat ) return 33320;
  12867. if ( p === RGBIntegerFormat ) return 36248;
  12868. if ( p === RGBAIntegerFormat ) return 36249;
  12869. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  12870. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  12871. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  12872. if ( extension !== null ) {
  12873. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  12874. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  12875. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  12876. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  12877. } else {
  12878. return null;
  12879. }
  12880. }
  12881. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  12882. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  12883. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  12884. if ( extension !== null ) {
  12885. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  12886. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  12887. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  12888. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  12889. } else {
  12890. return null;
  12891. }
  12892. }
  12893. if ( p === RGB_ETC1_Format ) {
  12894. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  12895. if ( extension !== null ) {
  12896. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  12897. } else {
  12898. return null;
  12899. }
  12900. }
  12901. if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  12902. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  12903. if ( extension !== null ) {
  12904. if ( p === RGB_ETC2_Format ) return extension.COMPRESSED_RGB8_ETC2;
  12905. if ( p === RGBA_ETC2_EAC_Format ) return extension.COMPRESSED_RGBA8_ETC2_EAC;
  12906. }
  12907. }
  12908. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  12909. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  12910. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  12911. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  12912. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ||
  12913. p === SRGB8_ALPHA8_ASTC_4x4_Format || p === SRGB8_ALPHA8_ASTC_5x4_Format || p === SRGB8_ALPHA8_ASTC_5x5_Format ||
  12914. p === SRGB8_ALPHA8_ASTC_6x5_Format || p === SRGB8_ALPHA8_ASTC_6x6_Format || p === SRGB8_ALPHA8_ASTC_8x5_Format ||
  12915. p === SRGB8_ALPHA8_ASTC_8x6_Format || p === SRGB8_ALPHA8_ASTC_8x8_Format || p === SRGB8_ALPHA8_ASTC_10x5_Format ||
  12916. p === SRGB8_ALPHA8_ASTC_10x6_Format || p === SRGB8_ALPHA8_ASTC_10x8_Format || p === SRGB8_ALPHA8_ASTC_10x10_Format ||
  12917. p === SRGB8_ALPHA8_ASTC_12x10_Format || p === SRGB8_ALPHA8_ASTC_12x12_Format ) {
  12918. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  12919. if ( extension !== null ) {
  12920. // TODO Complete?
  12921. return p;
  12922. } else {
  12923. return null;
  12924. }
  12925. }
  12926. if ( p === RGBA_BPTC_Format ) {
  12927. extension = extensions.get( 'EXT_texture_compression_bptc' );
  12928. if ( extension !== null ) {
  12929. // TODO Complete?
  12930. return p;
  12931. } else {
  12932. return null;
  12933. }
  12934. }
  12935. if ( p === UnsignedInt248Type ) {
  12936. if ( isWebGL2 ) return 34042;
  12937. extension = extensions.get( 'WEBGL_depth_texture' );
  12938. if ( extension !== null ) {
  12939. return extension.UNSIGNED_INT_24_8_WEBGL;
  12940. } else {
  12941. return null;
  12942. }
  12943. }
  12944. }
  12945. return { convert: convert };
  12946. }
  12947. class ArrayCamera extends PerspectiveCamera {
  12948. constructor( array = [] ) {
  12949. super();
  12950. this.cameras = array;
  12951. }
  12952. }
  12953. ArrayCamera.prototype.isArrayCamera = true;
  12954. class Group extends Object3D {
  12955. constructor() {
  12956. super();
  12957. this.type = 'Group';
  12958. }
  12959. }
  12960. Group.prototype.isGroup = true;
  12961. function WebXRController() {
  12962. this._targetRay = null;
  12963. this._grip = null;
  12964. this._hand = null;
  12965. }
  12966. Object.assign( WebXRController.prototype, {
  12967. constructor: WebXRController,
  12968. getHandSpace: function () {
  12969. if ( this._hand === null ) {
  12970. this._hand = new Group();
  12971. this._hand.matrixAutoUpdate = false;
  12972. this._hand.visible = false;
  12973. this._hand.joints = {};
  12974. this._hand.inputState = { pinching: false };
  12975. }
  12976. return this._hand;
  12977. },
  12978. getTargetRaySpace: function () {
  12979. if ( this._targetRay === null ) {
  12980. this._targetRay = new Group();
  12981. this._targetRay.matrixAutoUpdate = false;
  12982. this._targetRay.visible = false;
  12983. }
  12984. return this._targetRay;
  12985. },
  12986. getGripSpace: function () {
  12987. if ( this._grip === null ) {
  12988. this._grip = new Group();
  12989. this._grip.matrixAutoUpdate = false;
  12990. this._grip.visible = false;
  12991. }
  12992. return this._grip;
  12993. },
  12994. dispatchEvent: function ( event ) {
  12995. if ( this._targetRay !== null ) {
  12996. this._targetRay.dispatchEvent( event );
  12997. }
  12998. if ( this._grip !== null ) {
  12999. this._grip.dispatchEvent( event );
  13000. }
  13001. if ( this._hand !== null ) {
  13002. this._hand.dispatchEvent( event );
  13003. }
  13004. return this;
  13005. },
  13006. disconnect: function ( inputSource ) {
  13007. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  13008. if ( this._targetRay !== null ) {
  13009. this._targetRay.visible = false;
  13010. }
  13011. if ( this._grip !== null ) {
  13012. this._grip.visible = false;
  13013. }
  13014. if ( this._hand !== null ) {
  13015. this._hand.visible = false;
  13016. }
  13017. return this;
  13018. },
  13019. update: function ( inputSource, frame, referenceSpace ) {
  13020. let inputPose = null;
  13021. let gripPose = null;
  13022. let handPose = null;
  13023. const targetRay = this._targetRay;
  13024. const grip = this._grip;
  13025. const hand = this._hand;
  13026. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  13027. if ( targetRay !== null ) {
  13028. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  13029. if ( inputPose !== null ) {
  13030. targetRay.matrix.fromArray( inputPose.transform.matrix );
  13031. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  13032. }
  13033. }
  13034. if ( hand && inputSource.hand ) {
  13035. handPose = true;
  13036. for ( const inputjoint of inputSource.hand.values() ) {
  13037. // Update the joints groups with the XRJoint poses
  13038. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  13039. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  13040. // The transform of this joint will be updated with the joint pose on each frame
  13041. const joint = new Group();
  13042. joint.matrixAutoUpdate = false;
  13043. joint.visible = false;
  13044. hand.joints[ inputjoint.jointName ] = joint;
  13045. // ??
  13046. hand.add( joint );
  13047. }
  13048. const joint = hand.joints[ inputjoint.jointName ];
  13049. if ( jointPose !== null ) {
  13050. joint.matrix.fromArray( jointPose.transform.matrix );
  13051. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  13052. joint.jointRadius = jointPose.radius;
  13053. }
  13054. joint.visible = jointPose !== null;
  13055. }
  13056. // Custom events
  13057. // Check pinchz
  13058. const indexTip = hand.joints[ 'index-finger-tip' ];
  13059. const thumbTip = hand.joints[ 'thumb-tip' ];
  13060. const distance = indexTip.position.distanceTo( thumbTip.position );
  13061. const distanceToPinch = 0.02;
  13062. const threshold = 0.005;
  13063. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  13064. hand.inputState.pinching = false;
  13065. this.dispatchEvent( {
  13066. type: 'pinchend',
  13067. handedness: inputSource.handedness,
  13068. target: this
  13069. } );
  13070. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  13071. hand.inputState.pinching = true;
  13072. this.dispatchEvent( {
  13073. type: 'pinchstart',
  13074. handedness: inputSource.handedness,
  13075. target: this
  13076. } );
  13077. }
  13078. } else {
  13079. if ( grip !== null && inputSource.gripSpace ) {
  13080. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  13081. if ( gripPose !== null ) {
  13082. grip.matrix.fromArray( gripPose.transform.matrix );
  13083. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  13084. }
  13085. }
  13086. }
  13087. }
  13088. if ( targetRay !== null ) {
  13089. targetRay.visible = ( inputPose !== null );
  13090. }
  13091. if ( grip !== null ) {
  13092. grip.visible = ( gripPose !== null );
  13093. }
  13094. if ( hand !== null ) {
  13095. hand.visible = ( handPose !== null );
  13096. }
  13097. return this;
  13098. }
  13099. } );
  13100. function WebXRManager( renderer, gl ) {
  13101. const scope = this;
  13102. const state = renderer.state;
  13103. let session = null;
  13104. let framebufferScaleFactor = 1.0;
  13105. let referenceSpace = null;
  13106. let referenceSpaceType = 'local-floor';
  13107. let pose = null;
  13108. const controllers = [];
  13109. const inputSourcesMap = new Map();
  13110. //
  13111. const cameraL = new PerspectiveCamera();
  13112. cameraL.layers.enable( 1 );
  13113. cameraL.viewport = new Vector4();
  13114. const cameraR = new PerspectiveCamera();
  13115. cameraR.layers.enable( 2 );
  13116. cameraR.viewport = new Vector4();
  13117. const cameras = [ cameraL, cameraR ];
  13118. const cameraVR = new ArrayCamera();
  13119. cameraVR.layers.enable( 1 );
  13120. cameraVR.layers.enable( 2 );
  13121. let _currentDepthNear = null;
  13122. let _currentDepthFar = null;
  13123. //
  13124. this.enabled = false;
  13125. this.isPresenting = false;
  13126. this.getController = function ( index ) {
  13127. let controller = controllers[ index ];
  13128. if ( controller === undefined ) {
  13129. controller = new WebXRController();
  13130. controllers[ index ] = controller;
  13131. }
  13132. return controller.getTargetRaySpace();
  13133. };
  13134. this.getControllerGrip = function ( index ) {
  13135. let controller = controllers[ index ];
  13136. if ( controller === undefined ) {
  13137. controller = new WebXRController();
  13138. controllers[ index ] = controller;
  13139. }
  13140. return controller.getGripSpace();
  13141. };
  13142. this.getHand = function ( index ) {
  13143. let controller = controllers[ index ];
  13144. if ( controller === undefined ) {
  13145. controller = new WebXRController();
  13146. controllers[ index ] = controller;
  13147. }
  13148. return controller.getHandSpace();
  13149. };
  13150. //
  13151. function onSessionEvent( event ) {
  13152. const controller = inputSourcesMap.get( event.inputSource );
  13153. if ( controller ) {
  13154. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  13155. }
  13156. }
  13157. function onSessionEnd() {
  13158. inputSourcesMap.forEach( function ( controller, inputSource ) {
  13159. controller.disconnect( inputSource );
  13160. } );
  13161. inputSourcesMap.clear();
  13162. _currentDepthNear = null;
  13163. _currentDepthFar = null;
  13164. // restore framebuffer/rendering state
  13165. state.bindXRFramebuffer( null );
  13166. renderer.setRenderTarget( renderer.getRenderTarget() );
  13167. //
  13168. animation.stop();
  13169. scope.isPresenting = false;
  13170. scope.dispatchEvent( { type: 'sessionend' } );
  13171. }
  13172. this.setFramebufferScaleFactor = function ( value ) {
  13173. framebufferScaleFactor = value;
  13174. if ( scope.isPresenting === true ) {
  13175. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  13176. }
  13177. };
  13178. this.setReferenceSpaceType = function ( value ) {
  13179. referenceSpaceType = value;
  13180. if ( scope.isPresenting === true ) {
  13181. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  13182. }
  13183. };
  13184. this.getReferenceSpace = function () {
  13185. return referenceSpace;
  13186. };
  13187. this.getSession = function () {
  13188. return session;
  13189. };
  13190. this.setSession = async function ( value ) {
  13191. session = value;
  13192. if ( session !== null ) {
  13193. session.addEventListener( 'select', onSessionEvent );
  13194. session.addEventListener( 'selectstart', onSessionEvent );
  13195. session.addEventListener( 'selectend', onSessionEvent );
  13196. session.addEventListener( 'squeeze', onSessionEvent );
  13197. session.addEventListener( 'squeezestart', onSessionEvent );
  13198. session.addEventListener( 'squeezeend', onSessionEvent );
  13199. session.addEventListener( 'end', onSessionEnd );
  13200. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  13201. const attributes = gl.getContextAttributes();
  13202. if ( attributes.xrCompatible !== true ) {
  13203. await gl.makeXRCompatible();
  13204. }
  13205. const layerInit = {
  13206. antialias: attributes.antialias,
  13207. alpha: attributes.alpha,
  13208. depth: attributes.depth,
  13209. stencil: attributes.stencil,
  13210. framebufferScaleFactor: framebufferScaleFactor
  13211. };
  13212. // eslint-disable-next-line no-undef
  13213. const baseLayer = new XRWebGLLayer( session, gl, layerInit );
  13214. session.updateRenderState( { baseLayer: baseLayer } );
  13215. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  13216. animation.setContext( session );
  13217. animation.start();
  13218. scope.isPresenting = true;
  13219. scope.dispatchEvent( { type: 'sessionstart' } );
  13220. }
  13221. };
  13222. function onInputSourcesChange( event ) {
  13223. const inputSources = session.inputSources;
  13224. // Assign inputSources to available controllers
  13225. for ( let i = 0; i < controllers.length; i ++ ) {
  13226. inputSourcesMap.set( inputSources[ i ], controllers[ i ] );
  13227. }
  13228. // Notify disconnected
  13229. for ( let i = 0; i < event.removed.length; i ++ ) {
  13230. const inputSource = event.removed[ i ];
  13231. const controller = inputSourcesMap.get( inputSource );
  13232. if ( controller ) {
  13233. controller.dispatchEvent( { type: 'disconnected', data: inputSource } );
  13234. inputSourcesMap.delete( inputSource );
  13235. }
  13236. }
  13237. // Notify connected
  13238. for ( let i = 0; i < event.added.length; i ++ ) {
  13239. const inputSource = event.added[ i ];
  13240. const controller = inputSourcesMap.get( inputSource );
  13241. if ( controller ) {
  13242. controller.dispatchEvent( { type: 'connected', data: inputSource } );
  13243. }
  13244. }
  13245. }
  13246. //
  13247. const cameraLPos = new Vector3();
  13248. const cameraRPos = new Vector3();
  13249. /**
  13250. * Assumes 2 cameras that are parallel and share an X-axis, and that
  13251. * the cameras' projection and world matrices have already been set.
  13252. * And that near and far planes are identical for both cameras.
  13253. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  13254. */
  13255. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  13256. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  13257. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  13258. const ipd = cameraLPos.distanceTo( cameraRPos );
  13259. const projL = cameraL.projectionMatrix.elements;
  13260. const projR = cameraR.projectionMatrix.elements;
  13261. // VR systems will have identical far and near planes, and
  13262. // most likely identical top and bottom frustum extents.
  13263. // Use the left camera for these values.
  13264. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  13265. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  13266. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  13267. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  13268. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  13269. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  13270. const left = near * leftFov;
  13271. const right = near * rightFov;
  13272. // Calculate the new camera's position offset from the
  13273. // left camera. xOffset should be roughly half `ipd`.
  13274. const zOffset = ipd / ( - leftFov + rightFov );
  13275. const xOffset = zOffset * - leftFov;
  13276. // TODO: Better way to apply this offset?
  13277. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  13278. camera.translateX( xOffset );
  13279. camera.translateZ( zOffset );
  13280. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  13281. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  13282. // Find the union of the frustum values of the cameras and scale
  13283. // the values so that the near plane's position does not change in world space,
  13284. // although must now be relative to the new union camera.
  13285. const near2 = near + zOffset;
  13286. const far2 = far + zOffset;
  13287. const left2 = left - xOffset;
  13288. const right2 = right + ( ipd - xOffset );
  13289. const top2 = topFov * far / far2 * near2;
  13290. const bottom2 = bottomFov * far / far2 * near2;
  13291. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  13292. }
  13293. function updateCamera( camera, parent ) {
  13294. if ( parent === null ) {
  13295. camera.matrixWorld.copy( camera.matrix );
  13296. } else {
  13297. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  13298. }
  13299. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  13300. }
  13301. this.getCamera = function ( camera ) {
  13302. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  13303. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  13304. if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) {
  13305. // Note that the new renderState won't apply until the next frame. See #18320
  13306. session.updateRenderState( {
  13307. depthNear: cameraVR.near,
  13308. depthFar: cameraVR.far
  13309. } );
  13310. _currentDepthNear = cameraVR.near;
  13311. _currentDepthFar = cameraVR.far;
  13312. }
  13313. const parent = camera.parent;
  13314. const cameras = cameraVR.cameras;
  13315. updateCamera( cameraVR, parent );
  13316. for ( let i = 0; i < cameras.length; i ++ ) {
  13317. updateCamera( cameras[ i ], parent );
  13318. }
  13319. // update camera and its children
  13320. camera.matrixWorld.copy( cameraVR.matrixWorld );
  13321. camera.matrix.copy( cameraVR.matrix );
  13322. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  13323. const children = camera.children;
  13324. for ( let i = 0, l = children.length; i < l; i ++ ) {
  13325. children[ i ].updateMatrixWorld( true );
  13326. }
  13327. // update projection matrix for proper view frustum culling
  13328. if ( cameras.length === 2 ) {
  13329. setProjectionFromUnion( cameraVR, cameraL, cameraR );
  13330. } else {
  13331. // assume single camera setup (AR)
  13332. cameraVR.projectionMatrix.copy( cameraL.projectionMatrix );
  13333. }
  13334. return cameraVR;
  13335. };
  13336. // Animation Loop
  13337. let onAnimationFrameCallback = null;
  13338. function onAnimationFrame( time, frame ) {
  13339. pose = frame.getViewerPose( referenceSpace );
  13340. if ( pose !== null ) {
  13341. const views = pose.views;
  13342. const baseLayer = session.renderState.baseLayer;
  13343. state.bindXRFramebuffer( baseLayer.framebuffer );
  13344. let cameraVRNeedsUpdate = false;
  13345. // check if it's necessary to rebuild cameraVR's camera list
  13346. if ( views.length !== cameraVR.cameras.length ) {
  13347. cameraVR.cameras.length = 0;
  13348. cameraVRNeedsUpdate = true;
  13349. }
  13350. for ( let i = 0; i < views.length; i ++ ) {
  13351. const view = views[ i ];
  13352. const viewport = baseLayer.getViewport( view );
  13353. const camera = cameras[ i ];
  13354. camera.matrix.fromArray( view.transform.matrix );
  13355. camera.projectionMatrix.fromArray( view.projectionMatrix );
  13356. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  13357. if ( i === 0 ) {
  13358. cameraVR.matrix.copy( camera.matrix );
  13359. }
  13360. if ( cameraVRNeedsUpdate === true ) {
  13361. cameraVR.cameras.push( camera );
  13362. }
  13363. }
  13364. }
  13365. //
  13366. const inputSources = session.inputSources;
  13367. for ( let i = 0; i < controllers.length; i ++ ) {
  13368. const controller = controllers[ i ];
  13369. const inputSource = inputSources[ i ];
  13370. controller.update( inputSource, frame, referenceSpace );
  13371. }
  13372. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  13373. }
  13374. const animation = new WebGLAnimation();
  13375. animation.setAnimationLoop( onAnimationFrame );
  13376. this.setAnimationLoop = function ( callback ) {
  13377. onAnimationFrameCallback = callback;
  13378. };
  13379. this.dispose = function () {};
  13380. }
  13381. Object.assign( WebXRManager.prototype, EventDispatcher.prototype );
  13382. function WebGLMaterials( properties ) {
  13383. function refreshFogUniforms( uniforms, fog ) {
  13384. uniforms.fogColor.value.copy( fog.color );
  13385. if ( fog.isFog ) {
  13386. uniforms.fogNear.value = fog.near;
  13387. uniforms.fogFar.value = fog.far;
  13388. } else if ( fog.isFogExp2 ) {
  13389. uniforms.fogDensity.value = fog.density;
  13390. }
  13391. }
  13392. function refreshMaterialUniforms( uniforms, material, pixelRatio, height ) {
  13393. if ( material.isMeshBasicMaterial ) {
  13394. refreshUniformsCommon( uniforms, material );
  13395. } else if ( material.isMeshLambertMaterial ) {
  13396. refreshUniformsCommon( uniforms, material );
  13397. refreshUniformsLambert( uniforms, material );
  13398. } else if ( material.isMeshToonMaterial ) {
  13399. refreshUniformsCommon( uniforms, material );
  13400. refreshUniformsToon( uniforms, material );
  13401. } else if ( material.isMeshPhongMaterial ) {
  13402. refreshUniformsCommon( uniforms, material );
  13403. refreshUniformsPhong( uniforms, material );
  13404. } else if ( material.isMeshStandardMaterial ) {
  13405. refreshUniformsCommon( uniforms, material );
  13406. if ( material.isMeshPhysicalMaterial ) {
  13407. refreshUniformsPhysical( uniforms, material );
  13408. } else {
  13409. refreshUniformsStandard( uniforms, material );
  13410. }
  13411. } else if ( material.isMeshMatcapMaterial ) {
  13412. refreshUniformsCommon( uniforms, material );
  13413. refreshUniformsMatcap( uniforms, material );
  13414. } else if ( material.isMeshDepthMaterial ) {
  13415. refreshUniformsCommon( uniforms, material );
  13416. refreshUniformsDepth( uniforms, material );
  13417. } else if ( material.isMeshDistanceMaterial ) {
  13418. refreshUniformsCommon( uniforms, material );
  13419. refreshUniformsDistance( uniforms, material );
  13420. } else if ( material.isMeshNormalMaterial ) {
  13421. refreshUniformsCommon( uniforms, material );
  13422. refreshUniformsNormal( uniforms, material );
  13423. } else if ( material.isLineBasicMaterial ) {
  13424. refreshUniformsLine( uniforms, material );
  13425. if ( material.isLineDashedMaterial ) {
  13426. refreshUniformsDash( uniforms, material );
  13427. }
  13428. } else if ( material.isPointsMaterial ) {
  13429. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  13430. } else if ( material.isSpriteMaterial ) {
  13431. refreshUniformsSprites( uniforms, material );
  13432. } else if ( material.isShadowMaterial ) {
  13433. uniforms.color.value.copy( material.color );
  13434. uniforms.opacity.value = material.opacity;
  13435. } else if ( material.isShaderMaterial ) {
  13436. material.uniformsNeedUpdate = false; // #15581
  13437. }
  13438. }
  13439. function refreshUniformsCommon( uniforms, material ) {
  13440. uniforms.opacity.value = material.opacity;
  13441. if ( material.color ) {
  13442. uniforms.diffuse.value.copy( material.color );
  13443. }
  13444. if ( material.emissive ) {
  13445. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  13446. }
  13447. if ( material.map ) {
  13448. uniforms.map.value = material.map;
  13449. }
  13450. if ( material.alphaMap ) {
  13451. uniforms.alphaMap.value = material.alphaMap;
  13452. }
  13453. if ( material.specularMap ) {
  13454. uniforms.specularMap.value = material.specularMap;
  13455. }
  13456. const envMap = properties.get( material ).envMap;
  13457. if ( envMap ) {
  13458. uniforms.envMap.value = envMap;
  13459. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap._needsFlipEnvMap ) ? - 1 : 1;
  13460. uniforms.reflectivity.value = material.reflectivity;
  13461. uniforms.refractionRatio.value = material.refractionRatio;
  13462. const maxMipLevel = properties.get( envMap ).__maxMipLevel;
  13463. if ( maxMipLevel !== undefined ) {
  13464. uniforms.maxMipLevel.value = maxMipLevel;
  13465. }
  13466. }
  13467. if ( material.lightMap ) {
  13468. uniforms.lightMap.value = material.lightMap;
  13469. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  13470. }
  13471. if ( material.aoMap ) {
  13472. uniforms.aoMap.value = material.aoMap;
  13473. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  13474. }
  13475. // uv repeat and offset setting priorities
  13476. // 1. color map
  13477. // 2. specular map
  13478. // 3. displacementMap map
  13479. // 4. normal map
  13480. // 5. bump map
  13481. // 6. roughnessMap map
  13482. // 7. metalnessMap map
  13483. // 8. alphaMap map
  13484. // 9. emissiveMap map
  13485. // 10. clearcoat map
  13486. // 11. clearcoat normal map
  13487. // 12. clearcoat roughnessMap map
  13488. let uvScaleMap;
  13489. if ( material.map ) {
  13490. uvScaleMap = material.map;
  13491. } else if ( material.specularMap ) {
  13492. uvScaleMap = material.specularMap;
  13493. } else if ( material.displacementMap ) {
  13494. uvScaleMap = material.displacementMap;
  13495. } else if ( material.normalMap ) {
  13496. uvScaleMap = material.normalMap;
  13497. } else if ( material.bumpMap ) {
  13498. uvScaleMap = material.bumpMap;
  13499. } else if ( material.roughnessMap ) {
  13500. uvScaleMap = material.roughnessMap;
  13501. } else if ( material.metalnessMap ) {
  13502. uvScaleMap = material.metalnessMap;
  13503. } else if ( material.alphaMap ) {
  13504. uvScaleMap = material.alphaMap;
  13505. } else if ( material.emissiveMap ) {
  13506. uvScaleMap = material.emissiveMap;
  13507. } else if ( material.clearcoatMap ) {
  13508. uvScaleMap = material.clearcoatMap;
  13509. } else if ( material.clearcoatNormalMap ) {
  13510. uvScaleMap = material.clearcoatNormalMap;
  13511. } else if ( material.clearcoatRoughnessMap ) {
  13512. uvScaleMap = material.clearcoatRoughnessMap;
  13513. }
  13514. if ( uvScaleMap !== undefined ) {
  13515. // backwards compatibility
  13516. if ( uvScaleMap.isWebGLRenderTarget ) {
  13517. uvScaleMap = uvScaleMap.texture;
  13518. }
  13519. if ( uvScaleMap.matrixAutoUpdate === true ) {
  13520. uvScaleMap.updateMatrix();
  13521. }
  13522. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  13523. }
  13524. // uv repeat and offset setting priorities for uv2
  13525. // 1. ao map
  13526. // 2. light map
  13527. let uv2ScaleMap;
  13528. if ( material.aoMap ) {
  13529. uv2ScaleMap = material.aoMap;
  13530. } else if ( material.lightMap ) {
  13531. uv2ScaleMap = material.lightMap;
  13532. }
  13533. if ( uv2ScaleMap !== undefined ) {
  13534. // backwards compatibility
  13535. if ( uv2ScaleMap.isWebGLRenderTarget ) {
  13536. uv2ScaleMap = uv2ScaleMap.texture;
  13537. }
  13538. if ( uv2ScaleMap.matrixAutoUpdate === true ) {
  13539. uv2ScaleMap.updateMatrix();
  13540. }
  13541. uniforms.uv2Transform.value.copy( uv2ScaleMap.matrix );
  13542. }
  13543. }
  13544. function refreshUniformsLine( uniforms, material ) {
  13545. uniforms.diffuse.value.copy( material.color );
  13546. uniforms.opacity.value = material.opacity;
  13547. }
  13548. function refreshUniformsDash( uniforms, material ) {
  13549. uniforms.dashSize.value = material.dashSize;
  13550. uniforms.totalSize.value = material.dashSize + material.gapSize;
  13551. uniforms.scale.value = material.scale;
  13552. }
  13553. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  13554. uniforms.diffuse.value.copy( material.color );
  13555. uniforms.opacity.value = material.opacity;
  13556. uniforms.size.value = material.size * pixelRatio;
  13557. uniforms.scale.value = height * 0.5;
  13558. if ( material.map ) {
  13559. uniforms.map.value = material.map;
  13560. }
  13561. if ( material.alphaMap ) {
  13562. uniforms.alphaMap.value = material.alphaMap;
  13563. }
  13564. // uv repeat and offset setting priorities
  13565. // 1. color map
  13566. // 2. alpha map
  13567. let uvScaleMap;
  13568. if ( material.map ) {
  13569. uvScaleMap = material.map;
  13570. } else if ( material.alphaMap ) {
  13571. uvScaleMap = material.alphaMap;
  13572. }
  13573. if ( uvScaleMap !== undefined ) {
  13574. if ( uvScaleMap.matrixAutoUpdate === true ) {
  13575. uvScaleMap.updateMatrix();
  13576. }
  13577. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  13578. }
  13579. }
  13580. function refreshUniformsSprites( uniforms, material ) {
  13581. uniforms.diffuse.value.copy( material.color );
  13582. uniforms.opacity.value = material.opacity;
  13583. uniforms.rotation.value = material.rotation;
  13584. if ( material.map ) {
  13585. uniforms.map.value = material.map;
  13586. }
  13587. if ( material.alphaMap ) {
  13588. uniforms.alphaMap.value = material.alphaMap;
  13589. }
  13590. // uv repeat and offset setting priorities
  13591. // 1. color map
  13592. // 2. alpha map
  13593. let uvScaleMap;
  13594. if ( material.map ) {
  13595. uvScaleMap = material.map;
  13596. } else if ( material.alphaMap ) {
  13597. uvScaleMap = material.alphaMap;
  13598. }
  13599. if ( uvScaleMap !== undefined ) {
  13600. if ( uvScaleMap.matrixAutoUpdate === true ) {
  13601. uvScaleMap.updateMatrix();
  13602. }
  13603. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  13604. }
  13605. }
  13606. function refreshUniformsLambert( uniforms, material ) {
  13607. if ( material.emissiveMap ) {
  13608. uniforms.emissiveMap.value = material.emissiveMap;
  13609. }
  13610. }
  13611. function refreshUniformsPhong( uniforms, material ) {
  13612. uniforms.specular.value.copy( material.specular );
  13613. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  13614. if ( material.emissiveMap ) {
  13615. uniforms.emissiveMap.value = material.emissiveMap;
  13616. }
  13617. if ( material.bumpMap ) {
  13618. uniforms.bumpMap.value = material.bumpMap;
  13619. uniforms.bumpScale.value = material.bumpScale;
  13620. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  13621. }
  13622. if ( material.normalMap ) {
  13623. uniforms.normalMap.value = material.normalMap;
  13624. uniforms.normalScale.value.copy( material.normalScale );
  13625. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  13626. }
  13627. if ( material.displacementMap ) {
  13628. uniforms.displacementMap.value = material.displacementMap;
  13629. uniforms.displacementScale.value = material.displacementScale;
  13630. uniforms.displacementBias.value = material.displacementBias;
  13631. }
  13632. }
  13633. function refreshUniformsToon( uniforms, material ) {
  13634. if ( material.gradientMap ) {
  13635. uniforms.gradientMap.value = material.gradientMap;
  13636. }
  13637. if ( material.emissiveMap ) {
  13638. uniforms.emissiveMap.value = material.emissiveMap;
  13639. }
  13640. if ( material.bumpMap ) {
  13641. uniforms.bumpMap.value = material.bumpMap;
  13642. uniforms.bumpScale.value = material.bumpScale;
  13643. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  13644. }
  13645. if ( material.normalMap ) {
  13646. uniforms.normalMap.value = material.normalMap;
  13647. uniforms.normalScale.value.copy( material.normalScale );
  13648. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  13649. }
  13650. if ( material.displacementMap ) {
  13651. uniforms.displacementMap.value = material.displacementMap;
  13652. uniforms.displacementScale.value = material.displacementScale;
  13653. uniforms.displacementBias.value = material.displacementBias;
  13654. }
  13655. }
  13656. function refreshUniformsStandard( uniforms, material ) {
  13657. uniforms.roughness.value = material.roughness;
  13658. uniforms.metalness.value = material.metalness;
  13659. if ( material.roughnessMap ) {
  13660. uniforms.roughnessMap.value = material.roughnessMap;
  13661. }
  13662. if ( material.metalnessMap ) {
  13663. uniforms.metalnessMap.value = material.metalnessMap;
  13664. }
  13665. if ( material.emissiveMap ) {
  13666. uniforms.emissiveMap.value = material.emissiveMap;
  13667. }
  13668. if ( material.bumpMap ) {
  13669. uniforms.bumpMap.value = material.bumpMap;
  13670. uniforms.bumpScale.value = material.bumpScale;
  13671. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  13672. }
  13673. if ( material.normalMap ) {
  13674. uniforms.normalMap.value = material.normalMap;
  13675. uniforms.normalScale.value.copy( material.normalScale );
  13676. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  13677. }
  13678. if ( material.displacementMap ) {
  13679. uniforms.displacementMap.value = material.displacementMap;
  13680. uniforms.displacementScale.value = material.displacementScale;
  13681. uniforms.displacementBias.value = material.displacementBias;
  13682. }
  13683. const envMap = properties.get( material ).envMap;
  13684. if ( envMap ) {
  13685. //uniforms.envMap.value = material.envMap; // part of uniforms common
  13686. uniforms.envMapIntensity.value = material.envMapIntensity;
  13687. }
  13688. }
  13689. function refreshUniformsPhysical( uniforms, material ) {
  13690. refreshUniformsStandard( uniforms, material );
  13691. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  13692. uniforms.clearcoat.value = material.clearcoat;
  13693. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  13694. if ( material.sheen ) uniforms.sheen.value.copy( material.sheen );
  13695. if ( material.clearcoatMap ) {
  13696. uniforms.clearcoatMap.value = material.clearcoatMap;
  13697. }
  13698. if ( material.clearcoatRoughnessMap ) {
  13699. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  13700. }
  13701. if ( material.clearcoatNormalMap ) {
  13702. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  13703. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  13704. if ( material.side === BackSide ) {
  13705. uniforms.clearcoatNormalScale.value.negate();
  13706. }
  13707. }
  13708. uniforms.transmission.value = material.transmission;
  13709. if ( material.transmissionMap ) {
  13710. uniforms.transmissionMap.value = material.transmissionMap;
  13711. }
  13712. }
  13713. function refreshUniformsMatcap( uniforms, material ) {
  13714. if ( material.matcap ) {
  13715. uniforms.matcap.value = material.matcap;
  13716. }
  13717. if ( material.bumpMap ) {
  13718. uniforms.bumpMap.value = material.bumpMap;
  13719. uniforms.bumpScale.value = material.bumpScale;
  13720. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  13721. }
  13722. if ( material.normalMap ) {
  13723. uniforms.normalMap.value = material.normalMap;
  13724. uniforms.normalScale.value.copy( material.normalScale );
  13725. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  13726. }
  13727. if ( material.displacementMap ) {
  13728. uniforms.displacementMap.value = material.displacementMap;
  13729. uniforms.displacementScale.value = material.displacementScale;
  13730. uniforms.displacementBias.value = material.displacementBias;
  13731. }
  13732. }
  13733. function refreshUniformsDepth( uniforms, material ) {
  13734. if ( material.displacementMap ) {
  13735. uniforms.displacementMap.value = material.displacementMap;
  13736. uniforms.displacementScale.value = material.displacementScale;
  13737. uniforms.displacementBias.value = material.displacementBias;
  13738. }
  13739. }
  13740. function refreshUniformsDistance( uniforms, material ) {
  13741. if ( material.displacementMap ) {
  13742. uniforms.displacementMap.value = material.displacementMap;
  13743. uniforms.displacementScale.value = material.displacementScale;
  13744. uniforms.displacementBias.value = material.displacementBias;
  13745. }
  13746. uniforms.referencePosition.value.copy( material.referencePosition );
  13747. uniforms.nearDistance.value = material.nearDistance;
  13748. uniforms.farDistance.value = material.farDistance;
  13749. }
  13750. function refreshUniformsNormal( uniforms, material ) {
  13751. if ( material.bumpMap ) {
  13752. uniforms.bumpMap.value = material.bumpMap;
  13753. uniforms.bumpScale.value = material.bumpScale;
  13754. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  13755. }
  13756. if ( material.normalMap ) {
  13757. uniforms.normalMap.value = material.normalMap;
  13758. uniforms.normalScale.value.copy( material.normalScale );
  13759. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  13760. }
  13761. if ( material.displacementMap ) {
  13762. uniforms.displacementMap.value = material.displacementMap;
  13763. uniforms.displacementScale.value = material.displacementScale;
  13764. uniforms.displacementBias.value = material.displacementBias;
  13765. }
  13766. }
  13767. return {
  13768. refreshFogUniforms: refreshFogUniforms,
  13769. refreshMaterialUniforms: refreshMaterialUniforms
  13770. };
  13771. }
  13772. function createCanvasElement() {
  13773. const canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  13774. canvas.style.display = 'block';
  13775. return canvas;
  13776. }
  13777. function WebGLRenderer( parameters ) {
  13778. parameters = parameters || {};
  13779. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  13780. _context = parameters.context !== undefined ? parameters.context : null,
  13781. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  13782. _depth = parameters.depth !== undefined ? parameters.depth : true,
  13783. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  13784. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  13785. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  13786. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  13787. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  13788. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  13789. let currentRenderList = null;
  13790. let currentRenderState = null;
  13791. // render() can be called from within a callback triggered by another render.
  13792. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  13793. const renderListStack = [];
  13794. const renderStateStack = [];
  13795. // public properties
  13796. this.domElement = _canvas;
  13797. // Debug configuration container
  13798. this.debug = {
  13799. /**
  13800. * Enables error checking and reporting when shader programs are being compiled
  13801. * @type {boolean}
  13802. */
  13803. checkShaderErrors: true
  13804. };
  13805. // clearing
  13806. this.autoClear = true;
  13807. this.autoClearColor = true;
  13808. this.autoClearDepth = true;
  13809. this.autoClearStencil = true;
  13810. // scene graph
  13811. this.sortObjects = true;
  13812. // user-defined clipping
  13813. this.clippingPlanes = [];
  13814. this.localClippingEnabled = false;
  13815. // physically based shading
  13816. this.gammaFactor = 2.0; // for backwards compatibility
  13817. this.outputEncoding = LinearEncoding;
  13818. // physical lights
  13819. this.physicallyCorrectLights = false;
  13820. // tone mapping
  13821. this.toneMapping = NoToneMapping;
  13822. this.toneMappingExposure = 1.0;
  13823. // morphs
  13824. this.maxMorphTargets = 8;
  13825. this.maxMorphNormals = 4;
  13826. // internal properties
  13827. const _this = this;
  13828. let _isContextLost = false;
  13829. // internal state cache
  13830. let _currentActiveCubeFace = 0;
  13831. let _currentActiveMipmapLevel = 0;
  13832. let _currentRenderTarget = null;
  13833. let _currentMaterialId = - 1;
  13834. let _currentCamera = null;
  13835. const _currentViewport = new Vector4();
  13836. const _currentScissor = new Vector4();
  13837. let _currentScissorTest = null;
  13838. //
  13839. let _width = _canvas.width;
  13840. let _height = _canvas.height;
  13841. let _pixelRatio = 1;
  13842. let _opaqueSort = null;
  13843. let _transparentSort = null;
  13844. const _viewport = new Vector4( 0, 0, _width, _height );
  13845. const _scissor = new Vector4( 0, 0, _width, _height );
  13846. let _scissorTest = false;
  13847. // frustum
  13848. const _frustum = new Frustum();
  13849. // clipping
  13850. let _clippingEnabled = false;
  13851. let _localClippingEnabled = false;
  13852. // camera matrices cache
  13853. const _projScreenMatrix = new Matrix4();
  13854. const _vector3 = new Vector3();
  13855. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  13856. function getTargetPixelRatio() {
  13857. return _currentRenderTarget === null ? _pixelRatio : 1;
  13858. }
  13859. // initialize
  13860. let _gl = _context;
  13861. function getContext( contextNames, contextAttributes ) {
  13862. for ( let i = 0; i < contextNames.length; i ++ ) {
  13863. const contextName = contextNames[ i ];
  13864. const context = _canvas.getContext( contextName, contextAttributes );
  13865. if ( context !== null ) return context;
  13866. }
  13867. return null;
  13868. }
  13869. try {
  13870. const contextAttributes = {
  13871. alpha: _alpha,
  13872. depth: _depth,
  13873. stencil: _stencil,
  13874. antialias: _antialias,
  13875. premultipliedAlpha: _premultipliedAlpha,
  13876. preserveDrawingBuffer: _preserveDrawingBuffer,
  13877. powerPreference: _powerPreference,
  13878. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  13879. };
  13880. // event listeners must be registered before WebGL context is created, see #12753
  13881. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  13882. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  13883. if ( _gl === null ) {
  13884. const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ];
  13885. if ( _this.isWebGL1Renderer === true ) {
  13886. contextNames.shift();
  13887. }
  13888. _gl = getContext( contextNames, contextAttributes );
  13889. if ( _gl === null ) {
  13890. if ( getContext( contextNames ) ) {
  13891. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  13892. } else {
  13893. throw new Error( 'Error creating WebGL context.' );
  13894. }
  13895. }
  13896. }
  13897. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  13898. if ( _gl.getShaderPrecisionFormat === undefined ) {
  13899. _gl.getShaderPrecisionFormat = function () {
  13900. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  13901. };
  13902. }
  13903. } catch ( error ) {
  13904. console.error( 'THREE.WebGLRenderer: ' + error.message );
  13905. throw error;
  13906. }
  13907. let extensions, capabilities, state, info;
  13908. let properties, textures, cubemaps, attributes, geometries, objects;
  13909. let programCache, materials, renderLists, renderStates, clipping;
  13910. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  13911. let utils, bindingStates;
  13912. function initGLContext() {
  13913. extensions = new WebGLExtensions( _gl );
  13914. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  13915. extensions.init( capabilities );
  13916. utils = new WebGLUtils( _gl, extensions, capabilities );
  13917. state = new WebGLState( _gl, extensions, capabilities );
  13918. info = new WebGLInfo( _gl );
  13919. properties = new WebGLProperties();
  13920. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  13921. cubemaps = new WebGLCubeMaps( _this );
  13922. attributes = new WebGLAttributes( _gl, capabilities );
  13923. bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities );
  13924. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  13925. objects = new WebGLObjects( _gl, geometries, attributes, info );
  13926. morphtargets = new WebGLMorphtargets( _gl );
  13927. clipping = new WebGLClipping( properties );
  13928. programCache = new WebGLPrograms( _this, cubemaps, extensions, capabilities, bindingStates, clipping );
  13929. materials = new WebGLMaterials( properties );
  13930. renderLists = new WebGLRenderLists( properties );
  13931. renderStates = new WebGLRenderStates( extensions, capabilities );
  13932. background = new WebGLBackground( _this, cubemaps, state, objects, _premultipliedAlpha );
  13933. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  13934. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  13935. info.programs = programCache.programs;
  13936. _this.capabilities = capabilities;
  13937. _this.extensions = extensions;
  13938. _this.properties = properties;
  13939. _this.renderLists = renderLists;
  13940. _this.state = state;
  13941. _this.info = info;
  13942. }
  13943. initGLContext();
  13944. // xr
  13945. const xr = new WebXRManager( _this, _gl );
  13946. this.xr = xr;
  13947. // shadow map
  13948. const shadowMap = new WebGLShadowMap( _this, objects, capabilities.maxTextureSize );
  13949. this.shadowMap = shadowMap;
  13950. // API
  13951. this.getContext = function () {
  13952. return _gl;
  13953. };
  13954. this.getContextAttributes = function () {
  13955. return _gl.getContextAttributes();
  13956. };
  13957. this.forceContextLoss = function () {
  13958. const extension = extensions.get( 'WEBGL_lose_context' );
  13959. if ( extension ) extension.loseContext();
  13960. };
  13961. this.forceContextRestore = function () {
  13962. const extension = extensions.get( 'WEBGL_lose_context' );
  13963. if ( extension ) extension.restoreContext();
  13964. };
  13965. this.getPixelRatio = function () {
  13966. return _pixelRatio;
  13967. };
  13968. this.setPixelRatio = function ( value ) {
  13969. if ( value === undefined ) return;
  13970. _pixelRatio = value;
  13971. this.setSize( _width, _height, false );
  13972. };
  13973. this.getSize = function ( target ) {
  13974. if ( target === undefined ) {
  13975. console.warn( 'WebGLRenderer: .getsize() now requires a Vector2 as an argument' );
  13976. target = new Vector2();
  13977. }
  13978. return target.set( _width, _height );
  13979. };
  13980. this.setSize = function ( width, height, updateStyle ) {
  13981. if ( xr.isPresenting ) {
  13982. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  13983. return;
  13984. }
  13985. _width = width;
  13986. _height = height;
  13987. _canvas.width = Math.floor( width * _pixelRatio );
  13988. _canvas.height = Math.floor( height * _pixelRatio );
  13989. if ( updateStyle !== false ) {
  13990. _canvas.style.width = width + 'px';
  13991. _canvas.style.height = height + 'px';
  13992. }
  13993. this.setViewport( 0, 0, width, height );
  13994. };
  13995. this.getDrawingBufferSize = function ( target ) {
  13996. if ( target === undefined ) {
  13997. console.warn( 'WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument' );
  13998. target = new Vector2();
  13999. }
  14000. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  14001. };
  14002. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  14003. _width = width;
  14004. _height = height;
  14005. _pixelRatio = pixelRatio;
  14006. _canvas.width = Math.floor( width * pixelRatio );
  14007. _canvas.height = Math.floor( height * pixelRatio );
  14008. this.setViewport( 0, 0, width, height );
  14009. };
  14010. this.getCurrentViewport = function ( target ) {
  14011. if ( target === undefined ) {
  14012. console.warn( 'WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument' );
  14013. target = new Vector4();
  14014. }
  14015. return target.copy( _currentViewport );
  14016. };
  14017. this.getViewport = function ( target ) {
  14018. return target.copy( _viewport );
  14019. };
  14020. this.setViewport = function ( x, y, width, height ) {
  14021. if ( x.isVector4 ) {
  14022. _viewport.set( x.x, x.y, x.z, x.w );
  14023. } else {
  14024. _viewport.set( x, y, width, height );
  14025. }
  14026. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  14027. };
  14028. this.getScissor = function ( target ) {
  14029. return target.copy( _scissor );
  14030. };
  14031. this.setScissor = function ( x, y, width, height ) {
  14032. if ( x.isVector4 ) {
  14033. _scissor.set( x.x, x.y, x.z, x.w );
  14034. } else {
  14035. _scissor.set( x, y, width, height );
  14036. }
  14037. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  14038. };
  14039. this.getScissorTest = function () {
  14040. return _scissorTest;
  14041. };
  14042. this.setScissorTest = function ( boolean ) {
  14043. state.setScissorTest( _scissorTest = boolean );
  14044. };
  14045. this.setOpaqueSort = function ( method ) {
  14046. _opaqueSort = method;
  14047. };
  14048. this.setTransparentSort = function ( method ) {
  14049. _transparentSort = method;
  14050. };
  14051. // Clearing
  14052. this.getClearColor = function ( target ) {
  14053. if ( target === undefined ) {
  14054. console.warn( 'WebGLRenderer: .getClearColor() now requires a Color as an argument' );
  14055. target = new Color();
  14056. }
  14057. return target.copy( background.getClearColor() );
  14058. };
  14059. this.setClearColor = function () {
  14060. background.setClearColor.apply( background, arguments );
  14061. };
  14062. this.getClearAlpha = function () {
  14063. return background.getClearAlpha();
  14064. };
  14065. this.setClearAlpha = function () {
  14066. background.setClearAlpha.apply( background, arguments );
  14067. };
  14068. this.clear = function ( color, depth, stencil ) {
  14069. let bits = 0;
  14070. if ( color === undefined || color ) bits |= 16384;
  14071. if ( depth === undefined || depth ) bits |= 256;
  14072. if ( stencil === undefined || stencil ) bits |= 1024;
  14073. _gl.clear( bits );
  14074. };
  14075. this.clearColor = function () {
  14076. this.clear( true, false, false );
  14077. };
  14078. this.clearDepth = function () {
  14079. this.clear( false, true, false );
  14080. };
  14081. this.clearStencil = function () {
  14082. this.clear( false, false, true );
  14083. };
  14084. //
  14085. this.dispose = function () {
  14086. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  14087. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  14088. renderLists.dispose();
  14089. renderStates.dispose();
  14090. properties.dispose();
  14091. cubemaps.dispose();
  14092. objects.dispose();
  14093. bindingStates.dispose();
  14094. xr.dispose();
  14095. animation.stop();
  14096. };
  14097. // Events
  14098. function onContextLost( event ) {
  14099. event.preventDefault();
  14100. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  14101. _isContextLost = true;
  14102. }
  14103. function onContextRestore( /* event */ ) {
  14104. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  14105. _isContextLost = false;
  14106. initGLContext();
  14107. }
  14108. function onMaterialDispose( event ) {
  14109. const material = event.target;
  14110. material.removeEventListener( 'dispose', onMaterialDispose );
  14111. deallocateMaterial( material );
  14112. }
  14113. // Buffer deallocation
  14114. function deallocateMaterial( material ) {
  14115. releaseMaterialProgramReferences( material );
  14116. properties.remove( material );
  14117. }
  14118. function releaseMaterialProgramReferences( material ) {
  14119. const programs = properties.get( material ).programs;
  14120. if ( programs !== undefined ) {
  14121. programs.forEach( function ( program ) {
  14122. programCache.releaseProgram( program );
  14123. } );
  14124. }
  14125. }
  14126. // Buffer rendering
  14127. function renderObjectImmediate( object, program ) {
  14128. object.render( function ( object ) {
  14129. _this.renderBufferImmediate( object, program );
  14130. } );
  14131. }
  14132. this.renderBufferImmediate = function ( object, program ) {
  14133. bindingStates.initAttributes();
  14134. const buffers = properties.get( object );
  14135. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  14136. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  14137. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  14138. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  14139. const programAttributes = program.getAttributes();
  14140. if ( object.hasPositions ) {
  14141. _gl.bindBuffer( 34962, buffers.position );
  14142. _gl.bufferData( 34962, object.positionArray, 35048 );
  14143. bindingStates.enableAttribute( programAttributes.position );
  14144. _gl.vertexAttribPointer( programAttributes.position, 3, 5126, false, 0, 0 );
  14145. }
  14146. if ( object.hasNormals ) {
  14147. _gl.bindBuffer( 34962, buffers.normal );
  14148. _gl.bufferData( 34962, object.normalArray, 35048 );
  14149. bindingStates.enableAttribute( programAttributes.normal );
  14150. _gl.vertexAttribPointer( programAttributes.normal, 3, 5126, false, 0, 0 );
  14151. }
  14152. if ( object.hasUvs ) {
  14153. _gl.bindBuffer( 34962, buffers.uv );
  14154. _gl.bufferData( 34962, object.uvArray, 35048 );
  14155. bindingStates.enableAttribute( programAttributes.uv );
  14156. _gl.vertexAttribPointer( programAttributes.uv, 2, 5126, false, 0, 0 );
  14157. }
  14158. if ( object.hasColors ) {
  14159. _gl.bindBuffer( 34962, buffers.color );
  14160. _gl.bufferData( 34962, object.colorArray, 35048 );
  14161. bindingStates.enableAttribute( programAttributes.color );
  14162. _gl.vertexAttribPointer( programAttributes.color, 3, 5126, false, 0, 0 );
  14163. }
  14164. bindingStates.disableUnusedAttributes();
  14165. _gl.drawArrays( 4, 0, object.count );
  14166. object.count = 0;
  14167. };
  14168. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  14169. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  14170. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  14171. const program = setProgram( camera, scene, material, object );
  14172. state.setMaterial( material, frontFaceCW );
  14173. //
  14174. let index = geometry.index;
  14175. const position = geometry.attributes.position;
  14176. //
  14177. if ( index === null ) {
  14178. if ( position === undefined || position.count === 0 ) return;
  14179. } else if ( index.count === 0 ) {
  14180. return;
  14181. }
  14182. //
  14183. let rangeFactor = 1;
  14184. if ( material.wireframe === true ) {
  14185. index = geometries.getWireframeAttribute( geometry );
  14186. rangeFactor = 2;
  14187. }
  14188. if ( material.morphTargets || material.morphNormals ) {
  14189. morphtargets.update( object, geometry, material, program );
  14190. }
  14191. bindingStates.setup( object, material, program, geometry, index );
  14192. let attribute;
  14193. let renderer = bufferRenderer;
  14194. if ( index !== null ) {
  14195. attribute = attributes.get( index );
  14196. renderer = indexedBufferRenderer;
  14197. renderer.setIndex( attribute );
  14198. }
  14199. //
  14200. const dataCount = ( index !== null ) ? index.count : position.count;
  14201. const rangeStart = geometry.drawRange.start * rangeFactor;
  14202. const rangeCount = geometry.drawRange.count * rangeFactor;
  14203. const groupStart = group !== null ? group.start * rangeFactor : 0;
  14204. const groupCount = group !== null ? group.count * rangeFactor : Infinity;
  14205. const drawStart = Math.max( rangeStart, groupStart );
  14206. const drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  14207. const drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  14208. if ( drawCount === 0 ) return;
  14209. //
  14210. if ( object.isMesh ) {
  14211. if ( material.wireframe === true ) {
  14212. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  14213. renderer.setMode( 1 );
  14214. } else {
  14215. renderer.setMode( 4 );
  14216. }
  14217. } else if ( object.isLine ) {
  14218. let lineWidth = material.linewidth;
  14219. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  14220. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  14221. if ( object.isLineSegments ) {
  14222. renderer.setMode( 1 );
  14223. } else if ( object.isLineLoop ) {
  14224. renderer.setMode( 2 );
  14225. } else {
  14226. renderer.setMode( 3 );
  14227. }
  14228. } else if ( object.isPoints ) {
  14229. renderer.setMode( 0 );
  14230. } else if ( object.isSprite ) {
  14231. renderer.setMode( 4 );
  14232. }
  14233. if ( object.isInstancedMesh ) {
  14234. renderer.renderInstances( drawStart, drawCount, object.count );
  14235. } else if ( geometry.isInstancedBufferGeometry ) {
  14236. const instanceCount = Math.min( geometry.instanceCount, geometry._maxInstanceCount );
  14237. renderer.renderInstances( drawStart, drawCount, instanceCount );
  14238. } else {
  14239. renderer.render( drawStart, drawCount );
  14240. }
  14241. };
  14242. // Compile
  14243. this.compile = function ( scene, camera ) {
  14244. currentRenderState = renderStates.get( scene );
  14245. currentRenderState.init();
  14246. scene.traverseVisible( function ( object ) {
  14247. if ( object.isLight && object.layers.test( camera.layers ) ) {
  14248. currentRenderState.pushLight( object );
  14249. if ( object.castShadow ) {
  14250. currentRenderState.pushShadow( object );
  14251. }
  14252. }
  14253. } );
  14254. currentRenderState.setupLights();
  14255. scene.traverse( function ( object ) {
  14256. const material = object.material;
  14257. if ( material ) {
  14258. if ( Array.isArray( material ) ) {
  14259. for ( let i = 0; i < material.length; i ++ ) {
  14260. const material2 = material[ i ];
  14261. getProgram( material2, scene, object );
  14262. }
  14263. } else {
  14264. getProgram( material, scene, object );
  14265. }
  14266. }
  14267. } );
  14268. };
  14269. // Animation Loop
  14270. let onAnimationFrameCallback = null;
  14271. function onAnimationFrame( time ) {
  14272. if ( xr.isPresenting ) return;
  14273. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  14274. }
  14275. const animation = new WebGLAnimation();
  14276. animation.setAnimationLoop( onAnimationFrame );
  14277. if ( typeof window !== 'undefined' ) animation.setContext( window );
  14278. this.setAnimationLoop = function ( callback ) {
  14279. onAnimationFrameCallback = callback;
  14280. xr.setAnimationLoop( callback );
  14281. ( callback === null ) ? animation.stop() : animation.start();
  14282. };
  14283. // Rendering
  14284. this.render = function ( scene, camera ) {
  14285. let renderTarget, forceClear;
  14286. if ( arguments[ 2 ] !== undefined ) {
  14287. console.warn( 'THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.' );
  14288. renderTarget = arguments[ 2 ];
  14289. }
  14290. if ( arguments[ 3 ] !== undefined ) {
  14291. console.warn( 'THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.' );
  14292. forceClear = arguments[ 3 ];
  14293. }
  14294. if ( camera !== undefined && camera.isCamera !== true ) {
  14295. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  14296. return;
  14297. }
  14298. if ( _isContextLost === true ) return;
  14299. // reset caching for this frame
  14300. bindingStates.resetDefaultState();
  14301. _currentMaterialId = - 1;
  14302. _currentCamera = null;
  14303. // update scene graph
  14304. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  14305. // update camera matrices and frustum
  14306. if ( camera.parent === null ) camera.updateMatrixWorld();
  14307. if ( xr.enabled === true && xr.isPresenting === true ) {
  14308. camera = xr.getCamera( camera );
  14309. }
  14310. //
  14311. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, renderTarget || _currentRenderTarget );
  14312. currentRenderState = renderStates.get( scene, renderStateStack.length );
  14313. currentRenderState.init();
  14314. renderStateStack.push( currentRenderState );
  14315. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  14316. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  14317. _localClippingEnabled = this.localClippingEnabled;
  14318. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  14319. currentRenderList = renderLists.get( scene, renderListStack.length );
  14320. currentRenderList.init();
  14321. renderListStack.push( currentRenderList );
  14322. projectObject( scene, camera, 0, _this.sortObjects );
  14323. currentRenderList.finish();
  14324. if ( _this.sortObjects === true ) {
  14325. currentRenderList.sort( _opaqueSort, _transparentSort );
  14326. }
  14327. //
  14328. if ( _clippingEnabled === true ) clipping.beginShadows();
  14329. const shadowsArray = currentRenderState.state.shadowsArray;
  14330. shadowMap.render( shadowsArray, scene, camera );
  14331. currentRenderState.setupLights();
  14332. currentRenderState.setupLightsView( camera );
  14333. if ( _clippingEnabled === true ) clipping.endShadows();
  14334. //
  14335. if ( this.info.autoReset === true ) this.info.reset();
  14336. if ( renderTarget !== undefined ) {
  14337. this.setRenderTarget( renderTarget );
  14338. }
  14339. //
  14340. background.render( currentRenderList, scene, camera, forceClear );
  14341. // render scene
  14342. const opaqueObjects = currentRenderList.opaque;
  14343. const transparentObjects = currentRenderList.transparent;
  14344. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  14345. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  14346. //
  14347. if ( _currentRenderTarget !== null ) {
  14348. // Generate mipmap if we're using any kind of mipmap filtering
  14349. textures.updateRenderTargetMipmap( _currentRenderTarget );
  14350. // resolve multisample renderbuffers to a single-sample texture if necessary
  14351. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  14352. }
  14353. //
  14354. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  14355. // Ensure depth buffer writing is enabled so it can be cleared on next render
  14356. state.buffers.depth.setTest( true );
  14357. state.buffers.depth.setMask( true );
  14358. state.buffers.color.setMask( true );
  14359. state.setPolygonOffset( false );
  14360. // _gl.finish();
  14361. renderStateStack.pop();
  14362. if ( renderStateStack.length > 0 ) {
  14363. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  14364. } else {
  14365. currentRenderState = null;
  14366. }
  14367. renderListStack.pop();
  14368. if ( renderListStack.length > 0 ) {
  14369. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  14370. } else {
  14371. currentRenderList = null;
  14372. }
  14373. };
  14374. function projectObject( object, camera, groupOrder, sortObjects ) {
  14375. if ( object.visible === false ) return;
  14376. const visible = object.layers.test( camera.layers );
  14377. if ( visible ) {
  14378. if ( object.isGroup ) {
  14379. groupOrder = object.renderOrder;
  14380. } else if ( object.isLOD ) {
  14381. if ( object.autoUpdate === true ) object.update( camera );
  14382. } else if ( object.isLight ) {
  14383. currentRenderState.pushLight( object );
  14384. if ( object.castShadow ) {
  14385. currentRenderState.pushShadow( object );
  14386. }
  14387. } else if ( object.isSprite ) {
  14388. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  14389. if ( sortObjects ) {
  14390. _vector3.setFromMatrixPosition( object.matrixWorld )
  14391. .applyMatrix4( _projScreenMatrix );
  14392. }
  14393. const geometry = objects.update( object );
  14394. const material = object.material;
  14395. if ( material.visible ) {
  14396. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  14397. }
  14398. }
  14399. } else if ( object.isImmediateRenderObject ) {
  14400. if ( sortObjects ) {
  14401. _vector3.setFromMatrixPosition( object.matrixWorld )
  14402. .applyMatrix4( _projScreenMatrix );
  14403. }
  14404. currentRenderList.push( object, null, object.material, groupOrder, _vector3.z, null );
  14405. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  14406. if ( object.isSkinnedMesh ) {
  14407. // update skeleton only once in a frame
  14408. if ( object.skeleton.frame !== info.render.frame ) {
  14409. object.skeleton.update();
  14410. object.skeleton.frame = info.render.frame;
  14411. }
  14412. }
  14413. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  14414. if ( sortObjects ) {
  14415. _vector3.setFromMatrixPosition( object.matrixWorld )
  14416. .applyMatrix4( _projScreenMatrix );
  14417. }
  14418. const geometry = objects.update( object );
  14419. const material = object.material;
  14420. if ( Array.isArray( material ) ) {
  14421. const groups = geometry.groups;
  14422. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  14423. const group = groups[ i ];
  14424. const groupMaterial = material[ group.materialIndex ];
  14425. if ( groupMaterial && groupMaterial.visible ) {
  14426. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  14427. }
  14428. }
  14429. } else if ( material.visible ) {
  14430. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  14431. }
  14432. }
  14433. }
  14434. }
  14435. const children = object.children;
  14436. for ( let i = 0, l = children.length; i < l; i ++ ) {
  14437. projectObject( children[ i ], camera, groupOrder, sortObjects );
  14438. }
  14439. }
  14440. function renderObjects( renderList, scene, camera ) {
  14441. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  14442. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  14443. const renderItem = renderList[ i ];
  14444. const object = renderItem.object;
  14445. const geometry = renderItem.geometry;
  14446. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  14447. const group = renderItem.group;
  14448. if ( camera.isArrayCamera ) {
  14449. const cameras = camera.cameras;
  14450. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  14451. const camera2 = cameras[ j ];
  14452. if ( object.layers.test( camera2.layers ) ) {
  14453. state.viewport( _currentViewport.copy( camera2.viewport ) );
  14454. currentRenderState.setupLightsView( camera2 );
  14455. renderObject( object, scene, camera2, geometry, material, group );
  14456. }
  14457. }
  14458. } else {
  14459. renderObject( object, scene, camera, geometry, material, group );
  14460. }
  14461. }
  14462. }
  14463. function renderObject( object, scene, camera, geometry, material, group ) {
  14464. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  14465. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  14466. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  14467. if ( object.isImmediateRenderObject ) {
  14468. const program = setProgram( camera, scene, material, object );
  14469. state.setMaterial( material );
  14470. bindingStates.reset();
  14471. renderObjectImmediate( object, program );
  14472. } else {
  14473. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  14474. }
  14475. object.onAfterRender( _this, scene, camera, geometry, material, group );
  14476. }
  14477. function getProgram( material, scene, object ) {
  14478. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  14479. const materialProperties = properties.get( material );
  14480. const lights = currentRenderState.state.lights;
  14481. const shadowsArray = currentRenderState.state.shadowsArray;
  14482. const lightsStateVersion = lights.state.version;
  14483. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  14484. const programCacheKey = programCache.getProgramCacheKey( parameters );
  14485. let programs = materialProperties.programs;
  14486. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  14487. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  14488. materialProperties.fog = scene.fog;
  14489. materialProperties.envMap = cubemaps.get( material.envMap || materialProperties.environment );
  14490. if ( programs === undefined ) {
  14491. // new material
  14492. material.addEventListener( 'dispose', onMaterialDispose );
  14493. programs = new Map();
  14494. materialProperties.programs = programs;
  14495. }
  14496. let program = programs.get( programCacheKey );
  14497. if ( program !== undefined ) {
  14498. // early out if program and light state is identical
  14499. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  14500. updateCommonMaterialProperties( material, parameters );
  14501. return program;
  14502. }
  14503. } else {
  14504. parameters.uniforms = programCache.getUniforms( material );
  14505. material.onBeforeCompile( parameters, _this );
  14506. program = programCache.acquireProgram( parameters, programCacheKey );
  14507. programs.set( programCacheKey, program );
  14508. materialProperties.uniforms = parameters.uniforms;
  14509. }
  14510. const uniforms = materialProperties.uniforms;
  14511. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  14512. uniforms.clippingPlanes = clipping.uniform;
  14513. }
  14514. updateCommonMaterialProperties( material, parameters );
  14515. // store the light setup it was created for
  14516. materialProperties.needsLights = materialNeedsLights( material );
  14517. materialProperties.lightsStateVersion = lightsStateVersion;
  14518. if ( materialProperties.needsLights ) {
  14519. // wire up the material to this renderer's lighting state
  14520. uniforms.ambientLightColor.value = lights.state.ambient;
  14521. uniforms.lightProbe.value = lights.state.probe;
  14522. uniforms.directionalLights.value = lights.state.directional;
  14523. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  14524. uniforms.spotLights.value = lights.state.spot;
  14525. uniforms.spotLightShadows.value = lights.state.spotShadow;
  14526. uniforms.rectAreaLights.value = lights.state.rectArea;
  14527. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  14528. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  14529. uniforms.pointLights.value = lights.state.point;
  14530. uniforms.pointLightShadows.value = lights.state.pointShadow;
  14531. uniforms.hemisphereLights.value = lights.state.hemi;
  14532. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  14533. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  14534. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  14535. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  14536. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  14537. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  14538. // TODO (abelnation): add area lights shadow info to uniforms
  14539. }
  14540. const progUniforms = program.getUniforms();
  14541. const uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  14542. materialProperties.currentProgram = program;
  14543. materialProperties.uniformsList = uniformsList;
  14544. return program;
  14545. }
  14546. function updateCommonMaterialProperties( material, parameters ) {
  14547. const materialProperties = properties.get( material );
  14548. materialProperties.outputEncoding = parameters.outputEncoding;
  14549. materialProperties.instancing = parameters.instancing;
  14550. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  14551. materialProperties.numIntersection = parameters.numClipIntersection;
  14552. }
  14553. function setProgram( camera, scene, material, object ) {
  14554. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  14555. textures.resetTextureUnits();
  14556. const fog = scene.fog;
  14557. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  14558. const encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : _currentRenderTarget.texture.encoding;
  14559. const envMap = cubemaps.get( material.envMap || environment );
  14560. const materialProperties = properties.get( material );
  14561. const lights = currentRenderState.state.lights;
  14562. if ( _clippingEnabled === true ) {
  14563. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  14564. const useCache =
  14565. camera === _currentCamera &&
  14566. material.id === _currentMaterialId;
  14567. // we might want to call this function with some ClippingGroup
  14568. // object instead of the material, once it becomes feasible
  14569. // (#8465, #8379)
  14570. clipping.setState( material, camera, useCache );
  14571. }
  14572. }
  14573. //
  14574. let needsProgramChange = false;
  14575. if ( material.version === materialProperties.__version ) {
  14576. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  14577. needsProgramChange = true;
  14578. } else if ( materialProperties.outputEncoding !== encoding ) {
  14579. needsProgramChange = true;
  14580. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  14581. needsProgramChange = true;
  14582. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  14583. needsProgramChange = true;
  14584. } else if ( materialProperties.envMap !== envMap ) {
  14585. needsProgramChange = true;
  14586. } else if ( material.fog && materialProperties.fog !== fog ) {
  14587. needsProgramChange = true;
  14588. } else if ( materialProperties.numClippingPlanes !== undefined &&
  14589. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  14590. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  14591. needsProgramChange = true;
  14592. }
  14593. } else {
  14594. needsProgramChange = true;
  14595. materialProperties.__version = material.version;
  14596. }
  14597. //
  14598. let program = materialProperties.currentProgram;
  14599. if ( needsProgramChange === true ) {
  14600. program = getProgram( material, scene, object );
  14601. }
  14602. let refreshProgram = false;
  14603. let refreshMaterial = false;
  14604. let refreshLights = false;
  14605. const p_uniforms = program.getUniforms(),
  14606. m_uniforms = materialProperties.uniforms;
  14607. if ( state.useProgram( program.program ) ) {
  14608. refreshProgram = true;
  14609. refreshMaterial = true;
  14610. refreshLights = true;
  14611. }
  14612. if ( material.id !== _currentMaterialId ) {
  14613. _currentMaterialId = material.id;
  14614. refreshMaterial = true;
  14615. }
  14616. if ( refreshProgram || _currentCamera !== camera ) {
  14617. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  14618. if ( capabilities.logarithmicDepthBuffer ) {
  14619. p_uniforms.setValue( _gl, 'logDepthBufFC',
  14620. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  14621. }
  14622. if ( _currentCamera !== camera ) {
  14623. _currentCamera = camera;
  14624. // lighting uniforms depend on the camera so enforce an update
  14625. // now, in case this material supports lights - or later, when
  14626. // the next material that does gets activated:
  14627. refreshMaterial = true; // set to true on material change
  14628. refreshLights = true; // remains set until update done
  14629. }
  14630. // load material specific uniforms
  14631. // (shader material also gets them for the sake of genericity)
  14632. if ( material.isShaderMaterial ||
  14633. material.isMeshPhongMaterial ||
  14634. material.isMeshToonMaterial ||
  14635. material.isMeshStandardMaterial ||
  14636. material.envMap ) {
  14637. const uCamPos = p_uniforms.map.cameraPosition;
  14638. if ( uCamPos !== undefined ) {
  14639. uCamPos.setValue( _gl,
  14640. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  14641. }
  14642. }
  14643. if ( material.isMeshPhongMaterial ||
  14644. material.isMeshToonMaterial ||
  14645. material.isMeshLambertMaterial ||
  14646. material.isMeshBasicMaterial ||
  14647. material.isMeshStandardMaterial ||
  14648. material.isShaderMaterial ) {
  14649. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  14650. }
  14651. if ( material.isMeshPhongMaterial ||
  14652. material.isMeshToonMaterial ||
  14653. material.isMeshLambertMaterial ||
  14654. material.isMeshBasicMaterial ||
  14655. material.isMeshStandardMaterial ||
  14656. material.isShaderMaterial ||
  14657. material.isShadowMaterial ||
  14658. material.skinning ) {
  14659. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  14660. }
  14661. }
  14662. // skinning uniforms must be set even if material didn't change
  14663. // auto-setting of texture unit for bone texture must go before other textures
  14664. // otherwise textures used for skinning can take over texture units reserved for other material textures
  14665. if ( material.skinning ) {
  14666. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  14667. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  14668. const skeleton = object.skeleton;
  14669. if ( skeleton ) {
  14670. const bones = skeleton.bones;
  14671. if ( capabilities.floatVertexTextures ) {
  14672. if ( skeleton.boneTexture === null ) {
  14673. // layout (1 matrix = 4 pixels)
  14674. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  14675. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  14676. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  14677. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  14678. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  14679. let size = Math.sqrt( bones.length * 4 ); // 4 pixels needed for 1 matrix
  14680. size = MathUtils.ceilPowerOfTwo( size );
  14681. size = Math.max( size, 4 );
  14682. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  14683. boneMatrices.set( skeleton.boneMatrices ); // copy current values
  14684. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  14685. skeleton.boneMatrices = boneMatrices;
  14686. skeleton.boneTexture = boneTexture;
  14687. skeleton.boneTextureSize = size;
  14688. }
  14689. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  14690. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  14691. } else {
  14692. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  14693. }
  14694. }
  14695. }
  14696. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  14697. materialProperties.receiveShadow = object.receiveShadow;
  14698. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  14699. }
  14700. if ( refreshMaterial ) {
  14701. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  14702. if ( materialProperties.needsLights ) {
  14703. // the current material requires lighting info
  14704. // note: all lighting uniforms are always set correctly
  14705. // they simply reference the renderer's state for their
  14706. // values
  14707. //
  14708. // use the current material's .needsUpdate flags to set
  14709. // the GL state when required
  14710. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  14711. }
  14712. // refresh uniforms common to several materials
  14713. if ( fog && material.fog ) {
  14714. materials.refreshFogUniforms( m_uniforms, fog );
  14715. }
  14716. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height );
  14717. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  14718. }
  14719. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  14720. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  14721. material.uniformsNeedUpdate = false;
  14722. }
  14723. if ( material.isSpriteMaterial ) {
  14724. p_uniforms.setValue( _gl, 'center', object.center );
  14725. }
  14726. // common matrices
  14727. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  14728. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  14729. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  14730. return program;
  14731. }
  14732. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  14733. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  14734. uniforms.ambientLightColor.needsUpdate = value;
  14735. uniforms.lightProbe.needsUpdate = value;
  14736. uniforms.directionalLights.needsUpdate = value;
  14737. uniforms.directionalLightShadows.needsUpdate = value;
  14738. uniforms.pointLights.needsUpdate = value;
  14739. uniforms.pointLightShadows.needsUpdate = value;
  14740. uniforms.spotLights.needsUpdate = value;
  14741. uniforms.spotLightShadows.needsUpdate = value;
  14742. uniforms.rectAreaLights.needsUpdate = value;
  14743. uniforms.hemisphereLights.needsUpdate = value;
  14744. }
  14745. function materialNeedsLights( material ) {
  14746. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  14747. material.isMeshStandardMaterial || material.isShadowMaterial ||
  14748. ( material.isShaderMaterial && material.lights === true );
  14749. }
  14750. this.getActiveCubeFace = function () {
  14751. return _currentActiveCubeFace;
  14752. };
  14753. this.getActiveMipmapLevel = function () {
  14754. return _currentActiveMipmapLevel;
  14755. };
  14756. this.getRenderTarget = function () {
  14757. return _currentRenderTarget;
  14758. };
  14759. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  14760. _currentRenderTarget = renderTarget;
  14761. _currentActiveCubeFace = activeCubeFace;
  14762. _currentActiveMipmapLevel = activeMipmapLevel;
  14763. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  14764. textures.setupRenderTarget( renderTarget );
  14765. }
  14766. let framebuffer = null;
  14767. let isCube = false;
  14768. let isRenderTarget3D = false;
  14769. if ( renderTarget ) {
  14770. const texture = renderTarget.texture;
  14771. if ( texture.isDataTexture3D || texture.isDataTexture2DArray ) {
  14772. isRenderTarget3D = true;
  14773. }
  14774. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  14775. if ( renderTarget.isWebGLCubeRenderTarget ) {
  14776. framebuffer = __webglFramebuffer[ activeCubeFace ];
  14777. isCube = true;
  14778. } else if ( renderTarget.isWebGLMultisampleRenderTarget ) {
  14779. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  14780. } else {
  14781. framebuffer = __webglFramebuffer;
  14782. }
  14783. _currentViewport.copy( renderTarget.viewport );
  14784. _currentScissor.copy( renderTarget.scissor );
  14785. _currentScissorTest = renderTarget.scissorTest;
  14786. } else {
  14787. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  14788. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  14789. _currentScissorTest = _scissorTest;
  14790. }
  14791. state.bindFramebuffer( 36160, framebuffer );
  14792. state.viewport( _currentViewport );
  14793. state.scissor( _currentScissor );
  14794. state.setScissorTest( _currentScissorTest );
  14795. if ( isCube ) {
  14796. const textureProperties = properties.get( renderTarget.texture );
  14797. _gl.framebufferTexture2D( 36160, 36064, 34069 + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  14798. } else if ( isRenderTarget3D ) {
  14799. const textureProperties = properties.get( renderTarget.texture );
  14800. const layer = activeCubeFace || 0;
  14801. _gl.framebufferTextureLayer( 36160, 36064, textureProperties.__webglTexture, activeMipmapLevel || 0, layer );
  14802. }
  14803. };
  14804. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  14805. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  14806. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  14807. return;
  14808. }
  14809. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  14810. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  14811. framebuffer = framebuffer[ activeCubeFaceIndex ];
  14812. }
  14813. if ( framebuffer ) {
  14814. state.bindFramebuffer( 36160, framebuffer );
  14815. try {
  14816. const texture = renderTarget.texture;
  14817. const textureFormat = texture.format;
  14818. const textureType = texture.type;
  14819. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( 35739 ) ) {
  14820. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  14821. return;
  14822. }
  14823. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || ( capabilities.isWebGL2 && extensions.has( 'EXT_color_buffer_float' ) ) );
  14824. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( 35738 ) && // Edge and Chrome Mac < 52 (#9513)
  14825. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.has( 'OES_texture_float' ) || extensions.has( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  14826. ! halfFloatSupportedByExt ) {
  14827. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  14828. return;
  14829. }
  14830. if ( _gl.checkFramebufferStatus( 36160 ) === 36053 ) {
  14831. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  14832. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  14833. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  14834. }
  14835. } else {
  14836. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  14837. }
  14838. } finally {
  14839. // restore framebuffer of current render target if necessary
  14840. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  14841. state.bindFramebuffer( 36160, framebuffer );
  14842. }
  14843. }
  14844. };
  14845. this.copyFramebufferToTexture = function ( position, texture, level = 0 ) {
  14846. const levelScale = Math.pow( 2, - level );
  14847. const width = Math.floor( texture.image.width * levelScale );
  14848. const height = Math.floor( texture.image.height * levelScale );
  14849. const glFormat = utils.convert( texture.format );
  14850. textures.setTexture2D( texture, 0 );
  14851. _gl.copyTexImage2D( 3553, level, glFormat, position.x, position.y, width, height, 0 );
  14852. state.unbindTexture();
  14853. };
  14854. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) {
  14855. const width = srcTexture.image.width;
  14856. const height = srcTexture.image.height;
  14857. const glFormat = utils.convert( dstTexture.format );
  14858. const glType = utils.convert( dstTexture.type );
  14859. textures.setTexture2D( dstTexture, 0 );
  14860. // As another texture upload may have changed pixelStorei
  14861. // parameters, make sure they are correct for the dstTexture
  14862. _gl.pixelStorei( 37440, dstTexture.flipY );
  14863. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  14864. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  14865. if ( srcTexture.isDataTexture ) {
  14866. _gl.texSubImage2D( 3553, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  14867. } else {
  14868. if ( srcTexture.isCompressedTexture ) {
  14869. _gl.compressedTexSubImage2D( 3553, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data );
  14870. } else {
  14871. _gl.texSubImage2D( 3553, level, position.x, position.y, glFormat, glType, srcTexture.image );
  14872. }
  14873. }
  14874. // Generate mipmaps only when copying level 0
  14875. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( 3553 );
  14876. state.unbindTexture();
  14877. };
  14878. this.copyTextureToTexture3D = function ( sourceBox, position, srcTexture, dstTexture, level = 0 ) {
  14879. if ( _this.isWebGL1Renderer ) {
  14880. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.' );
  14881. return;
  14882. }
  14883. const { width, height, data } = srcTexture.image;
  14884. const glFormat = utils.convert( dstTexture.format );
  14885. const glType = utils.convert( dstTexture.type );
  14886. let glTarget;
  14887. if ( dstTexture.isDataTexture3D ) {
  14888. textures.setTexture3D( dstTexture, 0 );
  14889. glTarget = 32879;
  14890. } else if ( dstTexture.isDataTexture2DArray ) {
  14891. textures.setTexture2DArray( dstTexture, 0 );
  14892. glTarget = 35866;
  14893. } else {
  14894. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' );
  14895. return;
  14896. }
  14897. _gl.pixelStorei( 37440, dstTexture.flipY );
  14898. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  14899. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  14900. const unpackRowLen = _gl.getParameter( 3314 );
  14901. const unpackImageHeight = _gl.getParameter( 32878 );
  14902. const unpackSkipPixels = _gl.getParameter( 3316 );
  14903. const unpackSkipRows = _gl.getParameter( 3315 );
  14904. const unpackSkipImages = _gl.getParameter( 32877 );
  14905. _gl.pixelStorei( 3314, width );
  14906. _gl.pixelStorei( 32878, height );
  14907. _gl.pixelStorei( 3316, sourceBox.min.x );
  14908. _gl.pixelStorei( 3315, sourceBox.min.y );
  14909. _gl.pixelStorei( 32877, sourceBox.min.z );
  14910. _gl.texSubImage3D(
  14911. glTarget,
  14912. level,
  14913. position.x,
  14914. position.y,
  14915. position.z,
  14916. sourceBox.max.x - sourceBox.min.x + 1,
  14917. sourceBox.max.y - sourceBox.min.y + 1,
  14918. sourceBox.max.z - sourceBox.min.z + 1,
  14919. glFormat,
  14920. glType,
  14921. data
  14922. );
  14923. _gl.pixelStorei( 3314, unpackRowLen );
  14924. _gl.pixelStorei( 32878, unpackImageHeight );
  14925. _gl.pixelStorei( 3316, unpackSkipPixels );
  14926. _gl.pixelStorei( 3315, unpackSkipRows );
  14927. _gl.pixelStorei( 32877, unpackSkipImages );
  14928. // Generate mipmaps only when copying level 0
  14929. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget );
  14930. state.unbindTexture();
  14931. };
  14932. this.initTexture = function ( texture ) {
  14933. textures.setTexture2D( texture, 0 );
  14934. state.unbindTexture();
  14935. };
  14936. this.resetState = function () {
  14937. _currentActiveCubeFace = 0;
  14938. _currentActiveMipmapLevel = 0;
  14939. _currentRenderTarget = null;
  14940. state.reset();
  14941. bindingStates.reset();
  14942. };
  14943. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  14944. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef
  14945. }
  14946. }
  14947. class WebGL1Renderer extends WebGLRenderer {}
  14948. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  14949. class FogExp2 {
  14950. constructor( color, density ) {
  14951. this.name = '';
  14952. this.color = new Color( color );
  14953. this.density = ( density !== undefined ) ? density : 0.00025;
  14954. }
  14955. clone() {
  14956. return new FogExp2( this.color, this.density );
  14957. }
  14958. toJSON( /* meta */ ) {
  14959. return {
  14960. type: 'FogExp2',
  14961. color: this.color.getHex(),
  14962. density: this.density
  14963. };
  14964. }
  14965. }
  14966. FogExp2.prototype.isFogExp2 = true;
  14967. class Fog {
  14968. constructor( color, near, far ) {
  14969. this.name = '';
  14970. this.color = new Color( color );
  14971. this.near = ( near !== undefined ) ? near : 1;
  14972. this.far = ( far !== undefined ) ? far : 1000;
  14973. }
  14974. clone() {
  14975. return new Fog( this.color, this.near, this.far );
  14976. }
  14977. toJSON( /* meta */ ) {
  14978. return {
  14979. type: 'Fog',
  14980. color: this.color.getHex(),
  14981. near: this.near,
  14982. far: this.far
  14983. };
  14984. }
  14985. }
  14986. Fog.prototype.isFog = true;
  14987. class Scene extends Object3D {
  14988. constructor() {
  14989. super();
  14990. this.type = 'Scene';
  14991. this.background = null;
  14992. this.environment = null;
  14993. this.fog = null;
  14994. this.overrideMaterial = null;
  14995. this.autoUpdate = true; // checked by the renderer
  14996. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  14997. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef
  14998. }
  14999. }
  15000. copy( source, recursive ) {
  15001. super.copy( source, recursive );
  15002. if ( source.background !== null ) this.background = source.background.clone();
  15003. if ( source.environment !== null ) this.environment = source.environment.clone();
  15004. if ( source.fog !== null ) this.fog = source.fog.clone();
  15005. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  15006. this.autoUpdate = source.autoUpdate;
  15007. this.matrixAutoUpdate = source.matrixAutoUpdate;
  15008. return this;
  15009. }
  15010. toJSON( meta ) {
  15011. const data = super.toJSON( meta );
  15012. if ( this.background !== null ) data.object.background = this.background.toJSON( meta );
  15013. if ( this.environment !== null ) data.object.environment = this.environment.toJSON( meta );
  15014. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  15015. return data;
  15016. }
  15017. }
  15018. Scene.prototype.isScene = true;
  15019. function InterleavedBuffer( array, stride ) {
  15020. this.array = array;
  15021. this.stride = stride;
  15022. this.count = array !== undefined ? array.length / stride : 0;
  15023. this.usage = StaticDrawUsage;
  15024. this.updateRange = { offset: 0, count: - 1 };
  15025. this.version = 0;
  15026. this.uuid = MathUtils.generateUUID();
  15027. }
  15028. Object.defineProperty( InterleavedBuffer.prototype, 'needsUpdate', {
  15029. set: function ( value ) {
  15030. if ( value === true ) this.version ++;
  15031. }
  15032. } );
  15033. Object.assign( InterleavedBuffer.prototype, {
  15034. isInterleavedBuffer: true,
  15035. onUploadCallback: function () {},
  15036. setUsage: function ( value ) {
  15037. this.usage = value;
  15038. return this;
  15039. },
  15040. copy: function ( source ) {
  15041. this.array = new source.array.constructor( source.array );
  15042. this.count = source.count;
  15043. this.stride = source.stride;
  15044. this.usage = source.usage;
  15045. return this;
  15046. },
  15047. copyAt: function ( index1, attribute, index2 ) {
  15048. index1 *= this.stride;
  15049. index2 *= attribute.stride;
  15050. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  15051. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  15052. }
  15053. return this;
  15054. },
  15055. set: function ( value, offset = 0 ) {
  15056. this.array.set( value, offset );
  15057. return this;
  15058. },
  15059. clone: function ( data ) {
  15060. if ( data.arrayBuffers === undefined ) {
  15061. data.arrayBuffers = {};
  15062. }
  15063. if ( this.array.buffer._uuid === undefined ) {
  15064. this.array.buffer._uuid = MathUtils.generateUUID();
  15065. }
  15066. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  15067. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  15068. }
  15069. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  15070. const ib = new InterleavedBuffer( array, this.stride );
  15071. ib.setUsage( this.usage );
  15072. return ib;
  15073. },
  15074. onUpload: function ( callback ) {
  15075. this.onUploadCallback = callback;
  15076. return this;
  15077. },
  15078. toJSON: function ( data ) {
  15079. if ( data.arrayBuffers === undefined ) {
  15080. data.arrayBuffers = {};
  15081. }
  15082. // generate UUID for array buffer if necessary
  15083. if ( this.array.buffer._uuid === undefined ) {
  15084. this.array.buffer._uuid = MathUtils.generateUUID();
  15085. }
  15086. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  15087. data.arrayBuffers[ this.array.buffer._uuid ] = Array.prototype.slice.call( new Uint32Array( this.array.buffer ) );
  15088. }
  15089. //
  15090. return {
  15091. uuid: this.uuid,
  15092. buffer: this.array.buffer._uuid,
  15093. type: this.array.constructor.name,
  15094. stride: this.stride
  15095. };
  15096. }
  15097. } );
  15098. const _vector$6 = new Vector3();
  15099. function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) {
  15100. this.name = '';
  15101. this.data = interleavedBuffer;
  15102. this.itemSize = itemSize;
  15103. this.offset = offset;
  15104. this.normalized = normalized === true;
  15105. }
  15106. Object.defineProperties( InterleavedBufferAttribute.prototype, {
  15107. count: {
  15108. get: function () {
  15109. return this.data.count;
  15110. }
  15111. },
  15112. array: {
  15113. get: function () {
  15114. return this.data.array;
  15115. }
  15116. },
  15117. needsUpdate: {
  15118. set: function ( value ) {
  15119. this.data.needsUpdate = value;
  15120. }
  15121. }
  15122. } );
  15123. Object.assign( InterleavedBufferAttribute.prototype, {
  15124. isInterleavedBufferAttribute: true,
  15125. applyMatrix4: function ( m ) {
  15126. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  15127. _vector$6.x = this.getX( i );
  15128. _vector$6.y = this.getY( i );
  15129. _vector$6.z = this.getZ( i );
  15130. _vector$6.applyMatrix4( m );
  15131. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  15132. }
  15133. return this;
  15134. },
  15135. setX: function ( index, x ) {
  15136. this.data.array[ index * this.data.stride + this.offset ] = x;
  15137. return this;
  15138. },
  15139. setY: function ( index, y ) {
  15140. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  15141. return this;
  15142. },
  15143. setZ: function ( index, z ) {
  15144. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  15145. return this;
  15146. },
  15147. setW: function ( index, w ) {
  15148. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  15149. return this;
  15150. },
  15151. getX: function ( index ) {
  15152. return this.data.array[ index * this.data.stride + this.offset ];
  15153. },
  15154. getY: function ( index ) {
  15155. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  15156. },
  15157. getZ: function ( index ) {
  15158. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  15159. },
  15160. getW: function ( index ) {
  15161. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  15162. },
  15163. setXY: function ( index, x, y ) {
  15164. index = index * this.data.stride + this.offset;
  15165. this.data.array[ index + 0 ] = x;
  15166. this.data.array[ index + 1 ] = y;
  15167. return this;
  15168. },
  15169. setXYZ: function ( index, x, y, z ) {
  15170. index = index * this.data.stride + this.offset;
  15171. this.data.array[ index + 0 ] = x;
  15172. this.data.array[ index + 1 ] = y;
  15173. this.data.array[ index + 2 ] = z;
  15174. return this;
  15175. },
  15176. setXYZW: function ( index, x, y, z, w ) {
  15177. index = index * this.data.stride + this.offset;
  15178. this.data.array[ index + 0 ] = x;
  15179. this.data.array[ index + 1 ] = y;
  15180. this.data.array[ index + 2 ] = z;
  15181. this.data.array[ index + 3 ] = w;
  15182. return this;
  15183. },
  15184. clone: function ( data ) {
  15185. if ( data === undefined ) {
  15186. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.' );
  15187. const array = [];
  15188. for ( let i = 0; i < this.count; i ++ ) {
  15189. const index = i * this.data.stride + this.offset;
  15190. for ( let j = 0; j < this.itemSize; j ++ ) {
  15191. array.push( this.data.array[ index + j ] );
  15192. }
  15193. }
  15194. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  15195. } else {
  15196. if ( data.interleavedBuffers === undefined ) {
  15197. data.interleavedBuffers = {};
  15198. }
  15199. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  15200. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  15201. }
  15202. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  15203. }
  15204. },
  15205. toJSON: function ( data ) {
  15206. if ( data === undefined ) {
  15207. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.' );
  15208. const array = [];
  15209. for ( let i = 0; i < this.count; i ++ ) {
  15210. const index = i * this.data.stride + this.offset;
  15211. for ( let j = 0; j < this.itemSize; j ++ ) {
  15212. array.push( this.data.array[ index + j ] );
  15213. }
  15214. }
  15215. // deinterleave data and save it as an ordinary buffer attribute for now
  15216. return {
  15217. itemSize: this.itemSize,
  15218. type: this.array.constructor.name,
  15219. array: array,
  15220. normalized: this.normalized
  15221. };
  15222. } else {
  15223. // save as true interlaved attribtue
  15224. if ( data.interleavedBuffers === undefined ) {
  15225. data.interleavedBuffers = {};
  15226. }
  15227. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  15228. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  15229. }
  15230. return {
  15231. isInterleavedBufferAttribute: true,
  15232. itemSize: this.itemSize,
  15233. data: this.data.uuid,
  15234. offset: this.offset,
  15235. normalized: this.normalized
  15236. };
  15237. }
  15238. }
  15239. } );
  15240. /**
  15241. * parameters = {
  15242. * color: <hex>,
  15243. * map: new THREE.Texture( <Image> ),
  15244. * alphaMap: new THREE.Texture( <Image> ),
  15245. * rotation: <float>,
  15246. * sizeAttenuation: <bool>
  15247. * }
  15248. */
  15249. class SpriteMaterial extends Material {
  15250. constructor( parameters ) {
  15251. super();
  15252. this.type = 'SpriteMaterial';
  15253. this.color = new Color( 0xffffff );
  15254. this.map = null;
  15255. this.alphaMap = null;
  15256. this.rotation = 0;
  15257. this.sizeAttenuation = true;
  15258. this.transparent = true;
  15259. this.setValues( parameters );
  15260. }
  15261. copy( source ) {
  15262. super.copy( source );
  15263. this.color.copy( source.color );
  15264. this.map = source.map;
  15265. this.alphaMap = source.alphaMap;
  15266. this.rotation = source.rotation;
  15267. this.sizeAttenuation = source.sizeAttenuation;
  15268. return this;
  15269. }
  15270. }
  15271. SpriteMaterial.prototype.isSpriteMaterial = true;
  15272. let _geometry;
  15273. const _intersectPoint = /*@__PURE__*/ new Vector3();
  15274. const _worldScale = /*@__PURE__*/ new Vector3();
  15275. const _mvPosition = /*@__PURE__*/ new Vector3();
  15276. const _alignedPosition = /*@__PURE__*/ new Vector2();
  15277. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  15278. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  15279. const _vA$1 = /*@__PURE__*/ new Vector3();
  15280. const _vB$1 = /*@__PURE__*/ new Vector3();
  15281. const _vC$1 = /*@__PURE__*/ new Vector3();
  15282. const _uvA$1 = /*@__PURE__*/ new Vector2();
  15283. const _uvB$1 = /*@__PURE__*/ new Vector2();
  15284. const _uvC$1 = /*@__PURE__*/ new Vector2();
  15285. class Sprite extends Object3D {
  15286. constructor( material ) {
  15287. super();
  15288. this.type = 'Sprite';
  15289. if ( _geometry === undefined ) {
  15290. _geometry = new BufferGeometry();
  15291. const float32Array = new Float32Array( [
  15292. - 0.5, - 0.5, 0, 0, 0,
  15293. 0.5, - 0.5, 0, 1, 0,
  15294. 0.5, 0.5, 0, 1, 1,
  15295. - 0.5, 0.5, 0, 0, 1
  15296. ] );
  15297. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  15298. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  15299. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  15300. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  15301. }
  15302. this.geometry = _geometry;
  15303. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  15304. this.center = new Vector2( 0.5, 0.5 );
  15305. }
  15306. raycast( raycaster, intersects ) {
  15307. if ( raycaster.camera === null ) {
  15308. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  15309. }
  15310. _worldScale.setFromMatrixScale( this.matrixWorld );
  15311. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  15312. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  15313. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  15314. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  15315. _worldScale.multiplyScalar( - _mvPosition.z );
  15316. }
  15317. const rotation = this.material.rotation;
  15318. let sin, cos;
  15319. if ( rotation !== 0 ) {
  15320. cos = Math.cos( rotation );
  15321. sin = Math.sin( rotation );
  15322. }
  15323. const center = this.center;
  15324. transformVertex( _vA$1.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  15325. transformVertex( _vB$1.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  15326. transformVertex( _vC$1.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  15327. _uvA$1.set( 0, 0 );
  15328. _uvB$1.set( 1, 0 );
  15329. _uvC$1.set( 1, 1 );
  15330. // check first triangle
  15331. let intersect = raycaster.ray.intersectTriangle( _vA$1, _vB$1, _vC$1, false, _intersectPoint );
  15332. if ( intersect === null ) {
  15333. // check second triangle
  15334. transformVertex( _vB$1.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  15335. _uvB$1.set( 0, 1 );
  15336. intersect = raycaster.ray.intersectTriangle( _vA$1, _vC$1, _vB$1, false, _intersectPoint );
  15337. if ( intersect === null ) {
  15338. return;
  15339. }
  15340. }
  15341. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  15342. if ( distance < raycaster.near || distance > raycaster.far ) return;
  15343. intersects.push( {
  15344. distance: distance,
  15345. point: _intersectPoint.clone(),
  15346. uv: Triangle.getUV( _intersectPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() ),
  15347. face: null,
  15348. object: this
  15349. } );
  15350. }
  15351. copy( source ) {
  15352. super.copy( source );
  15353. if ( source.center !== undefined ) this.center.copy( source.center );
  15354. this.material = source.material;
  15355. return this;
  15356. }
  15357. }
  15358. Sprite.prototype.isSprite = true;
  15359. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  15360. // compute position in camera space
  15361. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  15362. // to check if rotation is not zero
  15363. if ( sin !== undefined ) {
  15364. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  15365. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  15366. } else {
  15367. _rotatedPosition.copy( _alignedPosition );
  15368. }
  15369. vertexPosition.copy( mvPosition );
  15370. vertexPosition.x += _rotatedPosition.x;
  15371. vertexPosition.y += _rotatedPosition.y;
  15372. // transform to world space
  15373. vertexPosition.applyMatrix4( _viewWorldMatrix );
  15374. }
  15375. const _v1$4 = /*@__PURE__*/ new Vector3();
  15376. const _v2$2 = /*@__PURE__*/ new Vector3();
  15377. class LOD extends Object3D {
  15378. constructor() {
  15379. super();
  15380. this._currentLevel = 0;
  15381. this.type = 'LOD';
  15382. Object.defineProperties( this, {
  15383. levels: {
  15384. enumerable: true,
  15385. value: []
  15386. },
  15387. isLOD: {
  15388. value: true,
  15389. }
  15390. } );
  15391. this.autoUpdate = true;
  15392. }
  15393. copy( source ) {
  15394. super.copy( source, false );
  15395. const levels = source.levels;
  15396. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  15397. const level = levels[ i ];
  15398. this.addLevel( level.object.clone(), level.distance );
  15399. }
  15400. this.autoUpdate = source.autoUpdate;
  15401. return this;
  15402. }
  15403. addLevel( object, distance = 0 ) {
  15404. distance = Math.abs( distance );
  15405. const levels = this.levels;
  15406. let l;
  15407. for ( l = 0; l < levels.length; l ++ ) {
  15408. if ( distance < levels[ l ].distance ) {
  15409. break;
  15410. }
  15411. }
  15412. levels.splice( l, 0, { distance: distance, object: object } );
  15413. this.add( object );
  15414. return this;
  15415. }
  15416. getCurrentLevel() {
  15417. return this._currentLevel;
  15418. }
  15419. getObjectForDistance( distance ) {
  15420. const levels = this.levels;
  15421. if ( levels.length > 0 ) {
  15422. let i, l;
  15423. for ( i = 1, l = levels.length; i < l; i ++ ) {
  15424. if ( distance < levels[ i ].distance ) {
  15425. break;
  15426. }
  15427. }
  15428. return levels[ i - 1 ].object;
  15429. }
  15430. return null;
  15431. }
  15432. raycast( raycaster, intersects ) {
  15433. const levels = this.levels;
  15434. if ( levels.length > 0 ) {
  15435. _v1$4.setFromMatrixPosition( this.matrixWorld );
  15436. const distance = raycaster.ray.origin.distanceTo( _v1$4 );
  15437. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  15438. }
  15439. }
  15440. update( camera ) {
  15441. const levels = this.levels;
  15442. if ( levels.length > 1 ) {
  15443. _v1$4.setFromMatrixPosition( camera.matrixWorld );
  15444. _v2$2.setFromMatrixPosition( this.matrixWorld );
  15445. const distance = _v1$4.distanceTo( _v2$2 ) / camera.zoom;
  15446. levels[ 0 ].object.visible = true;
  15447. let i, l;
  15448. for ( i = 1, l = levels.length; i < l; i ++ ) {
  15449. if ( distance >= levels[ i ].distance ) {
  15450. levels[ i - 1 ].object.visible = false;
  15451. levels[ i ].object.visible = true;
  15452. } else {
  15453. break;
  15454. }
  15455. }
  15456. this._currentLevel = i - 1;
  15457. for ( ; i < l; i ++ ) {
  15458. levels[ i ].object.visible = false;
  15459. }
  15460. }
  15461. }
  15462. toJSON( meta ) {
  15463. const data = super.toJSON( meta );
  15464. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  15465. data.object.levels = [];
  15466. const levels = this.levels;
  15467. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  15468. const level = levels[ i ];
  15469. data.object.levels.push( {
  15470. object: level.object.uuid,
  15471. distance: level.distance
  15472. } );
  15473. }
  15474. return data;
  15475. }
  15476. }
  15477. const _basePosition = new Vector3();
  15478. const _skinIndex = new Vector4();
  15479. const _skinWeight = new Vector4();
  15480. const _vector$7 = new Vector3();
  15481. const _matrix$1 = new Matrix4();
  15482. function SkinnedMesh( geometry, material ) {
  15483. Mesh.call( this, geometry, material );
  15484. this.type = 'SkinnedMesh';
  15485. this.bindMode = 'attached';
  15486. this.bindMatrix = new Matrix4();
  15487. this.bindMatrixInverse = new Matrix4();
  15488. }
  15489. SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  15490. constructor: SkinnedMesh,
  15491. isSkinnedMesh: true,
  15492. copy: function ( source ) {
  15493. Mesh.prototype.copy.call( this, source );
  15494. this.bindMode = source.bindMode;
  15495. this.bindMatrix.copy( source.bindMatrix );
  15496. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  15497. this.skeleton = source.skeleton;
  15498. return this;
  15499. },
  15500. bind: function ( skeleton, bindMatrix ) {
  15501. this.skeleton = skeleton;
  15502. if ( bindMatrix === undefined ) {
  15503. this.updateMatrixWorld( true );
  15504. this.skeleton.calculateInverses();
  15505. bindMatrix = this.matrixWorld;
  15506. }
  15507. this.bindMatrix.copy( bindMatrix );
  15508. this.bindMatrixInverse.copy( bindMatrix ).invert();
  15509. },
  15510. pose: function () {
  15511. this.skeleton.pose();
  15512. },
  15513. normalizeSkinWeights: function () {
  15514. const vector = new Vector4();
  15515. const skinWeight = this.geometry.attributes.skinWeight;
  15516. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  15517. vector.x = skinWeight.getX( i );
  15518. vector.y = skinWeight.getY( i );
  15519. vector.z = skinWeight.getZ( i );
  15520. vector.w = skinWeight.getW( i );
  15521. const scale = 1.0 / vector.manhattanLength();
  15522. if ( scale !== Infinity ) {
  15523. vector.multiplyScalar( scale );
  15524. } else {
  15525. vector.set( 1, 0, 0, 0 ); // do something reasonable
  15526. }
  15527. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  15528. }
  15529. },
  15530. updateMatrixWorld: function ( force ) {
  15531. Mesh.prototype.updateMatrixWorld.call( this, force );
  15532. if ( this.bindMode === 'attached' ) {
  15533. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  15534. } else if ( this.bindMode === 'detached' ) {
  15535. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  15536. } else {
  15537. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  15538. }
  15539. },
  15540. boneTransform: function ( index, target ) {
  15541. const skeleton = this.skeleton;
  15542. const geometry = this.geometry;
  15543. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  15544. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  15545. _basePosition.fromBufferAttribute( geometry.attributes.position, index ).applyMatrix4( this.bindMatrix );
  15546. target.set( 0, 0, 0 );
  15547. for ( let i = 0; i < 4; i ++ ) {
  15548. const weight = _skinWeight.getComponent( i );
  15549. if ( weight !== 0 ) {
  15550. const boneIndex = _skinIndex.getComponent( i );
  15551. _matrix$1.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  15552. target.addScaledVector( _vector$7.copy( _basePosition ).applyMatrix4( _matrix$1 ), weight );
  15553. }
  15554. }
  15555. return target.applyMatrix4( this.bindMatrixInverse );
  15556. }
  15557. } );
  15558. function Bone() {
  15559. Object3D.call( this );
  15560. this.type = 'Bone';
  15561. }
  15562. Bone.prototype = Object.assign( Object.create( Object3D.prototype ), {
  15563. constructor: Bone,
  15564. isBone: true
  15565. } );
  15566. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  15567. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  15568. class Skeleton {
  15569. constructor( bones = [], boneInverses = [] ) {
  15570. this.uuid = MathUtils.generateUUID();
  15571. this.bones = bones.slice( 0 );
  15572. this.boneInverses = boneInverses;
  15573. this.boneMatrices = null;
  15574. this.boneTexture = null;
  15575. this.boneTextureSize = 0;
  15576. this.frame = - 1;
  15577. this.init();
  15578. }
  15579. init() {
  15580. const bones = this.bones;
  15581. const boneInverses = this.boneInverses;
  15582. this.boneMatrices = new Float32Array( bones.length * 16 );
  15583. // calculate inverse bone matrices if necessary
  15584. if ( boneInverses.length === 0 ) {
  15585. this.calculateInverses();
  15586. } else {
  15587. // handle special case
  15588. if ( bones.length !== boneInverses.length ) {
  15589. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  15590. this.boneInverses = [];
  15591. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  15592. this.boneInverses.push( new Matrix4() );
  15593. }
  15594. }
  15595. }
  15596. }
  15597. calculateInverses() {
  15598. this.boneInverses.length = 0;
  15599. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  15600. const inverse = new Matrix4();
  15601. if ( this.bones[ i ] ) {
  15602. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  15603. }
  15604. this.boneInverses.push( inverse );
  15605. }
  15606. }
  15607. pose() {
  15608. // recover the bind-time world matrices
  15609. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  15610. const bone = this.bones[ i ];
  15611. if ( bone ) {
  15612. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  15613. }
  15614. }
  15615. // compute the local matrices, positions, rotations and scales
  15616. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  15617. const bone = this.bones[ i ];
  15618. if ( bone ) {
  15619. if ( bone.parent && bone.parent.isBone ) {
  15620. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  15621. bone.matrix.multiply( bone.matrixWorld );
  15622. } else {
  15623. bone.matrix.copy( bone.matrixWorld );
  15624. }
  15625. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  15626. }
  15627. }
  15628. }
  15629. update() {
  15630. const bones = this.bones;
  15631. const boneInverses = this.boneInverses;
  15632. const boneMatrices = this.boneMatrices;
  15633. const boneTexture = this.boneTexture;
  15634. // flatten bone matrices to array
  15635. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  15636. // compute the offset between the current and the original transform
  15637. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  15638. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  15639. _offsetMatrix.toArray( boneMatrices, i * 16 );
  15640. }
  15641. if ( boneTexture !== null ) {
  15642. boneTexture.needsUpdate = true;
  15643. }
  15644. }
  15645. clone() {
  15646. return new Skeleton( this.bones, this.boneInverses );
  15647. }
  15648. getBoneByName( name ) {
  15649. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  15650. const bone = this.bones[ i ];
  15651. if ( bone.name === name ) {
  15652. return bone;
  15653. }
  15654. }
  15655. return undefined;
  15656. }
  15657. dispose( ) {
  15658. if ( this.boneTexture !== null ) {
  15659. this.boneTexture.dispose();
  15660. this.boneTexture = null;
  15661. }
  15662. }
  15663. fromJSON( json, bones ) {
  15664. this.uuid = json.uuid;
  15665. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  15666. const uuid = json.bones[ i ];
  15667. let bone = bones[ uuid ];
  15668. if ( bone === undefined ) {
  15669. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  15670. bone = new Bone();
  15671. }
  15672. this.bones.push( bone );
  15673. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  15674. }
  15675. this.init();
  15676. return this;
  15677. }
  15678. toJSON() {
  15679. const data = {
  15680. metadata: {
  15681. version: 4.5,
  15682. type: 'Skeleton',
  15683. generator: 'Skeleton.toJSON'
  15684. },
  15685. bones: [],
  15686. boneInverses: []
  15687. };
  15688. data.uuid = this.uuid;
  15689. const bones = this.bones;
  15690. const boneInverses = this.boneInverses;
  15691. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  15692. const bone = bones[ i ];
  15693. data.bones.push( bone.uuid );
  15694. const boneInverse = boneInverses[ i ];
  15695. data.boneInverses.push( boneInverse.toArray() );
  15696. }
  15697. return data;
  15698. }
  15699. }
  15700. const _instanceLocalMatrix = new Matrix4();
  15701. const _instanceWorldMatrix = new Matrix4();
  15702. const _instanceIntersects = [];
  15703. const _mesh = new Mesh();
  15704. function InstancedMesh( geometry, material, count ) {
  15705. Mesh.call( this, geometry, material );
  15706. this.instanceMatrix = new BufferAttribute( new Float32Array( count * 16 ), 16 );
  15707. this.instanceColor = null;
  15708. this.count = count;
  15709. this.frustumCulled = false;
  15710. }
  15711. InstancedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  15712. constructor: InstancedMesh,
  15713. isInstancedMesh: true,
  15714. copy: function ( source ) {
  15715. Mesh.prototype.copy.call( this, source );
  15716. this.instanceMatrix.copy( source.instanceMatrix );
  15717. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  15718. this.count = source.count;
  15719. return this;
  15720. },
  15721. getColorAt: function ( index, color ) {
  15722. color.fromArray( this.instanceColor.array, index * 3 );
  15723. },
  15724. getMatrixAt: function ( index, matrix ) {
  15725. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  15726. },
  15727. raycast: function ( raycaster, intersects ) {
  15728. const matrixWorld = this.matrixWorld;
  15729. const raycastTimes = this.count;
  15730. _mesh.geometry = this.geometry;
  15731. _mesh.material = this.material;
  15732. if ( _mesh.material === undefined ) return;
  15733. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  15734. // calculate the world matrix for each instance
  15735. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  15736. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  15737. // the mesh represents this single instance
  15738. _mesh.matrixWorld = _instanceWorldMatrix;
  15739. _mesh.raycast( raycaster, _instanceIntersects );
  15740. // process the result of raycast
  15741. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  15742. const intersect = _instanceIntersects[ i ];
  15743. intersect.instanceId = instanceId;
  15744. intersect.object = this;
  15745. intersects.push( intersect );
  15746. }
  15747. _instanceIntersects.length = 0;
  15748. }
  15749. },
  15750. setColorAt: function ( index, color ) {
  15751. if ( this.instanceColor === null ) {
  15752. this.instanceColor = new BufferAttribute( new Float32Array( this.count * 3 ), 3 );
  15753. }
  15754. color.toArray( this.instanceColor.array, index * 3 );
  15755. },
  15756. setMatrixAt: function ( index, matrix ) {
  15757. matrix.toArray( this.instanceMatrix.array, index * 16 );
  15758. },
  15759. updateMorphTargets: function () {
  15760. },
  15761. dispose: function () {
  15762. this.dispatchEvent( { type: 'dispose' } );
  15763. }
  15764. } );
  15765. /**
  15766. * parameters = {
  15767. * color: <hex>,
  15768. * opacity: <float>,
  15769. *
  15770. * linewidth: <float>,
  15771. * linecap: "round",
  15772. * linejoin: "round"
  15773. * }
  15774. */
  15775. class LineBasicMaterial extends Material {
  15776. constructor( parameters ) {
  15777. super();
  15778. this.type = 'LineBasicMaterial';
  15779. this.color = new Color( 0xffffff );
  15780. this.linewidth = 1;
  15781. this.linecap = 'round';
  15782. this.linejoin = 'round';
  15783. this.morphTargets = false;
  15784. this.setValues( parameters );
  15785. }
  15786. copy( source ) {
  15787. super.copy( source );
  15788. this.color.copy( source.color );
  15789. this.linewidth = source.linewidth;
  15790. this.linecap = source.linecap;
  15791. this.linejoin = source.linejoin;
  15792. this.morphTargets = source.morphTargets;
  15793. return this;
  15794. }
  15795. }
  15796. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  15797. const _start = new Vector3();
  15798. const _end = new Vector3();
  15799. const _inverseMatrix$1 = new Matrix4();
  15800. const _ray$1 = new Ray();
  15801. const _sphere$2 = new Sphere();
  15802. function Line( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  15803. Object3D.call( this );
  15804. this.type = 'Line';
  15805. this.geometry = geometry;
  15806. this.material = material;
  15807. this.updateMorphTargets();
  15808. }
  15809. Line.prototype = Object.assign( Object.create( Object3D.prototype ), {
  15810. constructor: Line,
  15811. isLine: true,
  15812. copy: function ( source ) {
  15813. Object3D.prototype.copy.call( this, source );
  15814. this.material = source.material;
  15815. this.geometry = source.geometry;
  15816. return this;
  15817. },
  15818. computeLineDistances: function () {
  15819. const geometry = this.geometry;
  15820. if ( geometry.isBufferGeometry ) {
  15821. // we assume non-indexed geometry
  15822. if ( geometry.index === null ) {
  15823. const positionAttribute = geometry.attributes.position;
  15824. const lineDistances = [ 0 ];
  15825. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  15826. _start.fromBufferAttribute( positionAttribute, i - 1 );
  15827. _end.fromBufferAttribute( positionAttribute, i );
  15828. lineDistances[ i ] = lineDistances[ i - 1 ];
  15829. lineDistances[ i ] += _start.distanceTo( _end );
  15830. }
  15831. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  15832. } else {
  15833. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  15834. }
  15835. } else if ( geometry.isGeometry ) {
  15836. console.error( 'THREE.Line.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  15837. }
  15838. return this;
  15839. },
  15840. raycast: function ( raycaster, intersects ) {
  15841. const geometry = this.geometry;
  15842. const matrixWorld = this.matrixWorld;
  15843. const threshold = raycaster.params.Line.threshold;
  15844. // Checking boundingSphere distance to ray
  15845. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  15846. _sphere$2.copy( geometry.boundingSphere );
  15847. _sphere$2.applyMatrix4( matrixWorld );
  15848. _sphere$2.radius += threshold;
  15849. if ( raycaster.ray.intersectsSphere( _sphere$2 ) === false ) return;
  15850. //
  15851. _inverseMatrix$1.copy( matrixWorld ).invert();
  15852. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  15853. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  15854. const localThresholdSq = localThreshold * localThreshold;
  15855. const vStart = new Vector3();
  15856. const vEnd = new Vector3();
  15857. const interSegment = new Vector3();
  15858. const interRay = new Vector3();
  15859. const step = this.isLineSegments ? 2 : 1;
  15860. if ( geometry.isBufferGeometry ) {
  15861. const index = geometry.index;
  15862. const attributes = geometry.attributes;
  15863. const positionAttribute = attributes.position;
  15864. if ( index !== null ) {
  15865. const indices = index.array;
  15866. for ( let i = 0, l = indices.length - 1; i < l; i += step ) {
  15867. const a = indices[ i ];
  15868. const b = indices[ i + 1 ];
  15869. vStart.fromBufferAttribute( positionAttribute, a );
  15870. vEnd.fromBufferAttribute( positionAttribute, b );
  15871. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  15872. if ( distSq > localThresholdSq ) continue;
  15873. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  15874. const distance = raycaster.ray.origin.distanceTo( interRay );
  15875. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  15876. intersects.push( {
  15877. distance: distance,
  15878. // What do we want? intersection point on the ray or on the segment??
  15879. // point: raycaster.ray.at( distance ),
  15880. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  15881. index: i,
  15882. face: null,
  15883. faceIndex: null,
  15884. object: this
  15885. } );
  15886. }
  15887. } else {
  15888. for ( let i = 0, l = positionAttribute.count - 1; i < l; i += step ) {
  15889. vStart.fromBufferAttribute( positionAttribute, i );
  15890. vEnd.fromBufferAttribute( positionAttribute, i + 1 );
  15891. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  15892. if ( distSq > localThresholdSq ) continue;
  15893. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  15894. const distance = raycaster.ray.origin.distanceTo( interRay );
  15895. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  15896. intersects.push( {
  15897. distance: distance,
  15898. // What do we want? intersection point on the ray or on the segment??
  15899. // point: raycaster.ray.at( distance ),
  15900. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  15901. index: i,
  15902. face: null,
  15903. faceIndex: null,
  15904. object: this
  15905. } );
  15906. }
  15907. }
  15908. } else if ( geometry.isGeometry ) {
  15909. console.error( 'THREE.Line.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  15910. }
  15911. },
  15912. updateMorphTargets: function () {
  15913. const geometry = this.geometry;
  15914. if ( geometry.isBufferGeometry ) {
  15915. const morphAttributes = geometry.morphAttributes;
  15916. const keys = Object.keys( morphAttributes );
  15917. if ( keys.length > 0 ) {
  15918. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  15919. if ( morphAttribute !== undefined ) {
  15920. this.morphTargetInfluences = [];
  15921. this.morphTargetDictionary = {};
  15922. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  15923. const name = morphAttribute[ m ].name || String( m );
  15924. this.morphTargetInfluences.push( 0 );
  15925. this.morphTargetDictionary[ name ] = m;
  15926. }
  15927. }
  15928. }
  15929. } else {
  15930. const morphTargets = geometry.morphTargets;
  15931. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  15932. console.error( 'THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' );
  15933. }
  15934. }
  15935. }
  15936. } );
  15937. const _start$1 = new Vector3();
  15938. const _end$1 = new Vector3();
  15939. function LineSegments( geometry, material ) {
  15940. Line.call( this, geometry, material );
  15941. this.type = 'LineSegments';
  15942. }
  15943. LineSegments.prototype = Object.assign( Object.create( Line.prototype ), {
  15944. constructor: LineSegments,
  15945. isLineSegments: true,
  15946. computeLineDistances: function () {
  15947. const geometry = this.geometry;
  15948. if ( geometry.isBufferGeometry ) {
  15949. // we assume non-indexed geometry
  15950. if ( geometry.index === null ) {
  15951. const positionAttribute = geometry.attributes.position;
  15952. const lineDistances = [];
  15953. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  15954. _start$1.fromBufferAttribute( positionAttribute, i );
  15955. _end$1.fromBufferAttribute( positionAttribute, i + 1 );
  15956. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  15957. lineDistances[ i + 1 ] = lineDistances[ i ] + _start$1.distanceTo( _end$1 );
  15958. }
  15959. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  15960. } else {
  15961. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  15962. }
  15963. } else if ( geometry.isGeometry ) {
  15964. console.error( 'THREE.LineSegments.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  15965. }
  15966. return this;
  15967. }
  15968. } );
  15969. class LineLoop extends Line {
  15970. constructor( geometry, material ) {
  15971. super( geometry, material );
  15972. this.type = 'LineLoop';
  15973. }
  15974. }
  15975. LineLoop.prototype.isLineLoop = true;
  15976. /**
  15977. * parameters = {
  15978. * color: <hex>,
  15979. * opacity: <float>,
  15980. * map: new THREE.Texture( <Image> ),
  15981. * alphaMap: new THREE.Texture( <Image> ),
  15982. *
  15983. * size: <float>,
  15984. * sizeAttenuation: <bool>
  15985. *
  15986. * morphTargets: <bool>
  15987. * }
  15988. */
  15989. class PointsMaterial extends Material {
  15990. constructor( parameters ) {
  15991. super();
  15992. this.type = 'PointsMaterial';
  15993. this.color = new Color( 0xffffff );
  15994. this.map = null;
  15995. this.alphaMap = null;
  15996. this.size = 1;
  15997. this.sizeAttenuation = true;
  15998. this.morphTargets = false;
  15999. this.setValues( parameters );
  16000. }
  16001. copy( source ) {
  16002. super.copy( source );
  16003. this.color.copy( source.color );
  16004. this.map = source.map;
  16005. this.alphaMap = source.alphaMap;
  16006. this.size = source.size;
  16007. this.sizeAttenuation = source.sizeAttenuation;
  16008. this.morphTargets = source.morphTargets;
  16009. return this;
  16010. }
  16011. }
  16012. PointsMaterial.prototype.isPointsMaterial = true;
  16013. const _inverseMatrix$2 = new Matrix4();
  16014. const _ray$2 = new Ray();
  16015. const _sphere$3 = new Sphere();
  16016. const _position$1 = new Vector3();
  16017. function Points( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  16018. Object3D.call( this );
  16019. this.type = 'Points';
  16020. this.geometry = geometry;
  16021. this.material = material;
  16022. this.updateMorphTargets();
  16023. }
  16024. Points.prototype = Object.assign( Object.create( Object3D.prototype ), {
  16025. constructor: Points,
  16026. isPoints: true,
  16027. copy: function ( source ) {
  16028. Object3D.prototype.copy.call( this, source );
  16029. this.material = source.material;
  16030. this.geometry = source.geometry;
  16031. return this;
  16032. },
  16033. raycast: function ( raycaster, intersects ) {
  16034. const geometry = this.geometry;
  16035. const matrixWorld = this.matrixWorld;
  16036. const threshold = raycaster.params.Points.threshold;
  16037. // Checking boundingSphere distance to ray
  16038. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  16039. _sphere$3.copy( geometry.boundingSphere );
  16040. _sphere$3.applyMatrix4( matrixWorld );
  16041. _sphere$3.radius += threshold;
  16042. if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return;
  16043. //
  16044. _inverseMatrix$2.copy( matrixWorld ).invert();
  16045. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  16046. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  16047. const localThresholdSq = localThreshold * localThreshold;
  16048. if ( geometry.isBufferGeometry ) {
  16049. const index = geometry.index;
  16050. const attributes = geometry.attributes;
  16051. const positionAttribute = attributes.position;
  16052. if ( index !== null ) {
  16053. const indices = index.array;
  16054. for ( let i = 0, il = indices.length; i < il; i ++ ) {
  16055. const a = indices[ i ];
  16056. _position$1.fromBufferAttribute( positionAttribute, a );
  16057. testPoint( _position$1, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  16058. }
  16059. } else {
  16060. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  16061. _position$1.fromBufferAttribute( positionAttribute, i );
  16062. testPoint( _position$1, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  16063. }
  16064. }
  16065. } else {
  16066. console.error( 'THREE.Points.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  16067. }
  16068. },
  16069. updateMorphTargets: function () {
  16070. const geometry = this.geometry;
  16071. if ( geometry.isBufferGeometry ) {
  16072. const morphAttributes = geometry.morphAttributes;
  16073. const keys = Object.keys( morphAttributes );
  16074. if ( keys.length > 0 ) {
  16075. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  16076. if ( morphAttribute !== undefined ) {
  16077. this.morphTargetInfluences = [];
  16078. this.morphTargetDictionary = {};
  16079. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  16080. const name = morphAttribute[ m ].name || String( m );
  16081. this.morphTargetInfluences.push( 0 );
  16082. this.morphTargetDictionary[ name ] = m;
  16083. }
  16084. }
  16085. }
  16086. } else {
  16087. const morphTargets = geometry.morphTargets;
  16088. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  16089. console.error( 'THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' );
  16090. }
  16091. }
  16092. }
  16093. } );
  16094. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  16095. const rayPointDistanceSq = _ray$2.distanceSqToPoint( point );
  16096. if ( rayPointDistanceSq < localThresholdSq ) {
  16097. const intersectPoint = new Vector3();
  16098. _ray$2.closestPointToPoint( point, intersectPoint );
  16099. intersectPoint.applyMatrix4( matrixWorld );
  16100. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  16101. if ( distance < raycaster.near || distance > raycaster.far ) return;
  16102. intersects.push( {
  16103. distance: distance,
  16104. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  16105. point: intersectPoint,
  16106. index: index,
  16107. face: null,
  16108. object: object
  16109. } );
  16110. }
  16111. }
  16112. class VideoTexture extends Texture {
  16113. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  16114. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  16115. this.format = format !== undefined ? format : RGBFormat;
  16116. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  16117. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  16118. this.generateMipmaps = false;
  16119. const scope = this;
  16120. function updateVideo() {
  16121. scope.needsUpdate = true;
  16122. video.requestVideoFrameCallback( updateVideo );
  16123. }
  16124. if ( 'requestVideoFrameCallback' in video ) {
  16125. video.requestVideoFrameCallback( updateVideo );
  16126. }
  16127. }
  16128. clone() {
  16129. return new this.constructor( this.image ).copy( this );
  16130. }
  16131. update() {
  16132. const video = this.image;
  16133. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  16134. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  16135. this.needsUpdate = true;
  16136. }
  16137. }
  16138. }
  16139. VideoTexture.prototype.isVideoTexture = true;
  16140. class CompressedTexture extends Texture {
  16141. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  16142. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  16143. this.image = { width: width, height: height };
  16144. this.mipmaps = mipmaps;
  16145. // no flipping for cube textures
  16146. // (also flipping doesn't work for compressed textures )
  16147. this.flipY = false;
  16148. // can't generate mipmaps for compressed textures
  16149. // mips must be embedded in DDS files
  16150. this.generateMipmaps = false;
  16151. }
  16152. }
  16153. CompressedTexture.prototype.isCompressedTexture = true;
  16154. class CanvasTexture extends Texture {
  16155. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  16156. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  16157. this.needsUpdate = true;
  16158. }
  16159. }
  16160. CanvasTexture.prototype.isCanvasTexture = true;
  16161. class DepthTexture extends Texture {
  16162. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  16163. format = format !== undefined ? format : DepthFormat;
  16164. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  16165. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  16166. }
  16167. if ( type === undefined && format === DepthFormat ) type = UnsignedShortType;
  16168. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  16169. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  16170. this.image = { width: width, height: height };
  16171. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  16172. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  16173. this.flipY = false;
  16174. this.generateMipmaps = false;
  16175. }
  16176. }
  16177. DepthTexture.prototype.isDepthTexture = true;
  16178. class CircleGeometry extends BufferGeometry {
  16179. constructor( radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  16180. super();
  16181. this.type = 'CircleGeometry';
  16182. this.parameters = {
  16183. radius: radius,
  16184. segments: segments,
  16185. thetaStart: thetaStart,
  16186. thetaLength: thetaLength
  16187. };
  16188. segments = Math.max( 3, segments );
  16189. // buffers
  16190. const indices = [];
  16191. const vertices = [];
  16192. const normals = [];
  16193. const uvs = [];
  16194. // helper variables
  16195. const vertex = new Vector3();
  16196. const uv = new Vector2();
  16197. // center point
  16198. vertices.push( 0, 0, 0 );
  16199. normals.push( 0, 0, 1 );
  16200. uvs.push( 0.5, 0.5 );
  16201. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  16202. const segment = thetaStart + s / segments * thetaLength;
  16203. // vertex
  16204. vertex.x = radius * Math.cos( segment );
  16205. vertex.y = radius * Math.sin( segment );
  16206. vertices.push( vertex.x, vertex.y, vertex.z );
  16207. // normal
  16208. normals.push( 0, 0, 1 );
  16209. // uvs
  16210. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  16211. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  16212. uvs.push( uv.x, uv.y );
  16213. }
  16214. // indices
  16215. for ( let i = 1; i <= segments; i ++ ) {
  16216. indices.push( i, i + 1, 0 );
  16217. }
  16218. // build geometry
  16219. this.setIndex( indices );
  16220. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16221. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  16222. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16223. }
  16224. }
  16225. class CylinderGeometry extends BufferGeometry {
  16226. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  16227. super();
  16228. this.type = 'CylinderGeometry';
  16229. this.parameters = {
  16230. radiusTop: radiusTop,
  16231. radiusBottom: radiusBottom,
  16232. height: height,
  16233. radialSegments: radialSegments,
  16234. heightSegments: heightSegments,
  16235. openEnded: openEnded,
  16236. thetaStart: thetaStart,
  16237. thetaLength: thetaLength
  16238. };
  16239. const scope = this;
  16240. radialSegments = Math.floor( radialSegments );
  16241. heightSegments = Math.floor( heightSegments );
  16242. // buffers
  16243. const indices = [];
  16244. const vertices = [];
  16245. const normals = [];
  16246. const uvs = [];
  16247. // helper variables
  16248. let index = 0;
  16249. const indexArray = [];
  16250. const halfHeight = height / 2;
  16251. let groupStart = 0;
  16252. // generate geometry
  16253. generateTorso();
  16254. if ( openEnded === false ) {
  16255. if ( radiusTop > 0 ) generateCap( true );
  16256. if ( radiusBottom > 0 ) generateCap( false );
  16257. }
  16258. // build geometry
  16259. this.setIndex( indices );
  16260. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16261. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  16262. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  16263. function generateTorso() {
  16264. const normal = new Vector3();
  16265. const vertex = new Vector3();
  16266. let groupCount = 0;
  16267. // this will be used to calculate the normal
  16268. const slope = ( radiusBottom - radiusTop ) / height;
  16269. // generate vertices, normals and uvs
  16270. for ( let y = 0; y <= heightSegments; y ++ ) {
  16271. const indexRow = [];
  16272. const v = y / heightSegments;
  16273. // calculate the radius of the current row
  16274. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  16275. for ( let x = 0; x <= radialSegments; x ++ ) {
  16276. const u = x / radialSegments;
  16277. const theta = u * thetaLength + thetaStart;
  16278. const sinTheta = Math.sin( theta );
  16279. const cosTheta = Math.cos( theta );
  16280. // vertex
  16281. vertex.x = radius * sinTheta;
  16282. vertex.y = - v * height + halfHeight;
  16283. vertex.z = radius * cosTheta;
  16284. vertices.push( vertex.x, vertex.y, vertex.z );
  16285. // normal
  16286. normal.set( sinTheta, slope, cosTheta ).normalize();
  16287. normals.push( normal.x, normal.y, normal.z );
  16288. // uv
  16289. uvs.push( u, 1 - v );
  16290. // save index of vertex in respective row
  16291. indexRow.push( index ++ );
  16292. }
  16293. // now save vertices of the row in our index array
  16294. indexArray.push( indexRow );
  16295. }
  16296. // generate indices
  16297. for ( let x = 0; x < radialSegments; x ++ ) {
  16298. for ( let y = 0; y < heightSegments; y ++ ) {
  16299. // we use the index array to access the correct indices
  16300. const a = indexArray[ y ][ x ];
  16301. const b = indexArray[ y + 1 ][ x ];
  16302. const c = indexArray[ y + 1 ][ x + 1 ];
  16303. const d = indexArray[ y ][ x + 1 ];
  16304. // faces
  16305. indices.push( a, b, d );
  16306. indices.push( b, c, d );
  16307. // update group counter
  16308. groupCount += 6;
  16309. }
  16310. }
  16311. // add a group to the geometry. this will ensure multi material support
  16312. scope.addGroup( groupStart, groupCount, 0 );
  16313. // calculate new start value for groups
  16314. groupStart += groupCount;
  16315. }
  16316. function generateCap( top ) {
  16317. // save the index of the first center vertex
  16318. const centerIndexStart = index;
  16319. const uv = new Vector2();
  16320. const vertex = new Vector3();
  16321. let groupCount = 0;
  16322. const radius = ( top === true ) ? radiusTop : radiusBottom;
  16323. const sign = ( top === true ) ? 1 : - 1;
  16324. // first we generate the center vertex data of the cap.
  16325. // because the geometry needs one set of uvs per face,
  16326. // we must generate a center vertex per face/segment
  16327. for ( let x = 1; x <= radialSegments; x ++ ) {
  16328. // vertex
  16329. vertices.push( 0, halfHeight * sign, 0 );
  16330. // normal
  16331. normals.push( 0, sign, 0 );
  16332. // uv
  16333. uvs.push( 0.5, 0.5 );
  16334. // increase index
  16335. index ++;
  16336. }
  16337. // save the index of the last center vertex
  16338. const centerIndexEnd = index;
  16339. // now we generate the surrounding vertices, normals and uvs
  16340. for ( let x = 0; x <= radialSegments; x ++ ) {
  16341. const u = x / radialSegments;
  16342. const theta = u * thetaLength + thetaStart;
  16343. const cosTheta = Math.cos( theta );
  16344. const sinTheta = Math.sin( theta );
  16345. // vertex
  16346. vertex.x = radius * sinTheta;
  16347. vertex.y = halfHeight * sign;
  16348. vertex.z = radius * cosTheta;
  16349. vertices.push( vertex.x, vertex.y, vertex.z );
  16350. // normal
  16351. normals.push( 0, sign, 0 );
  16352. // uv
  16353. uv.x = ( cosTheta * 0.5 ) + 0.5;
  16354. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  16355. uvs.push( uv.x, uv.y );
  16356. // increase index
  16357. index ++;
  16358. }
  16359. // generate indices
  16360. for ( let x = 0; x < radialSegments; x ++ ) {
  16361. const c = centerIndexStart + x;
  16362. const i = centerIndexEnd + x;
  16363. if ( top === true ) {
  16364. // face top
  16365. indices.push( i, i + 1, c );
  16366. } else {
  16367. // face bottom
  16368. indices.push( i + 1, i, c );
  16369. }
  16370. groupCount += 3;
  16371. }
  16372. // add a group to the geometry. this will ensure multi material support
  16373. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  16374. // calculate new start value for groups
  16375. groupStart += groupCount;
  16376. }
  16377. }
  16378. }
  16379. class ConeGeometry extends CylinderGeometry {
  16380. constructor( radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  16381. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  16382. this.type = 'ConeGeometry';
  16383. this.parameters = {
  16384. radius: radius,
  16385. height: height,
  16386. radialSegments: radialSegments,
  16387. heightSegments: heightSegments,
  16388. openEnded: openEnded,
  16389. thetaStart: thetaStart,
  16390. thetaLength: thetaLength
  16391. };
  16392. }
  16393. }
  16394. class PolyhedronGeometry extends BufferGeometry {
  16395. constructor( vertices, indices, radius = 1, detail = 0 ) {
  16396. super();
  16397. this.type = 'PolyhedronGeometry';
  16398. this.parameters = {
  16399. vertices: vertices,
  16400. indices: indices,
  16401. radius: radius,
  16402. detail: detail
  16403. };
  16404. // default buffer data
  16405. const vertexBuffer = [];
  16406. const uvBuffer = [];
  16407. // the subdivision creates the vertex buffer data
  16408. subdivide( detail );
  16409. // all vertices should lie on a conceptual sphere with a given radius
  16410. applyRadius( radius );
  16411. // finally, create the uv data
  16412. generateUVs();
  16413. // build non-indexed geometry
  16414. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  16415. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  16416. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  16417. if ( detail === 0 ) {
  16418. this.computeVertexNormals(); // flat normals
  16419. } else {
  16420. this.normalizeNormals(); // smooth normals
  16421. }
  16422. // helper functions
  16423. function subdivide( detail ) {
  16424. const a = new Vector3();
  16425. const b = new Vector3();
  16426. const c = new Vector3();
  16427. // iterate over all faces and apply a subdivison with the given detail value
  16428. for ( let i = 0; i < indices.length; i += 3 ) {
  16429. // get the vertices of the face
  16430. getVertexByIndex( indices[ i + 0 ], a );
  16431. getVertexByIndex( indices[ i + 1 ], b );
  16432. getVertexByIndex( indices[ i + 2 ], c );
  16433. // perform subdivision
  16434. subdivideFace( a, b, c, detail );
  16435. }
  16436. }
  16437. function subdivideFace( a, b, c, detail ) {
  16438. const cols = detail + 1;
  16439. // we use this multidimensional array as a data structure for creating the subdivision
  16440. const v = [];
  16441. // construct all of the vertices for this subdivision
  16442. for ( let i = 0; i <= cols; i ++ ) {
  16443. v[ i ] = [];
  16444. const aj = a.clone().lerp( c, i / cols );
  16445. const bj = b.clone().lerp( c, i / cols );
  16446. const rows = cols - i;
  16447. for ( let j = 0; j <= rows; j ++ ) {
  16448. if ( j === 0 && i === cols ) {
  16449. v[ i ][ j ] = aj;
  16450. } else {
  16451. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  16452. }
  16453. }
  16454. }
  16455. // construct all of the faces
  16456. for ( let i = 0; i < cols; i ++ ) {
  16457. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  16458. const k = Math.floor( j / 2 );
  16459. if ( j % 2 === 0 ) {
  16460. pushVertex( v[ i ][ k + 1 ] );
  16461. pushVertex( v[ i + 1 ][ k ] );
  16462. pushVertex( v[ i ][ k ] );
  16463. } else {
  16464. pushVertex( v[ i ][ k + 1 ] );
  16465. pushVertex( v[ i + 1 ][ k + 1 ] );
  16466. pushVertex( v[ i + 1 ][ k ] );
  16467. }
  16468. }
  16469. }
  16470. }
  16471. function applyRadius( radius ) {
  16472. const vertex = new Vector3();
  16473. // iterate over the entire buffer and apply the radius to each vertex
  16474. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  16475. vertex.x = vertexBuffer[ i + 0 ];
  16476. vertex.y = vertexBuffer[ i + 1 ];
  16477. vertex.z = vertexBuffer[ i + 2 ];
  16478. vertex.normalize().multiplyScalar( radius );
  16479. vertexBuffer[ i + 0 ] = vertex.x;
  16480. vertexBuffer[ i + 1 ] = vertex.y;
  16481. vertexBuffer[ i + 2 ] = vertex.z;
  16482. }
  16483. }
  16484. function generateUVs() {
  16485. const vertex = new Vector3();
  16486. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  16487. vertex.x = vertexBuffer[ i + 0 ];
  16488. vertex.y = vertexBuffer[ i + 1 ];
  16489. vertex.z = vertexBuffer[ i + 2 ];
  16490. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  16491. const v = inclination( vertex ) / Math.PI + 0.5;
  16492. uvBuffer.push( u, 1 - v );
  16493. }
  16494. correctUVs();
  16495. correctSeam();
  16496. }
  16497. function correctSeam() {
  16498. // handle case when face straddles the seam, see #3269
  16499. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  16500. // uv data of a single face
  16501. const x0 = uvBuffer[ i + 0 ];
  16502. const x1 = uvBuffer[ i + 2 ];
  16503. const x2 = uvBuffer[ i + 4 ];
  16504. const max = Math.max( x0, x1, x2 );
  16505. const min = Math.min( x0, x1, x2 );
  16506. // 0.9 is somewhat arbitrary
  16507. if ( max > 0.9 && min < 0.1 ) {
  16508. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  16509. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  16510. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  16511. }
  16512. }
  16513. }
  16514. function pushVertex( vertex ) {
  16515. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  16516. }
  16517. function getVertexByIndex( index, vertex ) {
  16518. const stride = index * 3;
  16519. vertex.x = vertices[ stride + 0 ];
  16520. vertex.y = vertices[ stride + 1 ];
  16521. vertex.z = vertices[ stride + 2 ];
  16522. }
  16523. function correctUVs() {
  16524. const a = new Vector3();
  16525. const b = new Vector3();
  16526. const c = new Vector3();
  16527. const centroid = new Vector3();
  16528. const uvA = new Vector2();
  16529. const uvB = new Vector2();
  16530. const uvC = new Vector2();
  16531. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  16532. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  16533. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  16534. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  16535. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  16536. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  16537. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  16538. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  16539. const azi = azimuth( centroid );
  16540. correctUV( uvA, j + 0, a, azi );
  16541. correctUV( uvB, j + 2, b, azi );
  16542. correctUV( uvC, j + 4, c, azi );
  16543. }
  16544. }
  16545. function correctUV( uv, stride, vector, azimuth ) {
  16546. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  16547. uvBuffer[ stride ] = uv.x - 1;
  16548. }
  16549. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  16550. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  16551. }
  16552. }
  16553. // Angle around the Y axis, counter-clockwise when looking from above.
  16554. function azimuth( vector ) {
  16555. return Math.atan2( vector.z, - vector.x );
  16556. }
  16557. // Angle above the XZ plane.
  16558. function inclination( vector ) {
  16559. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  16560. }
  16561. }
  16562. }
  16563. class DodecahedronGeometry extends PolyhedronGeometry {
  16564. constructor( radius = 1, detail = 0 ) {
  16565. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  16566. const r = 1 / t;
  16567. const vertices = [
  16568. // (±1, ±1, ±1)
  16569. - 1, - 1, - 1, - 1, - 1, 1,
  16570. - 1, 1, - 1, - 1, 1, 1,
  16571. 1, - 1, - 1, 1, - 1, 1,
  16572. 1, 1, - 1, 1, 1, 1,
  16573. // (0, ±1/φ, ±φ)
  16574. 0, - r, - t, 0, - r, t,
  16575. 0, r, - t, 0, r, t,
  16576. // (±1/φ, ±φ, 0)
  16577. - r, - t, 0, - r, t, 0,
  16578. r, - t, 0, r, t, 0,
  16579. // (±φ, 0, ±1/φ)
  16580. - t, 0, - r, t, 0, - r,
  16581. - t, 0, r, t, 0, r
  16582. ];
  16583. const indices = [
  16584. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  16585. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  16586. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  16587. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  16588. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  16589. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  16590. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  16591. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  16592. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  16593. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  16594. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  16595. 1, 12, 14, 1, 14, 5, 1, 5, 9
  16596. ];
  16597. super( vertices, indices, radius, detail );
  16598. this.type = 'DodecahedronGeometry';
  16599. this.parameters = {
  16600. radius: radius,
  16601. detail: detail
  16602. };
  16603. }
  16604. }
  16605. const _v0$2 = new Vector3();
  16606. const _v1$5 = new Vector3();
  16607. const _normal$1 = new Vector3();
  16608. const _triangle = new Triangle();
  16609. class EdgesGeometry extends BufferGeometry {
  16610. constructor( geometry, thresholdAngle ) {
  16611. super();
  16612. this.type = 'EdgesGeometry';
  16613. this.parameters = {
  16614. thresholdAngle: thresholdAngle
  16615. };
  16616. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  16617. if ( geometry.isGeometry === true ) {
  16618. console.error( 'THREE.EdgesGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  16619. return;
  16620. }
  16621. const precisionPoints = 4;
  16622. const precision = Math.pow( 10, precisionPoints );
  16623. const thresholdDot = Math.cos( MathUtils.DEG2RAD * thresholdAngle );
  16624. const indexAttr = geometry.getIndex();
  16625. const positionAttr = geometry.getAttribute( 'position' );
  16626. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  16627. const indexArr = [ 0, 0, 0 ];
  16628. const vertKeys = [ 'a', 'b', 'c' ];
  16629. const hashes = new Array( 3 );
  16630. const edgeData = {};
  16631. const vertices = [];
  16632. for ( let i = 0; i < indexCount; i += 3 ) {
  16633. if ( indexAttr ) {
  16634. indexArr[ 0 ] = indexAttr.getX( i );
  16635. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  16636. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  16637. } else {
  16638. indexArr[ 0 ] = i;
  16639. indexArr[ 1 ] = i + 1;
  16640. indexArr[ 2 ] = i + 2;
  16641. }
  16642. const { a, b, c } = _triangle;
  16643. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  16644. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  16645. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  16646. _triangle.getNormal( _normal$1 );
  16647. // create hashes for the edge from the vertices
  16648. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  16649. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  16650. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  16651. // skip degenerate triangles
  16652. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  16653. continue;
  16654. }
  16655. // iterate over every edge
  16656. for ( let j = 0; j < 3; j ++ ) {
  16657. // get the first and next vertex making up the edge
  16658. const jNext = ( j + 1 ) % 3;
  16659. const vecHash0 = hashes[ j ];
  16660. const vecHash1 = hashes[ jNext ];
  16661. const v0 = _triangle[ vertKeys[ j ] ];
  16662. const v1 = _triangle[ vertKeys[ jNext ] ];
  16663. const hash = `${ vecHash0 }_${ vecHash1 }`;
  16664. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  16665. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  16666. // if we found a sibling edge add it into the vertex array if
  16667. // it meets the angle threshold and delete the edge from the map.
  16668. if ( _normal$1.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  16669. vertices.push( v0.x, v0.y, v0.z );
  16670. vertices.push( v1.x, v1.y, v1.z );
  16671. }
  16672. edgeData[ reverseHash ] = null;
  16673. } else if ( ! ( hash in edgeData ) ) {
  16674. // if we've already got an edge here then skip adding a new one
  16675. edgeData[ hash ] = {
  16676. index0: indexArr[ j ],
  16677. index1: indexArr[ jNext ],
  16678. normal: _normal$1.clone(),
  16679. };
  16680. }
  16681. }
  16682. }
  16683. // iterate over all remaining, unmatched edges and add them to the vertex array
  16684. for ( const key in edgeData ) {
  16685. if ( edgeData[ key ] ) {
  16686. const { index0, index1 } = edgeData[ key ];
  16687. _v0$2.fromBufferAttribute( positionAttr, index0 );
  16688. _v1$5.fromBufferAttribute( positionAttr, index1 );
  16689. vertices.push( _v0$2.x, _v0$2.y, _v0$2.z );
  16690. vertices.push( _v1$5.x, _v1$5.y, _v1$5.z );
  16691. }
  16692. }
  16693. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  16694. }
  16695. }
  16696. /**
  16697. * Port from https://github.com/mapbox/earcut (v2.2.2)
  16698. */
  16699. const Earcut = {
  16700. triangulate: function ( data, holeIndices, dim ) {
  16701. dim = dim || 2;
  16702. const hasHoles = holeIndices && holeIndices.length;
  16703. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  16704. let outerNode = linkedList( data, 0, outerLen, dim, true );
  16705. const triangles = [];
  16706. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  16707. let minX, minY, maxX, maxY, x, y, invSize;
  16708. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  16709. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  16710. if ( data.length > 80 * dim ) {
  16711. minX = maxX = data[ 0 ];
  16712. minY = maxY = data[ 1 ];
  16713. for ( let i = dim; i < outerLen; i += dim ) {
  16714. x = data[ i ];
  16715. y = data[ i + 1 ];
  16716. if ( x < minX ) minX = x;
  16717. if ( y < minY ) minY = y;
  16718. if ( x > maxX ) maxX = x;
  16719. if ( y > maxY ) maxY = y;
  16720. }
  16721. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  16722. invSize = Math.max( maxX - minX, maxY - minY );
  16723. invSize = invSize !== 0 ? 1 / invSize : 0;
  16724. }
  16725. earcutLinked( outerNode, triangles, dim, minX, minY, invSize );
  16726. return triangles;
  16727. }
  16728. };
  16729. // create a circular doubly linked list from polygon points in the specified winding order
  16730. function linkedList( data, start, end, dim, clockwise ) {
  16731. let i, last;
  16732. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  16733. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  16734. } else {
  16735. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  16736. }
  16737. if ( last && equals( last, last.next ) ) {
  16738. removeNode( last );
  16739. last = last.next;
  16740. }
  16741. return last;
  16742. }
  16743. // eliminate colinear or duplicate points
  16744. function filterPoints( start, end ) {
  16745. if ( ! start ) return start;
  16746. if ( ! end ) end = start;
  16747. let p = start,
  16748. again;
  16749. do {
  16750. again = false;
  16751. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  16752. removeNode( p );
  16753. p = end = p.prev;
  16754. if ( p === p.next ) break;
  16755. again = true;
  16756. } else {
  16757. p = p.next;
  16758. }
  16759. } while ( again || p !== end );
  16760. return end;
  16761. }
  16762. // main ear slicing loop which triangulates a polygon (given as a linked list)
  16763. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  16764. if ( ! ear ) return;
  16765. // interlink polygon nodes in z-order
  16766. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  16767. let stop = ear,
  16768. prev, next;
  16769. // iterate through ears, slicing them one by one
  16770. while ( ear.prev !== ear.next ) {
  16771. prev = ear.prev;
  16772. next = ear.next;
  16773. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  16774. // cut off the triangle
  16775. triangles.push( prev.i / dim );
  16776. triangles.push( ear.i / dim );
  16777. triangles.push( next.i / dim );
  16778. removeNode( ear );
  16779. // skipping the next vertex leads to less sliver triangles
  16780. ear = next.next;
  16781. stop = next.next;
  16782. continue;
  16783. }
  16784. ear = next;
  16785. // if we looped through the whole remaining polygon and can't find any more ears
  16786. if ( ear === stop ) {
  16787. // try filtering points and slicing again
  16788. if ( ! pass ) {
  16789. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  16790. // if this didn't work, try curing all small self-intersections locally
  16791. } else if ( pass === 1 ) {
  16792. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  16793. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  16794. // as a last resort, try splitting the remaining polygon into two
  16795. } else if ( pass === 2 ) {
  16796. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  16797. }
  16798. break;
  16799. }
  16800. }
  16801. }
  16802. // check whether a polygon node forms a valid ear with adjacent nodes
  16803. function isEar( ear ) {
  16804. const a = ear.prev,
  16805. b = ear,
  16806. c = ear.next;
  16807. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  16808. // now make sure we don't have other points inside the potential ear
  16809. let p = ear.next.next;
  16810. while ( p !== ear.prev ) {
  16811. if ( pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  16812. area( p.prev, p, p.next ) >= 0 ) return false;
  16813. p = p.next;
  16814. }
  16815. return true;
  16816. }
  16817. function isEarHashed( ear, minX, minY, invSize ) {
  16818. const a = ear.prev,
  16819. b = ear,
  16820. c = ear.next;
  16821. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  16822. // triangle bbox; min & max are calculated like this for speed
  16823. const minTX = a.x < b.x ? ( a.x < c.x ? a.x : c.x ) : ( b.x < c.x ? b.x : c.x ),
  16824. minTY = a.y < b.y ? ( a.y < c.y ? a.y : c.y ) : ( b.y < c.y ? b.y : c.y ),
  16825. maxTX = a.x > b.x ? ( a.x > c.x ? a.x : c.x ) : ( b.x > c.x ? b.x : c.x ),
  16826. maxTY = a.y > b.y ? ( a.y > c.y ? a.y : c.y ) : ( b.y > c.y ? b.y : c.y );
  16827. // z-order range for the current triangle bbox;
  16828. const minZ = zOrder( minTX, minTY, minX, minY, invSize ),
  16829. maxZ = zOrder( maxTX, maxTY, minX, minY, invSize );
  16830. let p = ear.prevZ,
  16831. n = ear.nextZ;
  16832. // look for points inside the triangle in both directions
  16833. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  16834. if ( p !== ear.prev && p !== ear.next &&
  16835. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  16836. area( p.prev, p, p.next ) >= 0 ) return false;
  16837. p = p.prevZ;
  16838. if ( n !== ear.prev && n !== ear.next &&
  16839. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  16840. area( n.prev, n, n.next ) >= 0 ) return false;
  16841. n = n.nextZ;
  16842. }
  16843. // look for remaining points in decreasing z-order
  16844. while ( p && p.z >= minZ ) {
  16845. if ( p !== ear.prev && p !== ear.next &&
  16846. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  16847. area( p.prev, p, p.next ) >= 0 ) return false;
  16848. p = p.prevZ;
  16849. }
  16850. // look for remaining points in increasing z-order
  16851. while ( n && n.z <= maxZ ) {
  16852. if ( n !== ear.prev && n !== ear.next &&
  16853. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  16854. area( n.prev, n, n.next ) >= 0 ) return false;
  16855. n = n.nextZ;
  16856. }
  16857. return true;
  16858. }
  16859. // go through all polygon nodes and cure small local self-intersections
  16860. function cureLocalIntersections( start, triangles, dim ) {
  16861. let p = start;
  16862. do {
  16863. const a = p.prev,
  16864. b = p.next.next;
  16865. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  16866. triangles.push( a.i / dim );
  16867. triangles.push( p.i / dim );
  16868. triangles.push( b.i / dim );
  16869. // remove two nodes involved
  16870. removeNode( p );
  16871. removeNode( p.next );
  16872. p = start = b;
  16873. }
  16874. p = p.next;
  16875. } while ( p !== start );
  16876. return filterPoints( p );
  16877. }
  16878. // try splitting polygon into two and triangulate them independently
  16879. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  16880. // look for a valid diagonal that divides the polygon into two
  16881. let a = start;
  16882. do {
  16883. let b = a.next.next;
  16884. while ( b !== a.prev ) {
  16885. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  16886. // split the polygon in two by the diagonal
  16887. let c = splitPolygon( a, b );
  16888. // filter colinear points around the cuts
  16889. a = filterPoints( a, a.next );
  16890. c = filterPoints( c, c.next );
  16891. // run earcut on each half
  16892. earcutLinked( a, triangles, dim, minX, minY, invSize );
  16893. earcutLinked( c, triangles, dim, minX, minY, invSize );
  16894. return;
  16895. }
  16896. b = b.next;
  16897. }
  16898. a = a.next;
  16899. } while ( a !== start );
  16900. }
  16901. // link every hole into the outer loop, producing a single-ring polygon without holes
  16902. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  16903. const queue = [];
  16904. let i, len, start, end, list;
  16905. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  16906. start = holeIndices[ i ] * dim;
  16907. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  16908. list = linkedList( data, start, end, dim, false );
  16909. if ( list === list.next ) list.steiner = true;
  16910. queue.push( getLeftmost( list ) );
  16911. }
  16912. queue.sort( compareX );
  16913. // process holes from left to right
  16914. for ( i = 0; i < queue.length; i ++ ) {
  16915. eliminateHole( queue[ i ], outerNode );
  16916. outerNode = filterPoints( outerNode, outerNode.next );
  16917. }
  16918. return outerNode;
  16919. }
  16920. function compareX( a, b ) {
  16921. return a.x - b.x;
  16922. }
  16923. // find a bridge between vertices that connects hole with an outer ring and and link it
  16924. function eliminateHole( hole, outerNode ) {
  16925. outerNode = findHoleBridge( hole, outerNode );
  16926. if ( outerNode ) {
  16927. const b = splitPolygon( outerNode, hole );
  16928. // filter collinear points around the cuts
  16929. filterPoints( outerNode, outerNode.next );
  16930. filterPoints( b, b.next );
  16931. }
  16932. }
  16933. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  16934. function findHoleBridge( hole, outerNode ) {
  16935. let p = outerNode;
  16936. const hx = hole.x;
  16937. const hy = hole.y;
  16938. let qx = - Infinity, m;
  16939. // find a segment intersected by a ray from the hole's leftmost point to the left;
  16940. // segment's endpoint with lesser x will be potential connection point
  16941. do {
  16942. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  16943. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  16944. if ( x <= hx && x > qx ) {
  16945. qx = x;
  16946. if ( x === hx ) {
  16947. if ( hy === p.y ) return p;
  16948. if ( hy === p.next.y ) return p.next;
  16949. }
  16950. m = p.x < p.next.x ? p : p.next;
  16951. }
  16952. }
  16953. p = p.next;
  16954. } while ( p !== outerNode );
  16955. if ( ! m ) return null;
  16956. if ( hx === qx ) return m; // hole touches outer segment; pick leftmost endpoint
  16957. // look for points inside the triangle of hole point, segment intersection and endpoint;
  16958. // if there are no points found, we have a valid connection;
  16959. // otherwise choose the point of the minimum angle with the ray as connection point
  16960. const stop = m,
  16961. mx = m.x,
  16962. my = m.y;
  16963. let tanMin = Infinity, tan;
  16964. p = m;
  16965. do {
  16966. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  16967. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  16968. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  16969. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  16970. m = p;
  16971. tanMin = tan;
  16972. }
  16973. }
  16974. p = p.next;
  16975. } while ( p !== stop );
  16976. return m;
  16977. }
  16978. // whether sector in vertex m contains sector in vertex p in the same coordinates
  16979. function sectorContainsSector( m, p ) {
  16980. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  16981. }
  16982. // interlink polygon nodes in z-order
  16983. function indexCurve( start, minX, minY, invSize ) {
  16984. let p = start;
  16985. do {
  16986. if ( p.z === null ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  16987. p.prevZ = p.prev;
  16988. p.nextZ = p.next;
  16989. p = p.next;
  16990. } while ( p !== start );
  16991. p.prevZ.nextZ = null;
  16992. p.prevZ = null;
  16993. sortLinked( p );
  16994. }
  16995. // Simon Tatham's linked list merge sort algorithm
  16996. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  16997. function sortLinked( list ) {
  16998. let i, p, q, e, tail, numMerges, pSize, qSize,
  16999. inSize = 1;
  17000. do {
  17001. p = list;
  17002. list = null;
  17003. tail = null;
  17004. numMerges = 0;
  17005. while ( p ) {
  17006. numMerges ++;
  17007. q = p;
  17008. pSize = 0;
  17009. for ( i = 0; i < inSize; i ++ ) {
  17010. pSize ++;
  17011. q = q.nextZ;
  17012. if ( ! q ) break;
  17013. }
  17014. qSize = inSize;
  17015. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  17016. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  17017. e = p;
  17018. p = p.nextZ;
  17019. pSize --;
  17020. } else {
  17021. e = q;
  17022. q = q.nextZ;
  17023. qSize --;
  17024. }
  17025. if ( tail ) tail.nextZ = e;
  17026. else list = e;
  17027. e.prevZ = tail;
  17028. tail = e;
  17029. }
  17030. p = q;
  17031. }
  17032. tail.nextZ = null;
  17033. inSize *= 2;
  17034. } while ( numMerges > 1 );
  17035. return list;
  17036. }
  17037. // z-order of a point given coords and inverse of the longer side of data bbox
  17038. function zOrder( x, y, minX, minY, invSize ) {
  17039. // coords are transformed into non-negative 15-bit integer range
  17040. x = 32767 * ( x - minX ) * invSize;
  17041. y = 32767 * ( y - minY ) * invSize;
  17042. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  17043. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  17044. x = ( x | ( x << 2 ) ) & 0x33333333;
  17045. x = ( x | ( x << 1 ) ) & 0x55555555;
  17046. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  17047. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  17048. y = ( y | ( y << 2 ) ) & 0x33333333;
  17049. y = ( y | ( y << 1 ) ) & 0x55555555;
  17050. return x | ( y << 1 );
  17051. }
  17052. // find the leftmost node of a polygon ring
  17053. function getLeftmost( start ) {
  17054. let p = start,
  17055. leftmost = start;
  17056. do {
  17057. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  17058. p = p.next;
  17059. } while ( p !== start );
  17060. return leftmost;
  17061. }
  17062. // check if a point lies within a convex triangle
  17063. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  17064. return ( cx - px ) * ( ay - py ) - ( ax - px ) * ( cy - py ) >= 0 &&
  17065. ( ax - px ) * ( by - py ) - ( bx - px ) * ( ay - py ) >= 0 &&
  17066. ( bx - px ) * ( cy - py ) - ( cx - px ) * ( by - py ) >= 0;
  17067. }
  17068. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  17069. function isValidDiagonal( a, b ) {
  17070. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  17071. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  17072. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  17073. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  17074. }
  17075. // signed area of a triangle
  17076. function area( p, q, r ) {
  17077. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  17078. }
  17079. // check if two points are equal
  17080. function equals( p1, p2 ) {
  17081. return p1.x === p2.x && p1.y === p2.y;
  17082. }
  17083. // check if two segments intersect
  17084. function intersects( p1, q1, p2, q2 ) {
  17085. const o1 = sign( area( p1, q1, p2 ) );
  17086. const o2 = sign( area( p1, q1, q2 ) );
  17087. const o3 = sign( area( p2, q2, p1 ) );
  17088. const o4 = sign( area( p2, q2, q1 ) );
  17089. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  17090. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  17091. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  17092. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  17093. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  17094. return false;
  17095. }
  17096. // for collinear points p, q, r, check if point q lies on segment pr
  17097. function onSegment( p, q, r ) {
  17098. 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 );
  17099. }
  17100. function sign( num ) {
  17101. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  17102. }
  17103. // check if a polygon diagonal intersects any polygon segments
  17104. function intersectsPolygon( a, b ) {
  17105. let p = a;
  17106. do {
  17107. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  17108. intersects( p, p.next, a, b ) ) return true;
  17109. p = p.next;
  17110. } while ( p !== a );
  17111. return false;
  17112. }
  17113. // check if a polygon diagonal is locally inside the polygon
  17114. function locallyInside( a, b ) {
  17115. return area( a.prev, a, a.next ) < 0 ?
  17116. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  17117. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  17118. }
  17119. // check if the middle point of a polygon diagonal is inside the polygon
  17120. function middleInside( a, b ) {
  17121. let p = a,
  17122. inside = false;
  17123. const px = ( a.x + b.x ) / 2,
  17124. py = ( a.y + b.y ) / 2;
  17125. do {
  17126. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  17127. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  17128. inside = ! inside;
  17129. p = p.next;
  17130. } while ( p !== a );
  17131. return inside;
  17132. }
  17133. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  17134. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  17135. function splitPolygon( a, b ) {
  17136. const a2 = new Node( a.i, a.x, a.y ),
  17137. b2 = new Node( b.i, b.x, b.y ),
  17138. an = a.next,
  17139. bp = b.prev;
  17140. a.next = b;
  17141. b.prev = a;
  17142. a2.next = an;
  17143. an.prev = a2;
  17144. b2.next = a2;
  17145. a2.prev = b2;
  17146. bp.next = b2;
  17147. b2.prev = bp;
  17148. return b2;
  17149. }
  17150. // create a node and optionally link it with previous one (in a circular doubly linked list)
  17151. function insertNode( i, x, y, last ) {
  17152. const p = new Node( i, x, y );
  17153. if ( ! last ) {
  17154. p.prev = p;
  17155. p.next = p;
  17156. } else {
  17157. p.next = last.next;
  17158. p.prev = last;
  17159. last.next.prev = p;
  17160. last.next = p;
  17161. }
  17162. return p;
  17163. }
  17164. function removeNode( p ) {
  17165. p.next.prev = p.prev;
  17166. p.prev.next = p.next;
  17167. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  17168. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  17169. }
  17170. function Node( i, x, y ) {
  17171. // vertex index in coordinates array
  17172. this.i = i;
  17173. // vertex coordinates
  17174. this.x = x;
  17175. this.y = y;
  17176. // previous and next vertex nodes in a polygon ring
  17177. this.prev = null;
  17178. this.next = null;
  17179. // z-order curve value
  17180. this.z = null;
  17181. // previous and next nodes in z-order
  17182. this.prevZ = null;
  17183. this.nextZ = null;
  17184. // indicates whether this is a steiner point
  17185. this.steiner = false;
  17186. }
  17187. function signedArea( data, start, end, dim ) {
  17188. let sum = 0;
  17189. for ( let i = start, j = end - dim; i < end; i += dim ) {
  17190. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  17191. j = i;
  17192. }
  17193. return sum;
  17194. }
  17195. const ShapeUtils = {
  17196. // calculate area of the contour polygon
  17197. area: function ( contour ) {
  17198. const n = contour.length;
  17199. let a = 0.0;
  17200. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  17201. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  17202. }
  17203. return a * 0.5;
  17204. },
  17205. isClockWise: function ( pts ) {
  17206. return ShapeUtils.area( pts ) < 0;
  17207. },
  17208. triangulateShape: function ( contour, holes ) {
  17209. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  17210. const holeIndices = []; // array of hole indices
  17211. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  17212. removeDupEndPts( contour );
  17213. addContour( vertices, contour );
  17214. //
  17215. let holeIndex = contour.length;
  17216. holes.forEach( removeDupEndPts );
  17217. for ( let i = 0; i < holes.length; i ++ ) {
  17218. holeIndices.push( holeIndex );
  17219. holeIndex += holes[ i ].length;
  17220. addContour( vertices, holes[ i ] );
  17221. }
  17222. //
  17223. const triangles = Earcut.triangulate( vertices, holeIndices );
  17224. //
  17225. for ( let i = 0; i < triangles.length; i += 3 ) {
  17226. faces.push( triangles.slice( i, i + 3 ) );
  17227. }
  17228. return faces;
  17229. }
  17230. };
  17231. function removeDupEndPts( points ) {
  17232. const l = points.length;
  17233. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  17234. points.pop();
  17235. }
  17236. }
  17237. function addContour( vertices, contour ) {
  17238. for ( let i = 0; i < contour.length; i ++ ) {
  17239. vertices.push( contour[ i ].x );
  17240. vertices.push( contour[ i ].y );
  17241. }
  17242. }
  17243. /**
  17244. * Creates extruded geometry from a path shape.
  17245. *
  17246. * parameters = {
  17247. *
  17248. * curveSegments: <int>, // number of points on the curves
  17249. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  17250. * depth: <float>, // Depth to extrude the shape
  17251. *
  17252. * bevelEnabled: <bool>, // turn on bevel
  17253. * bevelThickness: <float>, // how deep into the original shape bevel goes
  17254. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  17255. * bevelOffset: <float>, // how far from shape outline does bevel start
  17256. * bevelSegments: <int>, // number of bevel layers
  17257. *
  17258. * extrudePath: <THREE.Curve> // curve to extrude shape along
  17259. *
  17260. * UVGenerator: <Object> // object that provides UV generator functions
  17261. *
  17262. * }
  17263. */
  17264. class ExtrudeGeometry extends BufferGeometry {
  17265. constructor( shapes, options ) {
  17266. super();
  17267. this.type = 'ExtrudeGeometry';
  17268. this.parameters = {
  17269. shapes: shapes,
  17270. options: options
  17271. };
  17272. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  17273. const scope = this;
  17274. const verticesArray = [];
  17275. const uvArray = [];
  17276. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  17277. const shape = shapes[ i ];
  17278. addShape( shape );
  17279. }
  17280. // build geometry
  17281. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  17282. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  17283. this.computeVertexNormals();
  17284. // functions
  17285. function addShape( shape ) {
  17286. const placeholder = [];
  17287. // options
  17288. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  17289. const steps = options.steps !== undefined ? options.steps : 1;
  17290. let depth = options.depth !== undefined ? options.depth : 100;
  17291. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  17292. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  17293. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  17294. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  17295. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  17296. const extrudePath = options.extrudePath;
  17297. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  17298. // deprecated options
  17299. if ( options.amount !== undefined ) {
  17300. console.warn( 'THREE.ExtrudeBufferGeometry: amount has been renamed to depth.' );
  17301. depth = options.amount;
  17302. }
  17303. //
  17304. let extrudePts, extrudeByPath = false;
  17305. let splineTube, binormal, normal, position2;
  17306. if ( extrudePath ) {
  17307. extrudePts = extrudePath.getSpacedPoints( steps );
  17308. extrudeByPath = true;
  17309. bevelEnabled = false; // bevels not supported for path extrusion
  17310. // SETUP TNB variables
  17311. // TODO1 - have a .isClosed in spline?
  17312. splineTube = extrudePath.computeFrenetFrames( steps, false );
  17313. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  17314. binormal = new Vector3();
  17315. normal = new Vector3();
  17316. position2 = new Vector3();
  17317. }
  17318. // Safeguards if bevels are not enabled
  17319. if ( ! bevelEnabled ) {
  17320. bevelSegments = 0;
  17321. bevelThickness = 0;
  17322. bevelSize = 0;
  17323. bevelOffset = 0;
  17324. }
  17325. // Variables initialization
  17326. const shapePoints = shape.extractPoints( curveSegments );
  17327. let vertices = shapePoints.shape;
  17328. const holes = shapePoints.holes;
  17329. const reverse = ! ShapeUtils.isClockWise( vertices );
  17330. if ( reverse ) {
  17331. vertices = vertices.reverse();
  17332. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  17333. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  17334. const ahole = holes[ h ];
  17335. if ( ShapeUtils.isClockWise( ahole ) ) {
  17336. holes[ h ] = ahole.reverse();
  17337. }
  17338. }
  17339. }
  17340. const faces = ShapeUtils.triangulateShape( vertices, holes );
  17341. /* Vertices */
  17342. const contour = vertices; // vertices has all points but contour has only points of circumference
  17343. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  17344. const ahole = holes[ h ];
  17345. vertices = vertices.concat( ahole );
  17346. }
  17347. function scalePt2( pt, vec, size ) {
  17348. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  17349. return vec.clone().multiplyScalar( size ).add( pt );
  17350. }
  17351. const vlen = vertices.length, flen = faces.length;
  17352. // Find directions for point movement
  17353. function getBevelVec( inPt, inPrev, inNext ) {
  17354. // computes for inPt the corresponding point inPt' on a new contour
  17355. // shifted by 1 unit (length of normalized vector) to the left
  17356. // if we walk along contour clockwise, this new contour is outside the old one
  17357. //
  17358. // inPt' is the intersection of the two lines parallel to the two
  17359. // adjacent edges of inPt at a distance of 1 unit on the left side.
  17360. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  17361. // good reading for geometry algorithms (here: line-line intersection)
  17362. // http://geomalgorithms.com/a05-_intersect-1.html
  17363. const v_prev_x = inPt.x - inPrev.x,
  17364. v_prev_y = inPt.y - inPrev.y;
  17365. const v_next_x = inNext.x - inPt.x,
  17366. v_next_y = inNext.y - inPt.y;
  17367. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  17368. // check for collinear edges
  17369. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  17370. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  17371. // not collinear
  17372. // length of vectors for normalizing
  17373. const v_prev_len = Math.sqrt( v_prev_lensq );
  17374. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  17375. // shift adjacent points by unit vectors to the left
  17376. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  17377. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  17378. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  17379. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  17380. // scaling factor for v_prev to intersection point
  17381. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  17382. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  17383. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  17384. // vector from inPt to intersection point
  17385. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  17386. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  17387. // Don't normalize!, otherwise sharp corners become ugly
  17388. // but prevent crazy spikes
  17389. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  17390. if ( v_trans_lensq <= 2 ) {
  17391. return new Vector2( v_trans_x, v_trans_y );
  17392. } else {
  17393. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  17394. }
  17395. } else {
  17396. // handle special case of collinear edges
  17397. let direction_eq = false; // assumes: opposite
  17398. if ( v_prev_x > Number.EPSILON ) {
  17399. if ( v_next_x > Number.EPSILON ) {
  17400. direction_eq = true;
  17401. }
  17402. } else {
  17403. if ( v_prev_x < - Number.EPSILON ) {
  17404. if ( v_next_x < - Number.EPSILON ) {
  17405. direction_eq = true;
  17406. }
  17407. } else {
  17408. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  17409. direction_eq = true;
  17410. }
  17411. }
  17412. }
  17413. if ( direction_eq ) {
  17414. // console.log("Warning: lines are a straight sequence");
  17415. v_trans_x = - v_prev_y;
  17416. v_trans_y = v_prev_x;
  17417. shrink_by = Math.sqrt( v_prev_lensq );
  17418. } else {
  17419. // console.log("Warning: lines are a straight spike");
  17420. v_trans_x = v_prev_x;
  17421. v_trans_y = v_prev_y;
  17422. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  17423. }
  17424. }
  17425. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  17426. }
  17427. const contourMovements = [];
  17428. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  17429. if ( j === il ) j = 0;
  17430. if ( k === il ) k = 0;
  17431. // (j)---(i)---(k)
  17432. // console.log('i,j,k', i, j , k)
  17433. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  17434. }
  17435. const holesMovements = [];
  17436. let oneHoleMovements, verticesMovements = contourMovements.concat();
  17437. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  17438. const ahole = holes[ h ];
  17439. oneHoleMovements = [];
  17440. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  17441. if ( j === il ) j = 0;
  17442. if ( k === il ) k = 0;
  17443. // (j)---(i)---(k)
  17444. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  17445. }
  17446. holesMovements.push( oneHoleMovements );
  17447. verticesMovements = verticesMovements.concat( oneHoleMovements );
  17448. }
  17449. // Loop bevelSegments, 1 for the front, 1 for the back
  17450. for ( let b = 0; b < bevelSegments; b ++ ) {
  17451. //for ( b = bevelSegments; b > 0; b -- ) {
  17452. const t = b / bevelSegments;
  17453. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  17454. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  17455. // contract shape
  17456. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  17457. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  17458. v( vert.x, vert.y, - z );
  17459. }
  17460. // expand holes
  17461. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  17462. const ahole = holes[ h ];
  17463. oneHoleMovements = holesMovements[ h ];
  17464. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  17465. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  17466. v( vert.x, vert.y, - z );
  17467. }
  17468. }
  17469. }
  17470. const bs = bevelSize + bevelOffset;
  17471. // Back facing vertices
  17472. for ( let i = 0; i < vlen; i ++ ) {
  17473. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  17474. if ( ! extrudeByPath ) {
  17475. v( vert.x, vert.y, 0 );
  17476. } else {
  17477. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  17478. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  17479. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  17480. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  17481. v( position2.x, position2.y, position2.z );
  17482. }
  17483. }
  17484. // Add stepped vertices...
  17485. // Including front facing vertices
  17486. for ( let s = 1; s <= steps; s ++ ) {
  17487. for ( let i = 0; i < vlen; i ++ ) {
  17488. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  17489. if ( ! extrudeByPath ) {
  17490. v( vert.x, vert.y, depth / steps * s );
  17491. } else {
  17492. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  17493. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  17494. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  17495. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  17496. v( position2.x, position2.y, position2.z );
  17497. }
  17498. }
  17499. }
  17500. // Add bevel segments planes
  17501. //for ( b = 1; b <= bevelSegments; b ++ ) {
  17502. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  17503. const t = b / bevelSegments;
  17504. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  17505. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  17506. // contract shape
  17507. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  17508. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  17509. v( vert.x, vert.y, depth + z );
  17510. }
  17511. // expand holes
  17512. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  17513. const ahole = holes[ h ];
  17514. oneHoleMovements = holesMovements[ h ];
  17515. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  17516. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  17517. if ( ! extrudeByPath ) {
  17518. v( vert.x, vert.y, depth + z );
  17519. } else {
  17520. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  17521. }
  17522. }
  17523. }
  17524. }
  17525. /* Faces */
  17526. // Top and bottom faces
  17527. buildLidFaces();
  17528. // Sides faces
  17529. buildSideFaces();
  17530. ///// Internal functions
  17531. function buildLidFaces() {
  17532. const start = verticesArray.length / 3;
  17533. if ( bevelEnabled ) {
  17534. let layer = 0; // steps + 1
  17535. let offset = vlen * layer;
  17536. // Bottom faces
  17537. for ( let i = 0; i < flen; i ++ ) {
  17538. const face = faces[ i ];
  17539. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  17540. }
  17541. layer = steps + bevelSegments * 2;
  17542. offset = vlen * layer;
  17543. // Top faces
  17544. for ( let i = 0; i < flen; i ++ ) {
  17545. const face = faces[ i ];
  17546. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  17547. }
  17548. } else {
  17549. // Bottom faces
  17550. for ( let i = 0; i < flen; i ++ ) {
  17551. const face = faces[ i ];
  17552. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  17553. }
  17554. // Top faces
  17555. for ( let i = 0; i < flen; i ++ ) {
  17556. const face = faces[ i ];
  17557. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  17558. }
  17559. }
  17560. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  17561. }
  17562. // Create faces for the z-sides of the shape
  17563. function buildSideFaces() {
  17564. const start = verticesArray.length / 3;
  17565. let layeroffset = 0;
  17566. sidewalls( contour, layeroffset );
  17567. layeroffset += contour.length;
  17568. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  17569. const ahole = holes[ h ];
  17570. sidewalls( ahole, layeroffset );
  17571. //, true
  17572. layeroffset += ahole.length;
  17573. }
  17574. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  17575. }
  17576. function sidewalls( contour, layeroffset ) {
  17577. let i = contour.length;
  17578. while ( -- i >= 0 ) {
  17579. const j = i;
  17580. let k = i - 1;
  17581. if ( k < 0 ) k = contour.length - 1;
  17582. //console.log('b', i,j, i-1, k,vertices.length);
  17583. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  17584. const slen1 = vlen * s;
  17585. const slen2 = vlen * ( s + 1 );
  17586. const a = layeroffset + j + slen1,
  17587. b = layeroffset + k + slen1,
  17588. c = layeroffset + k + slen2,
  17589. d = layeroffset + j + slen2;
  17590. f4( a, b, c, d );
  17591. }
  17592. }
  17593. }
  17594. function v( x, y, z ) {
  17595. placeholder.push( x );
  17596. placeholder.push( y );
  17597. placeholder.push( z );
  17598. }
  17599. function f3( a, b, c ) {
  17600. addVertex( a );
  17601. addVertex( b );
  17602. addVertex( c );
  17603. const nextIndex = verticesArray.length / 3;
  17604. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  17605. addUV( uvs[ 0 ] );
  17606. addUV( uvs[ 1 ] );
  17607. addUV( uvs[ 2 ] );
  17608. }
  17609. function f4( a, b, c, d ) {
  17610. addVertex( a );
  17611. addVertex( b );
  17612. addVertex( d );
  17613. addVertex( b );
  17614. addVertex( c );
  17615. addVertex( d );
  17616. const nextIndex = verticesArray.length / 3;
  17617. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  17618. addUV( uvs[ 0 ] );
  17619. addUV( uvs[ 1 ] );
  17620. addUV( uvs[ 3 ] );
  17621. addUV( uvs[ 1 ] );
  17622. addUV( uvs[ 2 ] );
  17623. addUV( uvs[ 3 ] );
  17624. }
  17625. function addVertex( index ) {
  17626. verticesArray.push( placeholder[ index * 3 + 0 ] );
  17627. verticesArray.push( placeholder[ index * 3 + 1 ] );
  17628. verticesArray.push( placeholder[ index * 3 + 2 ] );
  17629. }
  17630. function addUV( vector2 ) {
  17631. uvArray.push( vector2.x );
  17632. uvArray.push( vector2.y );
  17633. }
  17634. }
  17635. }
  17636. toJSON() {
  17637. const data = BufferGeometry.prototype.toJSON.call( this );
  17638. const shapes = this.parameters.shapes;
  17639. const options = this.parameters.options;
  17640. return toJSON( shapes, options, data );
  17641. }
  17642. }
  17643. const WorldUVGenerator = {
  17644. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  17645. const a_x = vertices[ indexA * 3 ];
  17646. const a_y = vertices[ indexA * 3 + 1 ];
  17647. const b_x = vertices[ indexB * 3 ];
  17648. const b_y = vertices[ indexB * 3 + 1 ];
  17649. const c_x = vertices[ indexC * 3 ];
  17650. const c_y = vertices[ indexC * 3 + 1 ];
  17651. return [
  17652. new Vector2( a_x, a_y ),
  17653. new Vector2( b_x, b_y ),
  17654. new Vector2( c_x, c_y )
  17655. ];
  17656. },
  17657. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  17658. const a_x = vertices[ indexA * 3 ];
  17659. const a_y = vertices[ indexA * 3 + 1 ];
  17660. const a_z = vertices[ indexA * 3 + 2 ];
  17661. const b_x = vertices[ indexB * 3 ];
  17662. const b_y = vertices[ indexB * 3 + 1 ];
  17663. const b_z = vertices[ indexB * 3 + 2 ];
  17664. const c_x = vertices[ indexC * 3 ];
  17665. const c_y = vertices[ indexC * 3 + 1 ];
  17666. const c_z = vertices[ indexC * 3 + 2 ];
  17667. const d_x = vertices[ indexD * 3 ];
  17668. const d_y = vertices[ indexD * 3 + 1 ];
  17669. const d_z = vertices[ indexD * 3 + 2 ];
  17670. if ( Math.abs( a_y - b_y ) < 0.01 ) {
  17671. return [
  17672. new Vector2( a_x, 1 - a_z ),
  17673. new Vector2( b_x, 1 - b_z ),
  17674. new Vector2( c_x, 1 - c_z ),
  17675. new Vector2( d_x, 1 - d_z )
  17676. ];
  17677. } else {
  17678. return [
  17679. new Vector2( a_y, 1 - a_z ),
  17680. new Vector2( b_y, 1 - b_z ),
  17681. new Vector2( c_y, 1 - c_z ),
  17682. new Vector2( d_y, 1 - d_z )
  17683. ];
  17684. }
  17685. }
  17686. };
  17687. function toJSON( shapes, options, data ) {
  17688. data.shapes = [];
  17689. if ( Array.isArray( shapes ) ) {
  17690. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  17691. const shape = shapes[ i ];
  17692. data.shapes.push( shape.uuid );
  17693. }
  17694. } else {
  17695. data.shapes.push( shapes.uuid );
  17696. }
  17697. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  17698. return data;
  17699. }
  17700. class IcosahedronGeometry extends PolyhedronGeometry {
  17701. constructor( radius = 1, detail = 0 ) {
  17702. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  17703. const vertices = [
  17704. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  17705. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  17706. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  17707. ];
  17708. const indices = [
  17709. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  17710. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  17711. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  17712. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  17713. ];
  17714. super( vertices, indices, radius, detail );
  17715. this.type = 'IcosahedronGeometry';
  17716. this.parameters = {
  17717. radius: radius,
  17718. detail: detail
  17719. };
  17720. }
  17721. }
  17722. class LatheGeometry extends BufferGeometry {
  17723. constructor( points, segments = 12, phiStart = 0, phiLength = Math.PI * 2 ) {
  17724. super();
  17725. this.type = 'LatheGeometry';
  17726. this.parameters = {
  17727. points: points,
  17728. segments: segments,
  17729. phiStart: phiStart,
  17730. phiLength: phiLength
  17731. };
  17732. segments = Math.floor( segments );
  17733. // clamp phiLength so it's in range of [ 0, 2PI ]
  17734. phiLength = MathUtils.clamp( phiLength, 0, Math.PI * 2 );
  17735. // buffers
  17736. const indices = [];
  17737. const vertices = [];
  17738. const uvs = [];
  17739. // helper variables
  17740. const inverseSegments = 1.0 / segments;
  17741. const vertex = new Vector3();
  17742. const uv = new Vector2();
  17743. // generate vertices and uvs
  17744. for ( let i = 0; i <= segments; i ++ ) {
  17745. const phi = phiStart + i * inverseSegments * phiLength;
  17746. const sin = Math.sin( phi );
  17747. const cos = Math.cos( phi );
  17748. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  17749. // vertex
  17750. vertex.x = points[ j ].x * sin;
  17751. vertex.y = points[ j ].y;
  17752. vertex.z = points[ j ].x * cos;
  17753. vertices.push( vertex.x, vertex.y, vertex.z );
  17754. // uv
  17755. uv.x = i / segments;
  17756. uv.y = j / ( points.length - 1 );
  17757. uvs.push( uv.x, uv.y );
  17758. }
  17759. }
  17760. // indices
  17761. for ( let i = 0; i < segments; i ++ ) {
  17762. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  17763. const base = j + i * points.length;
  17764. const a = base;
  17765. const b = base + points.length;
  17766. const c = base + points.length + 1;
  17767. const d = base + 1;
  17768. // faces
  17769. indices.push( a, b, d );
  17770. indices.push( b, c, d );
  17771. }
  17772. }
  17773. // build geometry
  17774. this.setIndex( indices );
  17775. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  17776. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  17777. // generate normals
  17778. this.computeVertexNormals();
  17779. // if the geometry is closed, we need to average the normals along the seam.
  17780. // because the corresponding vertices are identical (but still have different UVs).
  17781. if ( phiLength === Math.PI * 2 ) {
  17782. const normals = this.attributes.normal.array;
  17783. const n1 = new Vector3();
  17784. const n2 = new Vector3();
  17785. const n = new Vector3();
  17786. // this is the buffer offset for the last line of vertices
  17787. const base = segments * points.length * 3;
  17788. for ( let i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  17789. // select the normal of the vertex in the first line
  17790. n1.x = normals[ j + 0 ];
  17791. n1.y = normals[ j + 1 ];
  17792. n1.z = normals[ j + 2 ];
  17793. // select the normal of the vertex in the last line
  17794. n2.x = normals[ base + j + 0 ];
  17795. n2.y = normals[ base + j + 1 ];
  17796. n2.z = normals[ base + j + 2 ];
  17797. // average normals
  17798. n.addVectors( n1, n2 ).normalize();
  17799. // assign the new values to both normals
  17800. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  17801. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  17802. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  17803. }
  17804. }
  17805. }
  17806. }
  17807. class OctahedronGeometry extends PolyhedronGeometry {
  17808. constructor( radius = 1, detail = 0 ) {
  17809. const vertices = [
  17810. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  17811. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  17812. ];
  17813. const indices = [
  17814. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  17815. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  17816. 1, 3, 4, 1, 4, 2
  17817. ];
  17818. super( vertices, indices, radius, detail );
  17819. this.type = 'OctahedronGeometry';
  17820. this.parameters = {
  17821. radius: radius,
  17822. detail: detail
  17823. };
  17824. }
  17825. }
  17826. /**
  17827. * Parametric Surfaces Geometry
  17828. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  17829. */
  17830. function ParametricGeometry( func, slices, stacks ) {
  17831. BufferGeometry.call( this );
  17832. this.type = 'ParametricGeometry';
  17833. this.parameters = {
  17834. func: func,
  17835. slices: slices,
  17836. stacks: stacks
  17837. };
  17838. // buffers
  17839. const indices = [];
  17840. const vertices = [];
  17841. const normals = [];
  17842. const uvs = [];
  17843. const EPS = 0.00001;
  17844. const normal = new Vector3();
  17845. const p0 = new Vector3(), p1 = new Vector3();
  17846. const pu = new Vector3(), pv = new Vector3();
  17847. if ( func.length < 3 ) {
  17848. console.error( 'THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.' );
  17849. }
  17850. // generate vertices, normals and uvs
  17851. const sliceCount = slices + 1;
  17852. for ( let i = 0; i <= stacks; i ++ ) {
  17853. const v = i / stacks;
  17854. for ( let j = 0; j <= slices; j ++ ) {
  17855. const u = j / slices;
  17856. // vertex
  17857. func( u, v, p0 );
  17858. vertices.push( p0.x, p0.y, p0.z );
  17859. // normal
  17860. // approximate tangent vectors via finite differences
  17861. if ( u - EPS >= 0 ) {
  17862. func( u - EPS, v, p1 );
  17863. pu.subVectors( p0, p1 );
  17864. } else {
  17865. func( u + EPS, v, p1 );
  17866. pu.subVectors( p1, p0 );
  17867. }
  17868. if ( v - EPS >= 0 ) {
  17869. func( u, v - EPS, p1 );
  17870. pv.subVectors( p0, p1 );
  17871. } else {
  17872. func( u, v + EPS, p1 );
  17873. pv.subVectors( p1, p0 );
  17874. }
  17875. // cross product of tangent vectors returns surface normal
  17876. normal.crossVectors( pu, pv ).normalize();
  17877. normals.push( normal.x, normal.y, normal.z );
  17878. // uv
  17879. uvs.push( u, v );
  17880. }
  17881. }
  17882. // generate indices
  17883. for ( let i = 0; i < stacks; i ++ ) {
  17884. for ( let j = 0; j < slices; j ++ ) {
  17885. const a = i * sliceCount + j;
  17886. const b = i * sliceCount + j + 1;
  17887. const c = ( i + 1 ) * sliceCount + j + 1;
  17888. const d = ( i + 1 ) * sliceCount + j;
  17889. // faces one and two
  17890. indices.push( a, b, d );
  17891. indices.push( b, c, d );
  17892. }
  17893. }
  17894. // build geometry
  17895. this.setIndex( indices );
  17896. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  17897. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  17898. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  17899. }
  17900. ParametricGeometry.prototype = Object.create( BufferGeometry.prototype );
  17901. ParametricGeometry.prototype.constructor = ParametricGeometry;
  17902. class RingGeometry extends BufferGeometry {
  17903. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  17904. super();
  17905. this.type = 'RingGeometry';
  17906. this.parameters = {
  17907. innerRadius: innerRadius,
  17908. outerRadius: outerRadius,
  17909. thetaSegments: thetaSegments,
  17910. phiSegments: phiSegments,
  17911. thetaStart: thetaStart,
  17912. thetaLength: thetaLength
  17913. };
  17914. thetaSegments = Math.max( 3, thetaSegments );
  17915. phiSegments = Math.max( 1, phiSegments );
  17916. // buffers
  17917. const indices = [];
  17918. const vertices = [];
  17919. const normals = [];
  17920. const uvs = [];
  17921. // some helper variables
  17922. let radius = innerRadius;
  17923. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  17924. const vertex = new Vector3();
  17925. const uv = new Vector2();
  17926. // generate vertices, normals and uvs
  17927. for ( let j = 0; j <= phiSegments; j ++ ) {
  17928. for ( let i = 0; i <= thetaSegments; i ++ ) {
  17929. // values are generate from the inside of the ring to the outside
  17930. const segment = thetaStart + i / thetaSegments * thetaLength;
  17931. // vertex
  17932. vertex.x = radius * Math.cos( segment );
  17933. vertex.y = radius * Math.sin( segment );
  17934. vertices.push( vertex.x, vertex.y, vertex.z );
  17935. // normal
  17936. normals.push( 0, 0, 1 );
  17937. // uv
  17938. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  17939. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  17940. uvs.push( uv.x, uv.y );
  17941. }
  17942. // increase the radius for next row of vertices
  17943. radius += radiusStep;
  17944. }
  17945. // indices
  17946. for ( let j = 0; j < phiSegments; j ++ ) {
  17947. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  17948. for ( let i = 0; i < thetaSegments; i ++ ) {
  17949. const segment = i + thetaSegmentLevel;
  17950. const a = segment;
  17951. const b = segment + thetaSegments + 1;
  17952. const c = segment + thetaSegments + 2;
  17953. const d = segment + 1;
  17954. // faces
  17955. indices.push( a, b, d );
  17956. indices.push( b, c, d );
  17957. }
  17958. }
  17959. // build geometry
  17960. this.setIndex( indices );
  17961. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  17962. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  17963. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  17964. }
  17965. }
  17966. class ShapeGeometry extends BufferGeometry {
  17967. constructor( shapes, curveSegments = 12 ) {
  17968. super();
  17969. this.type = 'ShapeGeometry';
  17970. this.parameters = {
  17971. shapes: shapes,
  17972. curveSegments: curveSegments
  17973. };
  17974. // buffers
  17975. const indices = [];
  17976. const vertices = [];
  17977. const normals = [];
  17978. const uvs = [];
  17979. // helper variables
  17980. let groupStart = 0;
  17981. let groupCount = 0;
  17982. // allow single and array values for "shapes" parameter
  17983. if ( Array.isArray( shapes ) === false ) {
  17984. addShape( shapes );
  17985. } else {
  17986. for ( let i = 0; i < shapes.length; i ++ ) {
  17987. addShape( shapes[ i ] );
  17988. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  17989. groupStart += groupCount;
  17990. groupCount = 0;
  17991. }
  17992. }
  17993. // build geometry
  17994. this.setIndex( indices );
  17995. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  17996. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  17997. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  17998. // helper functions
  17999. function addShape( shape ) {
  18000. const indexOffset = vertices.length / 3;
  18001. const points = shape.extractPoints( curveSegments );
  18002. let shapeVertices = points.shape;
  18003. const shapeHoles = points.holes;
  18004. // check direction of vertices
  18005. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  18006. shapeVertices = shapeVertices.reverse();
  18007. }
  18008. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  18009. const shapeHole = shapeHoles[ i ];
  18010. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  18011. shapeHoles[ i ] = shapeHole.reverse();
  18012. }
  18013. }
  18014. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  18015. // join vertices of inner and outer paths to a single array
  18016. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  18017. const shapeHole = shapeHoles[ i ];
  18018. shapeVertices = shapeVertices.concat( shapeHole );
  18019. }
  18020. // vertices, normals, uvs
  18021. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  18022. const vertex = shapeVertices[ i ];
  18023. vertices.push( vertex.x, vertex.y, 0 );
  18024. normals.push( 0, 0, 1 );
  18025. uvs.push( vertex.x, vertex.y ); // world uvs
  18026. }
  18027. // incides
  18028. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  18029. const face = faces[ i ];
  18030. const a = face[ 0 ] + indexOffset;
  18031. const b = face[ 1 ] + indexOffset;
  18032. const c = face[ 2 ] + indexOffset;
  18033. indices.push( a, b, c );
  18034. groupCount += 3;
  18035. }
  18036. }
  18037. }
  18038. toJSON() {
  18039. const data = BufferGeometry.prototype.toJSON.call( this );
  18040. const shapes = this.parameters.shapes;
  18041. return toJSON$1( shapes, data );
  18042. }
  18043. }
  18044. function toJSON$1( shapes, data ) {
  18045. data.shapes = [];
  18046. if ( Array.isArray( shapes ) ) {
  18047. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  18048. const shape = shapes[ i ];
  18049. data.shapes.push( shape.uuid );
  18050. }
  18051. } else {
  18052. data.shapes.push( shapes.uuid );
  18053. }
  18054. return data;
  18055. }
  18056. class SphereGeometry extends BufferGeometry {
  18057. constructor( radius = 1, widthSegments = 8, heightSegments = 6, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  18058. super();
  18059. this.type = 'SphereGeometry';
  18060. this.parameters = {
  18061. radius: radius,
  18062. widthSegments: widthSegments,
  18063. heightSegments: heightSegments,
  18064. phiStart: phiStart,
  18065. phiLength: phiLength,
  18066. thetaStart: thetaStart,
  18067. thetaLength: thetaLength
  18068. };
  18069. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  18070. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  18071. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  18072. let index = 0;
  18073. const grid = [];
  18074. const vertex = new Vector3();
  18075. const normal = new Vector3();
  18076. // buffers
  18077. const indices = [];
  18078. const vertices = [];
  18079. const normals = [];
  18080. const uvs = [];
  18081. // generate vertices, normals and uvs
  18082. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  18083. const verticesRow = [];
  18084. const v = iy / heightSegments;
  18085. // special case for the poles
  18086. let uOffset = 0;
  18087. if ( iy == 0 && thetaStart == 0 ) {
  18088. uOffset = 0.5 / widthSegments;
  18089. } else if ( iy == heightSegments && thetaEnd == Math.PI ) {
  18090. uOffset = - 0.5 / widthSegments;
  18091. }
  18092. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  18093. const u = ix / widthSegments;
  18094. // vertex
  18095. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  18096. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  18097. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  18098. vertices.push( vertex.x, vertex.y, vertex.z );
  18099. // normal
  18100. normal.copy( vertex ).normalize();
  18101. normals.push( normal.x, normal.y, normal.z );
  18102. // uv
  18103. uvs.push( u + uOffset, 1 - v );
  18104. verticesRow.push( index ++ );
  18105. }
  18106. grid.push( verticesRow );
  18107. }
  18108. // indices
  18109. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  18110. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  18111. const a = grid[ iy ][ ix + 1 ];
  18112. const b = grid[ iy ][ ix ];
  18113. const c = grid[ iy + 1 ][ ix ];
  18114. const d = grid[ iy + 1 ][ ix + 1 ];
  18115. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  18116. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  18117. }
  18118. }
  18119. // build geometry
  18120. this.setIndex( indices );
  18121. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18122. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  18123. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  18124. }
  18125. }
  18126. class TetrahedronGeometry extends PolyhedronGeometry {
  18127. constructor( radius = 1, detail = 0 ) {
  18128. const vertices = [
  18129. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  18130. ];
  18131. const indices = [
  18132. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  18133. ];
  18134. super( vertices, indices, radius, detail );
  18135. this.type = 'TetrahedronGeometry';
  18136. this.parameters = {
  18137. radius: radius,
  18138. detail: detail
  18139. };
  18140. }
  18141. }
  18142. /**
  18143. * Text = 3D Text
  18144. *
  18145. * parameters = {
  18146. * font: <THREE.Font>, // font
  18147. *
  18148. * size: <float>, // size of the text
  18149. * height: <float>, // thickness to extrude text
  18150. * curveSegments: <int>, // number of points on the curves
  18151. *
  18152. * bevelEnabled: <bool>, // turn on bevel
  18153. * bevelThickness: <float>, // how deep into text bevel goes
  18154. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  18155. * bevelOffset: <float> // how far from text outline does bevel start
  18156. * }
  18157. */
  18158. class TextGeometry extends ExtrudeGeometry {
  18159. constructor( text, parameters = {} ) {
  18160. const font = parameters.font;
  18161. if ( ! ( font && font.isFont ) ) {
  18162. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  18163. return new BufferGeometry();
  18164. }
  18165. const shapes = font.generateShapes( text, parameters.size );
  18166. // translate parameters to ExtrudeGeometry API
  18167. parameters.depth = parameters.height !== undefined ? parameters.height : 50;
  18168. // defaults
  18169. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  18170. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  18171. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  18172. super( shapes, parameters );
  18173. this.type = 'TextGeometry';
  18174. }
  18175. }
  18176. class TorusGeometry extends BufferGeometry {
  18177. constructor( radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2 ) {
  18178. super();
  18179. this.type = 'TorusGeometry';
  18180. this.parameters = {
  18181. radius: radius,
  18182. tube: tube,
  18183. radialSegments: radialSegments,
  18184. tubularSegments: tubularSegments,
  18185. arc: arc
  18186. };
  18187. radialSegments = Math.floor( radialSegments );
  18188. tubularSegments = Math.floor( tubularSegments );
  18189. // buffers
  18190. const indices = [];
  18191. const vertices = [];
  18192. const normals = [];
  18193. const uvs = [];
  18194. // helper variables
  18195. const center = new Vector3();
  18196. const vertex = new Vector3();
  18197. const normal = new Vector3();
  18198. // generate vertices, normals and uvs
  18199. for ( let j = 0; j <= radialSegments; j ++ ) {
  18200. for ( let i = 0; i <= tubularSegments; i ++ ) {
  18201. const u = i / tubularSegments * arc;
  18202. const v = j / radialSegments * Math.PI * 2;
  18203. // vertex
  18204. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  18205. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  18206. vertex.z = tube * Math.sin( v );
  18207. vertices.push( vertex.x, vertex.y, vertex.z );
  18208. // normal
  18209. center.x = radius * Math.cos( u );
  18210. center.y = radius * Math.sin( u );
  18211. normal.subVectors( vertex, center ).normalize();
  18212. normals.push( normal.x, normal.y, normal.z );
  18213. // uv
  18214. uvs.push( i / tubularSegments );
  18215. uvs.push( j / radialSegments );
  18216. }
  18217. }
  18218. // generate indices
  18219. for ( let j = 1; j <= radialSegments; j ++ ) {
  18220. for ( let i = 1; i <= tubularSegments; i ++ ) {
  18221. // indices
  18222. const a = ( tubularSegments + 1 ) * j + i - 1;
  18223. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  18224. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  18225. const d = ( tubularSegments + 1 ) * j + i;
  18226. // faces
  18227. indices.push( a, b, d );
  18228. indices.push( b, c, d );
  18229. }
  18230. }
  18231. // build geometry
  18232. this.setIndex( indices );
  18233. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18234. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  18235. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  18236. }
  18237. }
  18238. class TorusKnotGeometry extends BufferGeometry {
  18239. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  18240. super();
  18241. this.type = 'TorusKnotGeometry';
  18242. this.parameters = {
  18243. radius: radius,
  18244. tube: tube,
  18245. tubularSegments: tubularSegments,
  18246. radialSegments: radialSegments,
  18247. p: p,
  18248. q: q
  18249. };
  18250. tubularSegments = Math.floor( tubularSegments );
  18251. radialSegments = Math.floor( radialSegments );
  18252. // buffers
  18253. const indices = [];
  18254. const vertices = [];
  18255. const normals = [];
  18256. const uvs = [];
  18257. // helper variables
  18258. const vertex = new Vector3();
  18259. const normal = new Vector3();
  18260. const P1 = new Vector3();
  18261. const P2 = new Vector3();
  18262. const B = new Vector3();
  18263. const T = new Vector3();
  18264. const N = new Vector3();
  18265. // generate vertices, normals and uvs
  18266. for ( let i = 0; i <= tubularSegments; ++ i ) {
  18267. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  18268. const u = i / tubularSegments * p * Math.PI * 2;
  18269. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  18270. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  18271. calculatePositionOnCurve( u, p, q, radius, P1 );
  18272. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  18273. // calculate orthonormal basis
  18274. T.subVectors( P2, P1 );
  18275. N.addVectors( P2, P1 );
  18276. B.crossVectors( T, N );
  18277. N.crossVectors( B, T );
  18278. // normalize B, N. T can be ignored, we don't use it
  18279. B.normalize();
  18280. N.normalize();
  18281. for ( let j = 0; j <= radialSegments; ++ j ) {
  18282. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  18283. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  18284. const v = j / radialSegments * Math.PI * 2;
  18285. const cx = - tube * Math.cos( v );
  18286. const cy = tube * Math.sin( v );
  18287. // now calculate the final vertex position.
  18288. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  18289. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  18290. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  18291. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  18292. vertices.push( vertex.x, vertex.y, vertex.z );
  18293. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  18294. normal.subVectors( vertex, P1 ).normalize();
  18295. normals.push( normal.x, normal.y, normal.z );
  18296. // uv
  18297. uvs.push( i / tubularSegments );
  18298. uvs.push( j / radialSegments );
  18299. }
  18300. }
  18301. // generate indices
  18302. for ( let j = 1; j <= tubularSegments; j ++ ) {
  18303. for ( let i = 1; i <= radialSegments; i ++ ) {
  18304. // indices
  18305. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  18306. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  18307. const c = ( radialSegments + 1 ) * j + i;
  18308. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  18309. // faces
  18310. indices.push( a, b, d );
  18311. indices.push( b, c, d );
  18312. }
  18313. }
  18314. // build geometry
  18315. this.setIndex( indices );
  18316. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18317. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  18318. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  18319. // this function calculates the current position on the torus curve
  18320. function calculatePositionOnCurve( u, p, q, radius, position ) {
  18321. const cu = Math.cos( u );
  18322. const su = Math.sin( u );
  18323. const quOverP = q / p * u;
  18324. const cs = Math.cos( quOverP );
  18325. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  18326. position.y = radius * ( 2 + cs ) * su * 0.5;
  18327. position.z = radius * Math.sin( quOverP ) * 0.5;
  18328. }
  18329. }
  18330. }
  18331. class TubeGeometry extends BufferGeometry {
  18332. constructor( path, tubularSegments = 64, radius = 1, radialSegments = 8, closed = false ) {
  18333. super();
  18334. this.type = 'TubeGeometry';
  18335. this.parameters = {
  18336. path: path,
  18337. tubularSegments: tubularSegments,
  18338. radius: radius,
  18339. radialSegments: radialSegments,
  18340. closed: closed
  18341. };
  18342. const frames = path.computeFrenetFrames( tubularSegments, closed );
  18343. // expose internals
  18344. this.tangents = frames.tangents;
  18345. this.normals = frames.normals;
  18346. this.binormals = frames.binormals;
  18347. // helper variables
  18348. const vertex = new Vector3();
  18349. const normal = new Vector3();
  18350. const uv = new Vector2();
  18351. let P = new Vector3();
  18352. // buffer
  18353. const vertices = [];
  18354. const normals = [];
  18355. const uvs = [];
  18356. const indices = [];
  18357. // create buffer data
  18358. generateBufferData();
  18359. // build geometry
  18360. this.setIndex( indices );
  18361. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18362. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  18363. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  18364. // functions
  18365. function generateBufferData() {
  18366. for ( let i = 0; i < tubularSegments; i ++ ) {
  18367. generateSegment( i );
  18368. }
  18369. // if the geometry is not closed, generate the last row of vertices and normals
  18370. // at the regular position on the given path
  18371. //
  18372. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  18373. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  18374. // uvs are generated in a separate function.
  18375. // this makes it easy compute correct values for closed geometries
  18376. generateUVs();
  18377. // finally create faces
  18378. generateIndices();
  18379. }
  18380. function generateSegment( i ) {
  18381. // we use getPointAt to sample evenly distributed points from the given path
  18382. P = path.getPointAt( i / tubularSegments, P );
  18383. // retrieve corresponding normal and binormal
  18384. const N = frames.normals[ i ];
  18385. const B = frames.binormals[ i ];
  18386. // generate normals and vertices for the current segment
  18387. for ( let j = 0; j <= radialSegments; j ++ ) {
  18388. const v = j / radialSegments * Math.PI * 2;
  18389. const sin = Math.sin( v );
  18390. const cos = - Math.cos( v );
  18391. // normal
  18392. normal.x = ( cos * N.x + sin * B.x );
  18393. normal.y = ( cos * N.y + sin * B.y );
  18394. normal.z = ( cos * N.z + sin * B.z );
  18395. normal.normalize();
  18396. normals.push( normal.x, normal.y, normal.z );
  18397. // vertex
  18398. vertex.x = P.x + radius * normal.x;
  18399. vertex.y = P.y + radius * normal.y;
  18400. vertex.z = P.z + radius * normal.z;
  18401. vertices.push( vertex.x, vertex.y, vertex.z );
  18402. }
  18403. }
  18404. function generateIndices() {
  18405. for ( let j = 1; j <= tubularSegments; j ++ ) {
  18406. for ( let i = 1; i <= radialSegments; i ++ ) {
  18407. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  18408. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  18409. const c = ( radialSegments + 1 ) * j + i;
  18410. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  18411. // faces
  18412. indices.push( a, b, d );
  18413. indices.push( b, c, d );
  18414. }
  18415. }
  18416. }
  18417. function generateUVs() {
  18418. for ( let i = 0; i <= tubularSegments; i ++ ) {
  18419. for ( let j = 0; j <= radialSegments; j ++ ) {
  18420. uv.x = i / tubularSegments;
  18421. uv.y = j / radialSegments;
  18422. uvs.push( uv.x, uv.y );
  18423. }
  18424. }
  18425. }
  18426. }
  18427. toJSON() {
  18428. const data = BufferGeometry.prototype.toJSON.call( this );
  18429. data.path = this.parameters.path.toJSON();
  18430. return data;
  18431. }
  18432. }
  18433. class WireframeGeometry extends BufferGeometry {
  18434. constructor( geometry ) {
  18435. super();
  18436. this.type = 'WireframeGeometry';
  18437. if ( geometry.isGeometry === true ) {
  18438. console.error( 'THREE.WireframeGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  18439. return;
  18440. }
  18441. // buffer
  18442. const vertices = [];
  18443. // helper variables
  18444. const edge = [ 0, 0 ], edges = {};
  18445. const vertex = new Vector3();
  18446. if ( geometry.index !== null ) {
  18447. // indexed BufferGeometry
  18448. const position = geometry.attributes.position;
  18449. const indices = geometry.index;
  18450. let groups = geometry.groups;
  18451. if ( groups.length === 0 ) {
  18452. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  18453. }
  18454. // create a data structure that contains all eges without duplicates
  18455. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  18456. const group = groups[ o ];
  18457. const start = group.start;
  18458. const count = group.count;
  18459. for ( let i = start, l = ( start + count ); i < l; i += 3 ) {
  18460. for ( let j = 0; j < 3; j ++ ) {
  18461. const edge1 = indices.getX( i + j );
  18462. const edge2 = indices.getX( i + ( j + 1 ) % 3 );
  18463. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  18464. edge[ 1 ] = Math.max( edge1, edge2 );
  18465. const key = edge[ 0 ] + ',' + edge[ 1 ];
  18466. if ( edges[ key ] === undefined ) {
  18467. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  18468. }
  18469. }
  18470. }
  18471. }
  18472. // generate vertices
  18473. for ( const key in edges ) {
  18474. const e = edges[ key ];
  18475. vertex.fromBufferAttribute( position, e.index1 );
  18476. vertices.push( vertex.x, vertex.y, vertex.z );
  18477. vertex.fromBufferAttribute( position, e.index2 );
  18478. vertices.push( vertex.x, vertex.y, vertex.z );
  18479. }
  18480. } else {
  18481. // non-indexed BufferGeometry
  18482. const position = geometry.attributes.position;
  18483. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  18484. for ( let j = 0; j < 3; j ++ ) {
  18485. // three edges per triangle, an edge is represented as (index1, index2)
  18486. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  18487. const index1 = 3 * i + j;
  18488. vertex.fromBufferAttribute( position, index1 );
  18489. vertices.push( vertex.x, vertex.y, vertex.z );
  18490. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  18491. vertex.fromBufferAttribute( position, index2 );
  18492. vertices.push( vertex.x, vertex.y, vertex.z );
  18493. }
  18494. }
  18495. }
  18496. // build geometry
  18497. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18498. }
  18499. }
  18500. var Geometries = /*#__PURE__*/Object.freeze({
  18501. __proto__: null,
  18502. BoxGeometry: BoxGeometry,
  18503. BoxBufferGeometry: BoxGeometry,
  18504. CircleGeometry: CircleGeometry,
  18505. CircleBufferGeometry: CircleGeometry,
  18506. ConeGeometry: ConeGeometry,
  18507. ConeBufferGeometry: ConeGeometry,
  18508. CylinderGeometry: CylinderGeometry,
  18509. CylinderBufferGeometry: CylinderGeometry,
  18510. DodecahedronGeometry: DodecahedronGeometry,
  18511. DodecahedronBufferGeometry: DodecahedronGeometry,
  18512. EdgesGeometry: EdgesGeometry,
  18513. ExtrudeGeometry: ExtrudeGeometry,
  18514. ExtrudeBufferGeometry: ExtrudeGeometry,
  18515. IcosahedronGeometry: IcosahedronGeometry,
  18516. IcosahedronBufferGeometry: IcosahedronGeometry,
  18517. LatheGeometry: LatheGeometry,
  18518. LatheBufferGeometry: LatheGeometry,
  18519. OctahedronGeometry: OctahedronGeometry,
  18520. OctahedronBufferGeometry: OctahedronGeometry,
  18521. ParametricGeometry: ParametricGeometry,
  18522. ParametricBufferGeometry: ParametricGeometry,
  18523. PlaneGeometry: PlaneGeometry,
  18524. PlaneBufferGeometry: PlaneGeometry,
  18525. PolyhedronGeometry: PolyhedronGeometry,
  18526. PolyhedronBufferGeometry: PolyhedronGeometry,
  18527. RingGeometry: RingGeometry,
  18528. RingBufferGeometry: RingGeometry,
  18529. ShapeGeometry: ShapeGeometry,
  18530. ShapeBufferGeometry: ShapeGeometry,
  18531. SphereGeometry: SphereGeometry,
  18532. SphereBufferGeometry: SphereGeometry,
  18533. TetrahedronGeometry: TetrahedronGeometry,
  18534. TetrahedronBufferGeometry: TetrahedronGeometry,
  18535. TextGeometry: TextGeometry,
  18536. TextBufferGeometry: TextGeometry,
  18537. TorusGeometry: TorusGeometry,
  18538. TorusBufferGeometry: TorusGeometry,
  18539. TorusKnotGeometry: TorusKnotGeometry,
  18540. TorusKnotBufferGeometry: TorusKnotGeometry,
  18541. TubeGeometry: TubeGeometry,
  18542. TubeBufferGeometry: TubeGeometry,
  18543. WireframeGeometry: WireframeGeometry
  18544. });
  18545. /**
  18546. * parameters = {
  18547. * color: <THREE.Color>
  18548. * }
  18549. */
  18550. class ShadowMaterial extends Material {
  18551. constructor( parameters ) {
  18552. super();
  18553. this.type = 'ShadowMaterial';
  18554. this.color = new Color( 0x000000 );
  18555. this.transparent = true;
  18556. this.setValues( parameters );
  18557. }
  18558. copy( source ) {
  18559. super.copy( source );
  18560. this.color.copy( source.color );
  18561. return this;
  18562. }
  18563. }
  18564. ShadowMaterial.prototype.isShadowMaterial = true;
  18565. class RawShaderMaterial extends ShaderMaterial {
  18566. constructor( parameters ) {
  18567. super( parameters );
  18568. this.type = 'RawShaderMaterial';
  18569. }
  18570. }
  18571. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  18572. /**
  18573. * parameters = {
  18574. * color: <hex>,
  18575. * roughness: <float>,
  18576. * metalness: <float>,
  18577. * opacity: <float>,
  18578. *
  18579. * map: new THREE.Texture( <Image> ),
  18580. *
  18581. * lightMap: new THREE.Texture( <Image> ),
  18582. * lightMapIntensity: <float>
  18583. *
  18584. * aoMap: new THREE.Texture( <Image> ),
  18585. * aoMapIntensity: <float>
  18586. *
  18587. * emissive: <hex>,
  18588. * emissiveIntensity: <float>
  18589. * emissiveMap: new THREE.Texture( <Image> ),
  18590. *
  18591. * bumpMap: new THREE.Texture( <Image> ),
  18592. * bumpScale: <float>,
  18593. *
  18594. * normalMap: new THREE.Texture( <Image> ),
  18595. * normalMapType: THREE.TangentSpaceNormalMap,
  18596. * normalScale: <Vector2>,
  18597. *
  18598. * displacementMap: new THREE.Texture( <Image> ),
  18599. * displacementScale: <float>,
  18600. * displacementBias: <float>,
  18601. *
  18602. * roughnessMap: new THREE.Texture( <Image> ),
  18603. *
  18604. * metalnessMap: new THREE.Texture( <Image> ),
  18605. *
  18606. * alphaMap: new THREE.Texture( <Image> ),
  18607. *
  18608. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  18609. * envMapIntensity: <float>
  18610. *
  18611. * refractionRatio: <float>,
  18612. *
  18613. * wireframe: <boolean>,
  18614. * wireframeLinewidth: <float>,
  18615. *
  18616. * skinning: <bool>,
  18617. * morphTargets: <bool>,
  18618. * morphNormals: <bool>,
  18619. *
  18620. * flatShading: <bool>
  18621. * }
  18622. */
  18623. function MeshStandardMaterial( parameters ) {
  18624. Material.call( this );
  18625. this.defines = { 'STANDARD': '' };
  18626. this.type = 'MeshStandardMaterial';
  18627. this.color = new Color( 0xffffff ); // diffuse
  18628. this.roughness = 1.0;
  18629. this.metalness = 0.0;
  18630. this.map = null;
  18631. this.lightMap = null;
  18632. this.lightMapIntensity = 1.0;
  18633. this.aoMap = null;
  18634. this.aoMapIntensity = 1.0;
  18635. this.emissive = new Color( 0x000000 );
  18636. this.emissiveIntensity = 1.0;
  18637. this.emissiveMap = null;
  18638. this.bumpMap = null;
  18639. this.bumpScale = 1;
  18640. this.normalMap = null;
  18641. this.normalMapType = TangentSpaceNormalMap;
  18642. this.normalScale = new Vector2( 1, 1 );
  18643. this.displacementMap = null;
  18644. this.displacementScale = 1;
  18645. this.displacementBias = 0;
  18646. this.roughnessMap = null;
  18647. this.metalnessMap = null;
  18648. this.alphaMap = null;
  18649. this.envMap = null;
  18650. this.envMapIntensity = 1.0;
  18651. this.refractionRatio = 0.98;
  18652. this.wireframe = false;
  18653. this.wireframeLinewidth = 1;
  18654. this.wireframeLinecap = 'round';
  18655. this.wireframeLinejoin = 'round';
  18656. this.skinning = false;
  18657. this.morphTargets = false;
  18658. this.morphNormals = false;
  18659. this.flatShading = false;
  18660. this.vertexTangents = false;
  18661. this.setValues( parameters );
  18662. }
  18663. MeshStandardMaterial.prototype = Object.create( Material.prototype );
  18664. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  18665. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  18666. MeshStandardMaterial.prototype.copy = function ( source ) {
  18667. Material.prototype.copy.call( this, source );
  18668. this.defines = { 'STANDARD': '' };
  18669. this.color.copy( source.color );
  18670. this.roughness = source.roughness;
  18671. this.metalness = source.metalness;
  18672. this.map = source.map;
  18673. this.lightMap = source.lightMap;
  18674. this.lightMapIntensity = source.lightMapIntensity;
  18675. this.aoMap = source.aoMap;
  18676. this.aoMapIntensity = source.aoMapIntensity;
  18677. this.emissive.copy( source.emissive );
  18678. this.emissiveMap = source.emissiveMap;
  18679. this.emissiveIntensity = source.emissiveIntensity;
  18680. this.bumpMap = source.bumpMap;
  18681. this.bumpScale = source.bumpScale;
  18682. this.normalMap = source.normalMap;
  18683. this.normalMapType = source.normalMapType;
  18684. this.normalScale.copy( source.normalScale );
  18685. this.displacementMap = source.displacementMap;
  18686. this.displacementScale = source.displacementScale;
  18687. this.displacementBias = source.displacementBias;
  18688. this.roughnessMap = source.roughnessMap;
  18689. this.metalnessMap = source.metalnessMap;
  18690. this.alphaMap = source.alphaMap;
  18691. this.envMap = source.envMap;
  18692. this.envMapIntensity = source.envMapIntensity;
  18693. this.refractionRatio = source.refractionRatio;
  18694. this.wireframe = source.wireframe;
  18695. this.wireframeLinewidth = source.wireframeLinewidth;
  18696. this.wireframeLinecap = source.wireframeLinecap;
  18697. this.wireframeLinejoin = source.wireframeLinejoin;
  18698. this.skinning = source.skinning;
  18699. this.morphTargets = source.morphTargets;
  18700. this.morphNormals = source.morphNormals;
  18701. this.flatShading = source.flatShading;
  18702. this.vertexTangents = source.vertexTangents;
  18703. return this;
  18704. };
  18705. /**
  18706. * parameters = {
  18707. * clearcoat: <float>,
  18708. * clearcoatMap: new THREE.Texture( <Image> ),
  18709. * clearcoatRoughness: <float>,
  18710. * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
  18711. * clearcoatNormalScale: <Vector2>,
  18712. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  18713. *
  18714. * reflectivity: <float>,
  18715. * ior: <float>,
  18716. *
  18717. * sheen: <Color>,
  18718. *
  18719. * transmission: <float>,
  18720. * transmissionMap: new THREE.Texture( <Image> )
  18721. * }
  18722. */
  18723. function MeshPhysicalMaterial( parameters ) {
  18724. MeshStandardMaterial.call( this );
  18725. this.defines = {
  18726. 'STANDARD': '',
  18727. 'PHYSICAL': ''
  18728. };
  18729. this.type = 'MeshPhysicalMaterial';
  18730. this.clearcoat = 0.0;
  18731. this.clearcoatMap = null;
  18732. this.clearcoatRoughness = 0.0;
  18733. this.clearcoatRoughnessMap = null;
  18734. this.clearcoatNormalScale = new Vector2( 1, 1 );
  18735. this.clearcoatNormalMap = null;
  18736. this.reflectivity = 0.5; // maps to F0 = 0.04
  18737. Object.defineProperty( this, 'ior', {
  18738. get: function () {
  18739. return ( 1 + 0.4 * this.reflectivity ) / ( 1 - 0.4 * this.reflectivity );
  18740. },
  18741. set: function ( ior ) {
  18742. this.reflectivity = MathUtils.clamp( 2.5 * ( ior - 1 ) / ( ior + 1 ), 0, 1 );
  18743. }
  18744. } );
  18745. this.sheen = null; // null will disable sheen bsdf
  18746. this.transmission = 0.0;
  18747. this.transmissionMap = null;
  18748. this.setValues( parameters );
  18749. }
  18750. MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
  18751. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  18752. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  18753. MeshPhysicalMaterial.prototype.copy = function ( source ) {
  18754. MeshStandardMaterial.prototype.copy.call( this, source );
  18755. this.defines = {
  18756. 'STANDARD': '',
  18757. 'PHYSICAL': ''
  18758. };
  18759. this.clearcoat = source.clearcoat;
  18760. this.clearcoatMap = source.clearcoatMap;
  18761. this.clearcoatRoughness = source.clearcoatRoughness;
  18762. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  18763. this.clearcoatNormalMap = source.clearcoatNormalMap;
  18764. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  18765. this.reflectivity = source.reflectivity;
  18766. if ( source.sheen ) {
  18767. this.sheen = ( this.sheen || new Color() ).copy( source.sheen );
  18768. } else {
  18769. this.sheen = null;
  18770. }
  18771. this.transmission = source.transmission;
  18772. this.transmissionMap = source.transmissionMap;
  18773. return this;
  18774. };
  18775. /**
  18776. * parameters = {
  18777. * color: <hex>,
  18778. * specular: <hex>,
  18779. * shininess: <float>,
  18780. * opacity: <float>,
  18781. *
  18782. * map: new THREE.Texture( <Image> ),
  18783. *
  18784. * lightMap: new THREE.Texture( <Image> ),
  18785. * lightMapIntensity: <float>
  18786. *
  18787. * aoMap: new THREE.Texture( <Image> ),
  18788. * aoMapIntensity: <float>
  18789. *
  18790. * emissive: <hex>,
  18791. * emissiveIntensity: <float>
  18792. * emissiveMap: new THREE.Texture( <Image> ),
  18793. *
  18794. * bumpMap: new THREE.Texture( <Image> ),
  18795. * bumpScale: <float>,
  18796. *
  18797. * normalMap: new THREE.Texture( <Image> ),
  18798. * normalMapType: THREE.TangentSpaceNormalMap,
  18799. * normalScale: <Vector2>,
  18800. *
  18801. * displacementMap: new THREE.Texture( <Image> ),
  18802. * displacementScale: <float>,
  18803. * displacementBias: <float>,
  18804. *
  18805. * specularMap: new THREE.Texture( <Image> ),
  18806. *
  18807. * alphaMap: new THREE.Texture( <Image> ),
  18808. *
  18809. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  18810. * combine: THREE.MultiplyOperation,
  18811. * reflectivity: <float>,
  18812. * refractionRatio: <float>,
  18813. *
  18814. * wireframe: <boolean>,
  18815. * wireframeLinewidth: <float>,
  18816. *
  18817. * skinning: <bool>,
  18818. * morphTargets: <bool>,
  18819. * morphNormals: <bool>,
  18820. *
  18821. * flatShading: <bool>
  18822. * }
  18823. */
  18824. class MeshPhongMaterial extends Material {
  18825. constructor( parameters ) {
  18826. super();
  18827. this.type = 'MeshPhongMaterial';
  18828. this.color = new Color( 0xffffff ); // diffuse
  18829. this.specular = new Color( 0x111111 );
  18830. this.shininess = 30;
  18831. this.map = null;
  18832. this.lightMap = null;
  18833. this.lightMapIntensity = 1.0;
  18834. this.aoMap = null;
  18835. this.aoMapIntensity = 1.0;
  18836. this.emissive = new Color( 0x000000 );
  18837. this.emissiveIntensity = 1.0;
  18838. this.emissiveMap = null;
  18839. this.bumpMap = null;
  18840. this.bumpScale = 1;
  18841. this.normalMap = null;
  18842. this.normalMapType = TangentSpaceNormalMap;
  18843. this.normalScale = new Vector2( 1, 1 );
  18844. this.displacementMap = null;
  18845. this.displacementScale = 1;
  18846. this.displacementBias = 0;
  18847. this.specularMap = null;
  18848. this.alphaMap = null;
  18849. this.envMap = null;
  18850. this.combine = MultiplyOperation;
  18851. this.reflectivity = 1;
  18852. this.refractionRatio = 0.98;
  18853. this.wireframe = false;
  18854. this.wireframeLinewidth = 1;
  18855. this.wireframeLinecap = 'round';
  18856. this.wireframeLinejoin = 'round';
  18857. this.skinning = false;
  18858. this.morphTargets = false;
  18859. this.morphNormals = false;
  18860. this.flatShading = false;
  18861. this.setValues( parameters );
  18862. }
  18863. copy( source ) {
  18864. super.copy( source );
  18865. this.color.copy( source.color );
  18866. this.specular.copy( source.specular );
  18867. this.shininess = source.shininess;
  18868. this.map = source.map;
  18869. this.lightMap = source.lightMap;
  18870. this.lightMapIntensity = source.lightMapIntensity;
  18871. this.aoMap = source.aoMap;
  18872. this.aoMapIntensity = source.aoMapIntensity;
  18873. this.emissive.copy( source.emissive );
  18874. this.emissiveMap = source.emissiveMap;
  18875. this.emissiveIntensity = source.emissiveIntensity;
  18876. this.bumpMap = source.bumpMap;
  18877. this.bumpScale = source.bumpScale;
  18878. this.normalMap = source.normalMap;
  18879. this.normalMapType = source.normalMapType;
  18880. this.normalScale.copy( source.normalScale );
  18881. this.displacementMap = source.displacementMap;
  18882. this.displacementScale = source.displacementScale;
  18883. this.displacementBias = source.displacementBias;
  18884. this.specularMap = source.specularMap;
  18885. this.alphaMap = source.alphaMap;
  18886. this.envMap = source.envMap;
  18887. this.combine = source.combine;
  18888. this.reflectivity = source.reflectivity;
  18889. this.refractionRatio = source.refractionRatio;
  18890. this.wireframe = source.wireframe;
  18891. this.wireframeLinewidth = source.wireframeLinewidth;
  18892. this.wireframeLinecap = source.wireframeLinecap;
  18893. this.wireframeLinejoin = source.wireframeLinejoin;
  18894. this.skinning = source.skinning;
  18895. this.morphTargets = source.morphTargets;
  18896. this.morphNormals = source.morphNormals;
  18897. this.flatShading = source.flatShading;
  18898. return this;
  18899. }
  18900. }
  18901. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  18902. /**
  18903. * parameters = {
  18904. * color: <hex>,
  18905. *
  18906. * map: new THREE.Texture( <Image> ),
  18907. * gradientMap: new THREE.Texture( <Image> ),
  18908. *
  18909. * lightMap: new THREE.Texture( <Image> ),
  18910. * lightMapIntensity: <float>
  18911. *
  18912. * aoMap: new THREE.Texture( <Image> ),
  18913. * aoMapIntensity: <float>
  18914. *
  18915. * emissive: <hex>,
  18916. * emissiveIntensity: <float>
  18917. * emissiveMap: new THREE.Texture( <Image> ),
  18918. *
  18919. * bumpMap: new THREE.Texture( <Image> ),
  18920. * bumpScale: <float>,
  18921. *
  18922. * normalMap: new THREE.Texture( <Image> ),
  18923. * normalMapType: THREE.TangentSpaceNormalMap,
  18924. * normalScale: <Vector2>,
  18925. *
  18926. * displacementMap: new THREE.Texture( <Image> ),
  18927. * displacementScale: <float>,
  18928. * displacementBias: <float>,
  18929. *
  18930. * alphaMap: new THREE.Texture( <Image> ),
  18931. *
  18932. * wireframe: <boolean>,
  18933. * wireframeLinewidth: <float>,
  18934. *
  18935. * skinning: <bool>,
  18936. * morphTargets: <bool>,
  18937. * morphNormals: <bool>
  18938. * }
  18939. */
  18940. class MeshToonMaterial extends Material {
  18941. constructor( parameters ) {
  18942. super();
  18943. this.defines = { 'TOON': '' };
  18944. this.type = 'MeshToonMaterial';
  18945. this.color = new Color( 0xffffff );
  18946. this.map = null;
  18947. this.gradientMap = null;
  18948. this.lightMap = null;
  18949. this.lightMapIntensity = 1.0;
  18950. this.aoMap = null;
  18951. this.aoMapIntensity = 1.0;
  18952. this.emissive = new Color( 0x000000 );
  18953. this.emissiveIntensity = 1.0;
  18954. this.emissiveMap = null;
  18955. this.bumpMap = null;
  18956. this.bumpScale = 1;
  18957. this.normalMap = null;
  18958. this.normalMapType = TangentSpaceNormalMap;
  18959. this.normalScale = new Vector2( 1, 1 );
  18960. this.displacementMap = null;
  18961. this.displacementScale = 1;
  18962. this.displacementBias = 0;
  18963. this.alphaMap = null;
  18964. this.wireframe = false;
  18965. this.wireframeLinewidth = 1;
  18966. this.wireframeLinecap = 'round';
  18967. this.wireframeLinejoin = 'round';
  18968. this.skinning = false;
  18969. this.morphTargets = false;
  18970. this.morphNormals = false;
  18971. this.setValues( parameters );
  18972. }
  18973. copy( source ) {
  18974. super.copy( source );
  18975. this.color.copy( source.color );
  18976. this.map = source.map;
  18977. this.gradientMap = source.gradientMap;
  18978. this.lightMap = source.lightMap;
  18979. this.lightMapIntensity = source.lightMapIntensity;
  18980. this.aoMap = source.aoMap;
  18981. this.aoMapIntensity = source.aoMapIntensity;
  18982. this.emissive.copy( source.emissive );
  18983. this.emissiveMap = source.emissiveMap;
  18984. this.emissiveIntensity = source.emissiveIntensity;
  18985. this.bumpMap = source.bumpMap;
  18986. this.bumpScale = source.bumpScale;
  18987. this.normalMap = source.normalMap;
  18988. this.normalMapType = source.normalMapType;
  18989. this.normalScale.copy( source.normalScale );
  18990. this.displacementMap = source.displacementMap;
  18991. this.displacementScale = source.displacementScale;
  18992. this.displacementBias = source.displacementBias;
  18993. this.alphaMap = source.alphaMap;
  18994. this.wireframe = source.wireframe;
  18995. this.wireframeLinewidth = source.wireframeLinewidth;
  18996. this.wireframeLinecap = source.wireframeLinecap;
  18997. this.wireframeLinejoin = source.wireframeLinejoin;
  18998. this.skinning = source.skinning;
  18999. this.morphTargets = source.morphTargets;
  19000. this.morphNormals = source.morphNormals;
  19001. return this;
  19002. }
  19003. }
  19004. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  19005. /**
  19006. * parameters = {
  19007. * opacity: <float>,
  19008. *
  19009. * bumpMap: new THREE.Texture( <Image> ),
  19010. * bumpScale: <float>,
  19011. *
  19012. * normalMap: new THREE.Texture( <Image> ),
  19013. * normalMapType: THREE.TangentSpaceNormalMap,
  19014. * normalScale: <Vector2>,
  19015. *
  19016. * displacementMap: new THREE.Texture( <Image> ),
  19017. * displacementScale: <float>,
  19018. * displacementBias: <float>,
  19019. *
  19020. * wireframe: <boolean>,
  19021. * wireframeLinewidth: <float>
  19022. *
  19023. * skinning: <bool>,
  19024. * morphTargets: <bool>,
  19025. * morphNormals: <bool>,
  19026. *
  19027. * flatShading: <bool>
  19028. * }
  19029. */
  19030. class MeshNormalMaterial extends Material {
  19031. constructor( parameters ) {
  19032. super();
  19033. this.type = 'MeshNormalMaterial';
  19034. this.bumpMap = null;
  19035. this.bumpScale = 1;
  19036. this.normalMap = null;
  19037. this.normalMapType = TangentSpaceNormalMap;
  19038. this.normalScale = new Vector2( 1, 1 );
  19039. this.displacementMap = null;
  19040. this.displacementScale = 1;
  19041. this.displacementBias = 0;
  19042. this.wireframe = false;
  19043. this.wireframeLinewidth = 1;
  19044. this.fog = false;
  19045. this.skinning = false;
  19046. this.morphTargets = false;
  19047. this.morphNormals = false;
  19048. this.flatShading = false;
  19049. this.setValues( parameters );
  19050. }
  19051. copy( source ) {
  19052. super.copy( source );
  19053. this.bumpMap = source.bumpMap;
  19054. this.bumpScale = source.bumpScale;
  19055. this.normalMap = source.normalMap;
  19056. this.normalMapType = source.normalMapType;
  19057. this.normalScale.copy( source.normalScale );
  19058. this.displacementMap = source.displacementMap;
  19059. this.displacementScale = source.displacementScale;
  19060. this.displacementBias = source.displacementBias;
  19061. this.wireframe = source.wireframe;
  19062. this.wireframeLinewidth = source.wireframeLinewidth;
  19063. this.skinning = source.skinning;
  19064. this.morphTargets = source.morphTargets;
  19065. this.morphNormals = source.morphNormals;
  19066. this.flatShading = source.flatShading;
  19067. return this;
  19068. }
  19069. }
  19070. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  19071. /**
  19072. * parameters = {
  19073. * color: <hex>,
  19074. * opacity: <float>,
  19075. *
  19076. * map: new THREE.Texture( <Image> ),
  19077. *
  19078. * lightMap: new THREE.Texture( <Image> ),
  19079. * lightMapIntensity: <float>
  19080. *
  19081. * aoMap: new THREE.Texture( <Image> ),
  19082. * aoMapIntensity: <float>
  19083. *
  19084. * emissive: <hex>,
  19085. * emissiveIntensity: <float>
  19086. * emissiveMap: new THREE.Texture( <Image> ),
  19087. *
  19088. * specularMap: new THREE.Texture( <Image> ),
  19089. *
  19090. * alphaMap: new THREE.Texture( <Image> ),
  19091. *
  19092. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  19093. * combine: THREE.Multiply,
  19094. * reflectivity: <float>,
  19095. * refractionRatio: <float>,
  19096. *
  19097. * wireframe: <boolean>,
  19098. * wireframeLinewidth: <float>,
  19099. *
  19100. * skinning: <bool>,
  19101. * morphTargets: <bool>,
  19102. * morphNormals: <bool>
  19103. * }
  19104. */
  19105. class MeshLambertMaterial extends Material {
  19106. constructor( parameters ) {
  19107. super();
  19108. this.type = 'MeshLambertMaterial';
  19109. this.color = new Color( 0xffffff ); // diffuse
  19110. this.map = null;
  19111. this.lightMap = null;
  19112. this.lightMapIntensity = 1.0;
  19113. this.aoMap = null;
  19114. this.aoMapIntensity = 1.0;
  19115. this.emissive = new Color( 0x000000 );
  19116. this.emissiveIntensity = 1.0;
  19117. this.emissiveMap = null;
  19118. this.specularMap = null;
  19119. this.alphaMap = null;
  19120. this.envMap = null;
  19121. this.combine = MultiplyOperation;
  19122. this.reflectivity = 1;
  19123. this.refractionRatio = 0.98;
  19124. this.wireframe = false;
  19125. this.wireframeLinewidth = 1;
  19126. this.wireframeLinecap = 'round';
  19127. this.wireframeLinejoin = 'round';
  19128. this.skinning = false;
  19129. this.morphTargets = false;
  19130. this.morphNormals = false;
  19131. this.setValues( parameters );
  19132. }
  19133. copy( source ) {
  19134. super.copy( source );
  19135. this.color.copy( source.color );
  19136. this.map = source.map;
  19137. this.lightMap = source.lightMap;
  19138. this.lightMapIntensity = source.lightMapIntensity;
  19139. this.aoMap = source.aoMap;
  19140. this.aoMapIntensity = source.aoMapIntensity;
  19141. this.emissive.copy( source.emissive );
  19142. this.emissiveMap = source.emissiveMap;
  19143. this.emissiveIntensity = source.emissiveIntensity;
  19144. this.specularMap = source.specularMap;
  19145. this.alphaMap = source.alphaMap;
  19146. this.envMap = source.envMap;
  19147. this.combine = source.combine;
  19148. this.reflectivity = source.reflectivity;
  19149. this.refractionRatio = source.refractionRatio;
  19150. this.wireframe = source.wireframe;
  19151. this.wireframeLinewidth = source.wireframeLinewidth;
  19152. this.wireframeLinecap = source.wireframeLinecap;
  19153. this.wireframeLinejoin = source.wireframeLinejoin;
  19154. this.skinning = source.skinning;
  19155. this.morphTargets = source.morphTargets;
  19156. this.morphNormals = source.morphNormals;
  19157. return this;
  19158. }
  19159. }
  19160. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  19161. /**
  19162. * parameters = {
  19163. * color: <hex>,
  19164. * opacity: <float>,
  19165. *
  19166. * matcap: new THREE.Texture( <Image> ),
  19167. *
  19168. * map: new THREE.Texture( <Image> ),
  19169. *
  19170. * bumpMap: new THREE.Texture( <Image> ),
  19171. * bumpScale: <float>,
  19172. *
  19173. * normalMap: new THREE.Texture( <Image> ),
  19174. * normalMapType: THREE.TangentSpaceNormalMap,
  19175. * normalScale: <Vector2>,
  19176. *
  19177. * displacementMap: new THREE.Texture( <Image> ),
  19178. * displacementScale: <float>,
  19179. * displacementBias: <float>,
  19180. *
  19181. * alphaMap: new THREE.Texture( <Image> ),
  19182. *
  19183. * skinning: <bool>,
  19184. * morphTargets: <bool>,
  19185. * morphNormals: <bool>
  19186. *
  19187. * flatShading: <bool>
  19188. * }
  19189. */
  19190. class MeshMatcapMaterial extends Material {
  19191. constructor( parameters ) {
  19192. super();
  19193. this.defines = { 'MATCAP': '' };
  19194. this.type = 'MeshMatcapMaterial';
  19195. this.color = new Color( 0xffffff ); // diffuse
  19196. this.matcap = null;
  19197. this.map = null;
  19198. this.bumpMap = null;
  19199. this.bumpScale = 1;
  19200. this.normalMap = null;
  19201. this.normalMapType = TangentSpaceNormalMap;
  19202. this.normalScale = new Vector2( 1, 1 );
  19203. this.displacementMap = null;
  19204. this.displacementScale = 1;
  19205. this.displacementBias = 0;
  19206. this.alphaMap = null;
  19207. this.skinning = false;
  19208. this.morphTargets = false;
  19209. this.morphNormals = false;
  19210. this.flatShading = false;
  19211. this.setValues( parameters );
  19212. }
  19213. copy( source ) {
  19214. super.copy( source );
  19215. this.defines = { 'MATCAP': '' };
  19216. this.color.copy( source.color );
  19217. this.matcap = source.matcap;
  19218. this.map = source.map;
  19219. this.bumpMap = source.bumpMap;
  19220. this.bumpScale = source.bumpScale;
  19221. this.normalMap = source.normalMap;
  19222. this.normalMapType = source.normalMapType;
  19223. this.normalScale.copy( source.normalScale );
  19224. this.displacementMap = source.displacementMap;
  19225. this.displacementScale = source.displacementScale;
  19226. this.displacementBias = source.displacementBias;
  19227. this.alphaMap = source.alphaMap;
  19228. this.skinning = source.skinning;
  19229. this.morphTargets = source.morphTargets;
  19230. this.morphNormals = source.morphNormals;
  19231. this.flatShading = source.flatShading;
  19232. return this;
  19233. }
  19234. }
  19235. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  19236. /**
  19237. * parameters = {
  19238. * color: <hex>,
  19239. * opacity: <float>,
  19240. *
  19241. * linewidth: <float>,
  19242. *
  19243. * scale: <float>,
  19244. * dashSize: <float>,
  19245. * gapSize: <float>
  19246. * }
  19247. */
  19248. class LineDashedMaterial extends LineBasicMaterial {
  19249. constructor( parameters ) {
  19250. super();
  19251. this.type = 'LineDashedMaterial';
  19252. this.scale = 1;
  19253. this.dashSize = 3;
  19254. this.gapSize = 1;
  19255. this.setValues( parameters );
  19256. }
  19257. copy( source ) {
  19258. super.copy( source );
  19259. this.scale = source.scale;
  19260. this.dashSize = source.dashSize;
  19261. this.gapSize = source.gapSize;
  19262. return this;
  19263. }
  19264. }
  19265. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  19266. var Materials = /*#__PURE__*/Object.freeze({
  19267. __proto__: null,
  19268. ShadowMaterial: ShadowMaterial,
  19269. SpriteMaterial: SpriteMaterial,
  19270. RawShaderMaterial: RawShaderMaterial,
  19271. ShaderMaterial: ShaderMaterial,
  19272. PointsMaterial: PointsMaterial,
  19273. MeshPhysicalMaterial: MeshPhysicalMaterial,
  19274. MeshStandardMaterial: MeshStandardMaterial,
  19275. MeshPhongMaterial: MeshPhongMaterial,
  19276. MeshToonMaterial: MeshToonMaterial,
  19277. MeshNormalMaterial: MeshNormalMaterial,
  19278. MeshLambertMaterial: MeshLambertMaterial,
  19279. MeshDepthMaterial: MeshDepthMaterial,
  19280. MeshDistanceMaterial: MeshDistanceMaterial,
  19281. MeshBasicMaterial: MeshBasicMaterial,
  19282. MeshMatcapMaterial: MeshMatcapMaterial,
  19283. LineDashedMaterial: LineDashedMaterial,
  19284. LineBasicMaterial: LineBasicMaterial,
  19285. Material: Material
  19286. });
  19287. const AnimationUtils = {
  19288. // same as Array.prototype.slice, but also works on typed arrays
  19289. arraySlice: function ( array, from, to ) {
  19290. if ( AnimationUtils.isTypedArray( array ) ) {
  19291. // in ios9 array.subarray(from, undefined) will return empty array
  19292. // but array.subarray(from) or array.subarray(from, len) is correct
  19293. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  19294. }
  19295. return array.slice( from, to );
  19296. },
  19297. // converts an array to a specific type
  19298. convertArray: function ( array, type, forceClone ) {
  19299. if ( ! array || // let 'undefined' and 'null' pass
  19300. ! forceClone && array.constructor === type ) return array;
  19301. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  19302. return new type( array ); // create typed array
  19303. }
  19304. return Array.prototype.slice.call( array ); // create Array
  19305. },
  19306. isTypedArray: function ( object ) {
  19307. return ArrayBuffer.isView( object ) &&
  19308. ! ( object instanceof DataView );
  19309. },
  19310. // returns an array by which times and values can be sorted
  19311. getKeyframeOrder: function ( times ) {
  19312. function compareTime( i, j ) {
  19313. return times[ i ] - times[ j ];
  19314. }
  19315. const n = times.length;
  19316. const result = new Array( n );
  19317. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  19318. result.sort( compareTime );
  19319. return result;
  19320. },
  19321. // uses the array previously returned by 'getKeyframeOrder' to sort data
  19322. sortedArray: function ( values, stride, order ) {
  19323. const nValues = values.length;
  19324. const result = new values.constructor( nValues );
  19325. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  19326. const srcOffset = order[ i ] * stride;
  19327. for ( let j = 0; j !== stride; ++ j ) {
  19328. result[ dstOffset ++ ] = values[ srcOffset + j ];
  19329. }
  19330. }
  19331. return result;
  19332. },
  19333. // function for parsing AOS keyframe formats
  19334. flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) {
  19335. let i = 1, key = jsonKeys[ 0 ];
  19336. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  19337. key = jsonKeys[ i ++ ];
  19338. }
  19339. if ( key === undefined ) return; // no data
  19340. let value = key[ valuePropertyName ];
  19341. if ( value === undefined ) return; // no data
  19342. if ( Array.isArray( value ) ) {
  19343. do {
  19344. value = key[ valuePropertyName ];
  19345. if ( value !== undefined ) {
  19346. times.push( key.time );
  19347. values.push.apply( values, value ); // push all elements
  19348. }
  19349. key = jsonKeys[ i ++ ];
  19350. } while ( key !== undefined );
  19351. } else if ( value.toArray !== undefined ) {
  19352. // ...assume THREE.Math-ish
  19353. do {
  19354. value = key[ valuePropertyName ];
  19355. if ( value !== undefined ) {
  19356. times.push( key.time );
  19357. value.toArray( values, values.length );
  19358. }
  19359. key = jsonKeys[ i ++ ];
  19360. } while ( key !== undefined );
  19361. } else {
  19362. // otherwise push as-is
  19363. do {
  19364. value = key[ valuePropertyName ];
  19365. if ( value !== undefined ) {
  19366. times.push( key.time );
  19367. values.push( value );
  19368. }
  19369. key = jsonKeys[ i ++ ];
  19370. } while ( key !== undefined );
  19371. }
  19372. },
  19373. subclip: function ( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  19374. const clip = sourceClip.clone();
  19375. clip.name = name;
  19376. const tracks = [];
  19377. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  19378. const track = clip.tracks[ i ];
  19379. const valueSize = track.getValueSize();
  19380. const times = [];
  19381. const values = [];
  19382. for ( let j = 0; j < track.times.length; ++ j ) {
  19383. const frame = track.times[ j ] * fps;
  19384. if ( frame < startFrame || frame >= endFrame ) continue;
  19385. times.push( track.times[ j ] );
  19386. for ( let k = 0; k < valueSize; ++ k ) {
  19387. values.push( track.values[ j * valueSize + k ] );
  19388. }
  19389. }
  19390. if ( times.length === 0 ) continue;
  19391. track.times = AnimationUtils.convertArray( times, track.times.constructor );
  19392. track.values = AnimationUtils.convertArray( values, track.values.constructor );
  19393. tracks.push( track );
  19394. }
  19395. clip.tracks = tracks;
  19396. // find minimum .times value across all tracks in the trimmed clip
  19397. let minStartTime = Infinity;
  19398. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  19399. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  19400. minStartTime = clip.tracks[ i ].times[ 0 ];
  19401. }
  19402. }
  19403. // shift all tracks such that clip begins at t=0
  19404. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  19405. clip.tracks[ i ].shift( - 1 * minStartTime );
  19406. }
  19407. clip.resetDuration();
  19408. return clip;
  19409. },
  19410. makeClipAdditive: function ( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  19411. if ( fps <= 0 ) fps = 30;
  19412. const numTracks = referenceClip.tracks.length;
  19413. const referenceTime = referenceFrame / fps;
  19414. // Make each track's values relative to the values at the reference frame
  19415. for ( let i = 0; i < numTracks; ++ i ) {
  19416. const referenceTrack = referenceClip.tracks[ i ];
  19417. const referenceTrackType = referenceTrack.ValueTypeName;
  19418. // Skip this track if it's non-numeric
  19419. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  19420. // Find the track in the target clip whose name and type matches the reference track
  19421. const targetTrack = targetClip.tracks.find( function ( track ) {
  19422. return track.name === referenceTrack.name
  19423. && track.ValueTypeName === referenceTrackType;
  19424. } );
  19425. if ( targetTrack === undefined ) continue;
  19426. let referenceOffset = 0;
  19427. const referenceValueSize = referenceTrack.getValueSize();
  19428. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  19429. referenceOffset = referenceValueSize / 3;
  19430. }
  19431. let targetOffset = 0;
  19432. const targetValueSize = targetTrack.getValueSize();
  19433. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  19434. targetOffset = targetValueSize / 3;
  19435. }
  19436. const lastIndex = referenceTrack.times.length - 1;
  19437. let referenceValue;
  19438. // Find the value to subtract out of the track
  19439. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  19440. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  19441. const startIndex = referenceOffset;
  19442. const endIndex = referenceValueSize - referenceOffset;
  19443. referenceValue = AnimationUtils.arraySlice( referenceTrack.values, startIndex, endIndex );
  19444. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  19445. // Reference frame is after the last keyframe, so just use the last keyframe
  19446. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  19447. const endIndex = startIndex + referenceValueSize - referenceOffset;
  19448. referenceValue = AnimationUtils.arraySlice( referenceTrack.values, startIndex, endIndex );
  19449. } else {
  19450. // Interpolate to the reference value
  19451. const interpolant = referenceTrack.createInterpolant();
  19452. const startIndex = referenceOffset;
  19453. const endIndex = referenceValueSize - referenceOffset;
  19454. interpolant.evaluate( referenceTime );
  19455. referenceValue = AnimationUtils.arraySlice( interpolant.resultBuffer, startIndex, endIndex );
  19456. }
  19457. // Conjugate the quaternion
  19458. if ( referenceTrackType === 'quaternion' ) {
  19459. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  19460. referenceQuat.toArray( referenceValue );
  19461. }
  19462. // Subtract the reference value from all of the track values
  19463. const numTimes = targetTrack.times.length;
  19464. for ( let j = 0; j < numTimes; ++ j ) {
  19465. const valueStart = j * targetValueSize + targetOffset;
  19466. if ( referenceTrackType === 'quaternion' ) {
  19467. // Multiply the conjugate for quaternion track types
  19468. Quaternion.multiplyQuaternionsFlat(
  19469. targetTrack.values,
  19470. valueStart,
  19471. referenceValue,
  19472. 0,
  19473. targetTrack.values,
  19474. valueStart
  19475. );
  19476. } else {
  19477. const valueEnd = targetValueSize - targetOffset * 2;
  19478. // Subtract each value for all other numeric track types
  19479. for ( let k = 0; k < valueEnd; ++ k ) {
  19480. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  19481. }
  19482. }
  19483. }
  19484. }
  19485. targetClip.blendMode = AdditiveAnimationBlendMode;
  19486. return targetClip;
  19487. }
  19488. };
  19489. /**
  19490. * Abstract base class of interpolants over parametric samples.
  19491. *
  19492. * The parameter domain is one dimensional, typically the time or a path
  19493. * along a curve defined by the data.
  19494. *
  19495. * The sample values can have any dimensionality and derived classes may
  19496. * apply special interpretations to the data.
  19497. *
  19498. * This class provides the interval seek in a Template Method, deferring
  19499. * the actual interpolation to derived classes.
  19500. *
  19501. * Time complexity is O(1) for linear access crossing at most two points
  19502. * and O(log N) for random access, where N is the number of positions.
  19503. *
  19504. * References:
  19505. *
  19506. * http://www.oodesign.com/template-method-pattern.html
  19507. *
  19508. */
  19509. function Interpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  19510. this.parameterPositions = parameterPositions;
  19511. this._cachedIndex = 0;
  19512. this.resultBuffer = resultBuffer !== undefined ?
  19513. resultBuffer : new sampleValues.constructor( sampleSize );
  19514. this.sampleValues = sampleValues;
  19515. this.valueSize = sampleSize;
  19516. }
  19517. Object.assign( Interpolant.prototype, {
  19518. evaluate: function ( t ) {
  19519. const pp = this.parameterPositions;
  19520. let i1 = this._cachedIndex,
  19521. t1 = pp[ i1 ],
  19522. t0 = pp[ i1 - 1 ];
  19523. validate_interval: {
  19524. seek: {
  19525. let right;
  19526. linear_scan: {
  19527. //- See http://jsperf.com/comparison-to-undefined/3
  19528. //- slower code:
  19529. //-
  19530. //- if ( t >= t1 || t1 === undefined ) {
  19531. forward_scan: if ( ! ( t < t1 ) ) {
  19532. for ( let giveUpAt = i1 + 2; ; ) {
  19533. if ( t1 === undefined ) {
  19534. if ( t < t0 ) break forward_scan;
  19535. // after end
  19536. i1 = pp.length;
  19537. this._cachedIndex = i1;
  19538. return this.afterEnd_( i1 - 1, t, t0 );
  19539. }
  19540. if ( i1 === giveUpAt ) break; // this loop
  19541. t0 = t1;
  19542. t1 = pp[ ++ i1 ];
  19543. if ( t < t1 ) {
  19544. // we have arrived at the sought interval
  19545. break seek;
  19546. }
  19547. }
  19548. // prepare binary search on the right side of the index
  19549. right = pp.length;
  19550. break linear_scan;
  19551. }
  19552. //- slower code:
  19553. //- if ( t < t0 || t0 === undefined ) {
  19554. if ( ! ( t >= t0 ) ) {
  19555. // looping?
  19556. const t1global = pp[ 1 ];
  19557. if ( t < t1global ) {
  19558. i1 = 2; // + 1, using the scan for the details
  19559. t0 = t1global;
  19560. }
  19561. // linear reverse scan
  19562. for ( let giveUpAt = i1 - 2; ; ) {
  19563. if ( t0 === undefined ) {
  19564. // before start
  19565. this._cachedIndex = 0;
  19566. return this.beforeStart_( 0, t, t1 );
  19567. }
  19568. if ( i1 === giveUpAt ) break; // this loop
  19569. t1 = t0;
  19570. t0 = pp[ -- i1 - 1 ];
  19571. if ( t >= t0 ) {
  19572. // we have arrived at the sought interval
  19573. break seek;
  19574. }
  19575. }
  19576. // prepare binary search on the left side of the index
  19577. right = i1;
  19578. i1 = 0;
  19579. break linear_scan;
  19580. }
  19581. // the interval is valid
  19582. break validate_interval;
  19583. } // linear scan
  19584. // binary search
  19585. while ( i1 < right ) {
  19586. const mid = ( i1 + right ) >>> 1;
  19587. if ( t < pp[ mid ] ) {
  19588. right = mid;
  19589. } else {
  19590. i1 = mid + 1;
  19591. }
  19592. }
  19593. t1 = pp[ i1 ];
  19594. t0 = pp[ i1 - 1 ];
  19595. // check boundary cases, again
  19596. if ( t0 === undefined ) {
  19597. this._cachedIndex = 0;
  19598. return this.beforeStart_( 0, t, t1 );
  19599. }
  19600. if ( t1 === undefined ) {
  19601. i1 = pp.length;
  19602. this._cachedIndex = i1;
  19603. return this.afterEnd_( i1 - 1, t0, t );
  19604. }
  19605. } // seek
  19606. this._cachedIndex = i1;
  19607. this.intervalChanged_( i1, t0, t1 );
  19608. } // validate_interval
  19609. return this.interpolate_( i1, t0, t, t1 );
  19610. },
  19611. settings: null, // optional, subclass-specific settings structure
  19612. // Note: The indirection allows central control of many interpolants.
  19613. // --- Protected interface
  19614. DefaultSettings_: {},
  19615. getSettings_: function () {
  19616. return this.settings || this.DefaultSettings_;
  19617. },
  19618. copySampleValue_: function ( index ) {
  19619. // copies a sample value to the result buffer
  19620. const result = this.resultBuffer,
  19621. values = this.sampleValues,
  19622. stride = this.valueSize,
  19623. offset = index * stride;
  19624. for ( let i = 0; i !== stride; ++ i ) {
  19625. result[ i ] = values[ offset + i ];
  19626. }
  19627. return result;
  19628. },
  19629. // Template methods for derived classes:
  19630. interpolate_: function ( /* i1, t0, t, t1 */ ) {
  19631. throw new Error( 'call to abstract method' );
  19632. // implementations shall return this.resultBuffer
  19633. },
  19634. intervalChanged_: function ( /* i1, t0, t1 */ ) {
  19635. // empty
  19636. }
  19637. } );
  19638. // DECLARE ALIAS AFTER assign prototype
  19639. Object.assign( Interpolant.prototype, {
  19640. //( 0, t, t0 ), returns this.resultBuffer
  19641. beforeStart_: Interpolant.prototype.copySampleValue_,
  19642. //( N-1, tN-1, t ), returns this.resultBuffer
  19643. afterEnd_: Interpolant.prototype.copySampleValue_,
  19644. } );
  19645. /**
  19646. * Fast and simple cubic spline interpolant.
  19647. *
  19648. * It was derived from a Hermitian construction setting the first derivative
  19649. * at each sample position to the linear slope between neighboring positions
  19650. * over their parameter interval.
  19651. */
  19652. function CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  19653. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  19654. this._weightPrev = - 0;
  19655. this._offsetPrev = - 0;
  19656. this._weightNext = - 0;
  19657. this._offsetNext = - 0;
  19658. }
  19659. CubicInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  19660. constructor: CubicInterpolant,
  19661. DefaultSettings_: {
  19662. endingStart: ZeroCurvatureEnding,
  19663. endingEnd: ZeroCurvatureEnding
  19664. },
  19665. intervalChanged_: function ( i1, t0, t1 ) {
  19666. const pp = this.parameterPositions;
  19667. let iPrev = i1 - 2,
  19668. iNext = i1 + 1,
  19669. tPrev = pp[ iPrev ],
  19670. tNext = pp[ iNext ];
  19671. if ( tPrev === undefined ) {
  19672. switch ( this.getSettings_().endingStart ) {
  19673. case ZeroSlopeEnding:
  19674. // f'(t0) = 0
  19675. iPrev = i1;
  19676. tPrev = 2 * t0 - t1;
  19677. break;
  19678. case WrapAroundEnding:
  19679. // use the other end of the curve
  19680. iPrev = pp.length - 2;
  19681. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  19682. break;
  19683. default: // ZeroCurvatureEnding
  19684. // f''(t0) = 0 a.k.a. Natural Spline
  19685. iPrev = i1;
  19686. tPrev = t1;
  19687. }
  19688. }
  19689. if ( tNext === undefined ) {
  19690. switch ( this.getSettings_().endingEnd ) {
  19691. case ZeroSlopeEnding:
  19692. // f'(tN) = 0
  19693. iNext = i1;
  19694. tNext = 2 * t1 - t0;
  19695. break;
  19696. case WrapAroundEnding:
  19697. // use the other end of the curve
  19698. iNext = 1;
  19699. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  19700. break;
  19701. default: // ZeroCurvatureEnding
  19702. // f''(tN) = 0, a.k.a. Natural Spline
  19703. iNext = i1 - 1;
  19704. tNext = t0;
  19705. }
  19706. }
  19707. const halfDt = ( t1 - t0 ) * 0.5,
  19708. stride = this.valueSize;
  19709. this._weightPrev = halfDt / ( t0 - tPrev );
  19710. this._weightNext = halfDt / ( tNext - t1 );
  19711. this._offsetPrev = iPrev * stride;
  19712. this._offsetNext = iNext * stride;
  19713. },
  19714. interpolate_: function ( i1, t0, t, t1 ) {
  19715. const result = this.resultBuffer,
  19716. values = this.sampleValues,
  19717. stride = this.valueSize,
  19718. o1 = i1 * stride, o0 = o1 - stride,
  19719. oP = this._offsetPrev, oN = this._offsetNext,
  19720. wP = this._weightPrev, wN = this._weightNext,
  19721. p = ( t - t0 ) / ( t1 - t0 ),
  19722. pp = p * p,
  19723. ppp = pp * p;
  19724. // evaluate polynomials
  19725. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  19726. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  19727. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  19728. const sN = wN * ppp - wN * pp;
  19729. // combine data linearly
  19730. for ( let i = 0; i !== stride; ++ i ) {
  19731. result[ i ] =
  19732. sP * values[ oP + i ] +
  19733. s0 * values[ o0 + i ] +
  19734. s1 * values[ o1 + i ] +
  19735. sN * values[ oN + i ];
  19736. }
  19737. return result;
  19738. }
  19739. } );
  19740. function LinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  19741. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  19742. }
  19743. LinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  19744. constructor: LinearInterpolant,
  19745. interpolate_: function ( i1, t0, t, t1 ) {
  19746. const result = this.resultBuffer,
  19747. values = this.sampleValues,
  19748. stride = this.valueSize,
  19749. offset1 = i1 * stride,
  19750. offset0 = offset1 - stride,
  19751. weight1 = ( t - t0 ) / ( t1 - t0 ),
  19752. weight0 = 1 - weight1;
  19753. for ( let i = 0; i !== stride; ++ i ) {
  19754. result[ i ] =
  19755. values[ offset0 + i ] * weight0 +
  19756. values[ offset1 + i ] * weight1;
  19757. }
  19758. return result;
  19759. }
  19760. } );
  19761. /**
  19762. *
  19763. * Interpolant that evaluates to the sample value at the position preceeding
  19764. * the parameter.
  19765. */
  19766. function DiscreteInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  19767. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  19768. }
  19769. DiscreteInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  19770. constructor: DiscreteInterpolant,
  19771. interpolate_: function ( i1 /*, t0, t, t1 */ ) {
  19772. return this.copySampleValue_( i1 - 1 );
  19773. }
  19774. } );
  19775. class KeyframeTrack {
  19776. constructor( name, times, values, interpolation ) {
  19777. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  19778. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  19779. this.name = name;
  19780. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  19781. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  19782. this.setInterpolation( interpolation || this.DefaultInterpolation );
  19783. }
  19784. // Serialization (in static context, because of constructor invocation
  19785. // and automatic invocation of .toJSON):
  19786. static toJSON( track ) {
  19787. const trackType = track.constructor;
  19788. let json;
  19789. // derived classes can define a static toJSON method
  19790. if ( trackType.toJSON !== this.toJSON ) {
  19791. json = trackType.toJSON( track );
  19792. } else {
  19793. // by default, we assume the data can be serialized as-is
  19794. json = {
  19795. 'name': track.name,
  19796. 'times': AnimationUtils.convertArray( track.times, Array ),
  19797. 'values': AnimationUtils.convertArray( track.values, Array )
  19798. };
  19799. const interpolation = track.getInterpolation();
  19800. if ( interpolation !== track.DefaultInterpolation ) {
  19801. json.interpolation = interpolation;
  19802. }
  19803. }
  19804. json.type = track.ValueTypeName; // mandatory
  19805. return json;
  19806. }
  19807. InterpolantFactoryMethodDiscrete( result ) {
  19808. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  19809. }
  19810. InterpolantFactoryMethodLinear( result ) {
  19811. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  19812. }
  19813. InterpolantFactoryMethodSmooth( result ) {
  19814. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  19815. }
  19816. setInterpolation( interpolation ) {
  19817. let factoryMethod;
  19818. switch ( interpolation ) {
  19819. case InterpolateDiscrete:
  19820. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  19821. break;
  19822. case InterpolateLinear:
  19823. factoryMethod = this.InterpolantFactoryMethodLinear;
  19824. break;
  19825. case InterpolateSmooth:
  19826. factoryMethod = this.InterpolantFactoryMethodSmooth;
  19827. break;
  19828. }
  19829. if ( factoryMethod === undefined ) {
  19830. const message = 'unsupported interpolation for ' +
  19831. this.ValueTypeName + ' keyframe track named ' + this.name;
  19832. if ( this.createInterpolant === undefined ) {
  19833. // fall back to default, unless the default itself is messed up
  19834. if ( interpolation !== this.DefaultInterpolation ) {
  19835. this.setInterpolation( this.DefaultInterpolation );
  19836. } else {
  19837. throw new Error( message ); // fatal, in this case
  19838. }
  19839. }
  19840. console.warn( 'THREE.KeyframeTrack:', message );
  19841. return this;
  19842. }
  19843. this.createInterpolant = factoryMethod;
  19844. return this;
  19845. }
  19846. getInterpolation() {
  19847. switch ( this.createInterpolant ) {
  19848. case this.InterpolantFactoryMethodDiscrete:
  19849. return InterpolateDiscrete;
  19850. case this.InterpolantFactoryMethodLinear:
  19851. return InterpolateLinear;
  19852. case this.InterpolantFactoryMethodSmooth:
  19853. return InterpolateSmooth;
  19854. }
  19855. }
  19856. getValueSize() {
  19857. return this.values.length / this.times.length;
  19858. }
  19859. // move all keyframes either forwards or backwards in time
  19860. shift( timeOffset ) {
  19861. if ( timeOffset !== 0.0 ) {
  19862. const times = this.times;
  19863. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  19864. times[ i ] += timeOffset;
  19865. }
  19866. }
  19867. return this;
  19868. }
  19869. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  19870. scale( timeScale ) {
  19871. if ( timeScale !== 1.0 ) {
  19872. const times = this.times;
  19873. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  19874. times[ i ] *= timeScale;
  19875. }
  19876. }
  19877. return this;
  19878. }
  19879. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  19880. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  19881. trim( startTime, endTime ) {
  19882. const times = this.times,
  19883. nKeys = times.length;
  19884. let from = 0,
  19885. to = nKeys - 1;
  19886. while ( from !== nKeys && times[ from ] < startTime ) {
  19887. ++ from;
  19888. }
  19889. while ( to !== - 1 && times[ to ] > endTime ) {
  19890. -- to;
  19891. }
  19892. ++ to; // inclusive -> exclusive bound
  19893. if ( from !== 0 || to !== nKeys ) {
  19894. // empty tracks are forbidden, so keep at least one keyframe
  19895. if ( from >= to ) {
  19896. to = Math.max( to, 1 );
  19897. from = to - 1;
  19898. }
  19899. const stride = this.getValueSize();
  19900. this.times = AnimationUtils.arraySlice( times, from, to );
  19901. this.values = AnimationUtils.arraySlice( this.values, from * stride, to * stride );
  19902. }
  19903. return this;
  19904. }
  19905. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  19906. validate() {
  19907. let valid = true;
  19908. const valueSize = this.getValueSize();
  19909. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  19910. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  19911. valid = false;
  19912. }
  19913. const times = this.times,
  19914. values = this.values,
  19915. nKeys = times.length;
  19916. if ( nKeys === 0 ) {
  19917. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  19918. valid = false;
  19919. }
  19920. let prevTime = null;
  19921. for ( let i = 0; i !== nKeys; i ++ ) {
  19922. const currTime = times[ i ];
  19923. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  19924. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  19925. valid = false;
  19926. break;
  19927. }
  19928. if ( prevTime !== null && prevTime > currTime ) {
  19929. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  19930. valid = false;
  19931. break;
  19932. }
  19933. prevTime = currTime;
  19934. }
  19935. if ( values !== undefined ) {
  19936. if ( AnimationUtils.isTypedArray( values ) ) {
  19937. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  19938. const value = values[ i ];
  19939. if ( isNaN( value ) ) {
  19940. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  19941. valid = false;
  19942. break;
  19943. }
  19944. }
  19945. }
  19946. }
  19947. return valid;
  19948. }
  19949. // removes equivalent sequential keys as common in morph target sequences
  19950. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  19951. optimize() {
  19952. // times or values may be shared with other tracks, so overwriting is unsafe
  19953. const times = AnimationUtils.arraySlice( this.times ),
  19954. values = AnimationUtils.arraySlice( this.values ),
  19955. stride = this.getValueSize(),
  19956. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  19957. lastIndex = times.length - 1;
  19958. let writeIndex = 1;
  19959. for ( let i = 1; i < lastIndex; ++ i ) {
  19960. let keep = false;
  19961. const time = times[ i ];
  19962. const timeNext = times[ i + 1 ];
  19963. // remove adjacent keyframes scheduled at the same time
  19964. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  19965. if ( ! smoothInterpolation ) {
  19966. // remove unnecessary keyframes same as their neighbors
  19967. const offset = i * stride,
  19968. offsetP = offset - stride,
  19969. offsetN = offset + stride;
  19970. for ( let j = 0; j !== stride; ++ j ) {
  19971. const value = values[ offset + j ];
  19972. if ( value !== values[ offsetP + j ] ||
  19973. value !== values[ offsetN + j ] ) {
  19974. keep = true;
  19975. break;
  19976. }
  19977. }
  19978. } else {
  19979. keep = true;
  19980. }
  19981. }
  19982. // in-place compaction
  19983. if ( keep ) {
  19984. if ( i !== writeIndex ) {
  19985. times[ writeIndex ] = times[ i ];
  19986. const readOffset = i * stride,
  19987. writeOffset = writeIndex * stride;
  19988. for ( let j = 0; j !== stride; ++ j ) {
  19989. values[ writeOffset + j ] = values[ readOffset + j ];
  19990. }
  19991. }
  19992. ++ writeIndex;
  19993. }
  19994. }
  19995. // flush last keyframe (compaction looks ahead)
  19996. if ( lastIndex > 0 ) {
  19997. times[ writeIndex ] = times[ lastIndex ];
  19998. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  19999. values[ writeOffset + j ] = values[ readOffset + j ];
  20000. }
  20001. ++ writeIndex;
  20002. }
  20003. if ( writeIndex !== times.length ) {
  20004. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  20005. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  20006. } else {
  20007. this.times = times;
  20008. this.values = values;
  20009. }
  20010. return this;
  20011. }
  20012. clone() {
  20013. const times = AnimationUtils.arraySlice( this.times, 0 );
  20014. const values = AnimationUtils.arraySlice( this.values, 0 );
  20015. const TypedKeyframeTrack = this.constructor;
  20016. const track = new TypedKeyframeTrack( this.name, times, values );
  20017. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  20018. track.createInterpolant = this.createInterpolant;
  20019. return track;
  20020. }
  20021. }
  20022. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  20023. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  20024. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  20025. /**
  20026. * A Track of Boolean keyframe values.
  20027. */
  20028. class BooleanKeyframeTrack extends KeyframeTrack {}
  20029. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  20030. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  20031. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  20032. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  20033. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  20034. /**
  20035. * A Track of keyframe values that represent color.
  20036. */
  20037. class ColorKeyframeTrack extends KeyframeTrack {}
  20038. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  20039. /**
  20040. * A Track of numeric keyframe values.
  20041. */
  20042. class NumberKeyframeTrack extends KeyframeTrack {}
  20043. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  20044. /**
  20045. * Spherical linear unit quaternion interpolant.
  20046. */
  20047. function QuaternionLinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  20048. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  20049. }
  20050. QuaternionLinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  20051. constructor: QuaternionLinearInterpolant,
  20052. interpolate_: function ( i1, t0, t, t1 ) {
  20053. const result = this.resultBuffer,
  20054. values = this.sampleValues,
  20055. stride = this.valueSize,
  20056. alpha = ( t - t0 ) / ( t1 - t0 );
  20057. let offset = i1 * stride;
  20058. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  20059. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  20060. }
  20061. return result;
  20062. }
  20063. } );
  20064. /**
  20065. * A Track of quaternion keyframe values.
  20066. */
  20067. class QuaternionKeyframeTrack extends KeyframeTrack {
  20068. InterpolantFactoryMethodLinear( result ) {
  20069. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  20070. }
  20071. }
  20072. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  20073. // ValueBufferType is inherited
  20074. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  20075. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  20076. /**
  20077. * A Track that interpolates Strings
  20078. */
  20079. class StringKeyframeTrack extends KeyframeTrack {}
  20080. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  20081. StringKeyframeTrack.prototype.ValueBufferType = Array;
  20082. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  20083. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  20084. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  20085. /**
  20086. * A Track of vectored keyframe values.
  20087. */
  20088. class VectorKeyframeTrack extends KeyframeTrack {}
  20089. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  20090. class AnimationClip {
  20091. constructor( name, duration = - 1, tracks, blendMode = NormalAnimationBlendMode ) {
  20092. this.name = name;
  20093. this.tracks = tracks;
  20094. this.duration = duration;
  20095. this.blendMode = blendMode;
  20096. this.uuid = MathUtils.generateUUID();
  20097. // this means it should figure out its duration by scanning the tracks
  20098. if ( this.duration < 0 ) {
  20099. this.resetDuration();
  20100. }
  20101. }
  20102. static parse( json ) {
  20103. const tracks = [],
  20104. jsonTracks = json.tracks,
  20105. frameTime = 1.0 / ( json.fps || 1.0 );
  20106. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  20107. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  20108. }
  20109. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  20110. clip.uuid = json.uuid;
  20111. return clip;
  20112. }
  20113. static toJSON( clip ) {
  20114. const tracks = [],
  20115. clipTracks = clip.tracks;
  20116. const json = {
  20117. 'name': clip.name,
  20118. 'duration': clip.duration,
  20119. 'tracks': tracks,
  20120. 'uuid': clip.uuid,
  20121. 'blendMode': clip.blendMode
  20122. };
  20123. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  20124. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  20125. }
  20126. return json;
  20127. }
  20128. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  20129. const numMorphTargets = morphTargetSequence.length;
  20130. const tracks = [];
  20131. for ( let i = 0; i < numMorphTargets; i ++ ) {
  20132. let times = [];
  20133. let values = [];
  20134. times.push(
  20135. ( i + numMorphTargets - 1 ) % numMorphTargets,
  20136. i,
  20137. ( i + 1 ) % numMorphTargets );
  20138. values.push( 0, 1, 0 );
  20139. const order = AnimationUtils.getKeyframeOrder( times );
  20140. times = AnimationUtils.sortedArray( times, 1, order );
  20141. values = AnimationUtils.sortedArray( values, 1, order );
  20142. // if there is a key at the first frame, duplicate it as the
  20143. // last frame as well for perfect loop.
  20144. if ( ! noLoop && times[ 0 ] === 0 ) {
  20145. times.push( numMorphTargets );
  20146. values.push( values[ 0 ] );
  20147. }
  20148. tracks.push(
  20149. new NumberKeyframeTrack(
  20150. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  20151. times, values
  20152. ).scale( 1.0 / fps ) );
  20153. }
  20154. return new this( name, - 1, tracks );
  20155. }
  20156. static findByName( objectOrClipArray, name ) {
  20157. let clipArray = objectOrClipArray;
  20158. if ( ! Array.isArray( objectOrClipArray ) ) {
  20159. const o = objectOrClipArray;
  20160. clipArray = o.geometry && o.geometry.animations || o.animations;
  20161. }
  20162. for ( let i = 0; i < clipArray.length; i ++ ) {
  20163. if ( clipArray[ i ].name === name ) {
  20164. return clipArray[ i ];
  20165. }
  20166. }
  20167. return null;
  20168. }
  20169. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  20170. const animationToMorphTargets = {};
  20171. // tested with https://regex101.com/ on trick sequences
  20172. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  20173. const pattern = /^([\w-]*?)([\d]+)$/;
  20174. // sort morph target names into animation groups based
  20175. // patterns like Walk_001, Walk_002, Run_001, Run_002
  20176. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  20177. const morphTarget = morphTargets[ i ];
  20178. const parts = morphTarget.name.match( pattern );
  20179. if ( parts && parts.length > 1 ) {
  20180. const name = parts[ 1 ];
  20181. let animationMorphTargets = animationToMorphTargets[ name ];
  20182. if ( ! animationMorphTargets ) {
  20183. animationToMorphTargets[ name ] = animationMorphTargets = [];
  20184. }
  20185. animationMorphTargets.push( morphTarget );
  20186. }
  20187. }
  20188. const clips = [];
  20189. for ( const name in animationToMorphTargets ) {
  20190. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  20191. }
  20192. return clips;
  20193. }
  20194. // parse the animation.hierarchy format
  20195. static parseAnimation( animation, bones ) {
  20196. if ( ! animation ) {
  20197. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  20198. return null;
  20199. }
  20200. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  20201. // only return track if there are actually keys.
  20202. if ( animationKeys.length !== 0 ) {
  20203. const times = [];
  20204. const values = [];
  20205. AnimationUtils.flattenJSON( animationKeys, times, values, propertyName );
  20206. // empty keys are filtered out, so check again
  20207. if ( times.length !== 0 ) {
  20208. destTracks.push( new trackType( trackName, times, values ) );
  20209. }
  20210. }
  20211. };
  20212. const tracks = [];
  20213. const clipName = animation.name || 'default';
  20214. const fps = animation.fps || 30;
  20215. const blendMode = animation.blendMode;
  20216. // automatic length determination in AnimationClip.
  20217. let duration = animation.length || - 1;
  20218. const hierarchyTracks = animation.hierarchy || [];
  20219. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  20220. const animationKeys = hierarchyTracks[ h ].keys;
  20221. // skip empty tracks
  20222. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  20223. // process morph targets
  20224. if ( animationKeys[ 0 ].morphTargets ) {
  20225. // figure out all morph targets used in this track
  20226. const morphTargetNames = {};
  20227. let k;
  20228. for ( k = 0; k < animationKeys.length; k ++ ) {
  20229. if ( animationKeys[ k ].morphTargets ) {
  20230. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  20231. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  20232. }
  20233. }
  20234. }
  20235. // create a track for each morph target with all zero
  20236. // morphTargetInfluences except for the keys in which
  20237. // the morphTarget is named.
  20238. for ( const morphTargetName in morphTargetNames ) {
  20239. const times = [];
  20240. const values = [];
  20241. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  20242. const animationKey = animationKeys[ k ];
  20243. times.push( animationKey.time );
  20244. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  20245. }
  20246. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  20247. }
  20248. duration = morphTargetNames.length * ( fps || 1.0 );
  20249. } else {
  20250. // ...assume skeletal animation
  20251. const boneName = '.bones[' + bones[ h ].name + ']';
  20252. addNonemptyTrack(
  20253. VectorKeyframeTrack, boneName + '.position',
  20254. animationKeys, 'pos', tracks );
  20255. addNonemptyTrack(
  20256. QuaternionKeyframeTrack, boneName + '.quaternion',
  20257. animationKeys, 'rot', tracks );
  20258. addNonemptyTrack(
  20259. VectorKeyframeTrack, boneName + '.scale',
  20260. animationKeys, 'scl', tracks );
  20261. }
  20262. }
  20263. if ( tracks.length === 0 ) {
  20264. return null;
  20265. }
  20266. const clip = new this( clipName, duration, tracks, blendMode );
  20267. return clip;
  20268. }
  20269. resetDuration() {
  20270. const tracks = this.tracks;
  20271. let duration = 0;
  20272. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  20273. const track = this.tracks[ i ];
  20274. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  20275. }
  20276. this.duration = duration;
  20277. return this;
  20278. }
  20279. trim() {
  20280. for ( let i = 0; i < this.tracks.length; i ++ ) {
  20281. this.tracks[ i ].trim( 0, this.duration );
  20282. }
  20283. return this;
  20284. }
  20285. validate() {
  20286. let valid = true;
  20287. for ( let i = 0; i < this.tracks.length; i ++ ) {
  20288. valid = valid && this.tracks[ i ].validate();
  20289. }
  20290. return valid;
  20291. }
  20292. optimize() {
  20293. for ( let i = 0; i < this.tracks.length; i ++ ) {
  20294. this.tracks[ i ].optimize();
  20295. }
  20296. return this;
  20297. }
  20298. clone() {
  20299. const tracks = [];
  20300. for ( let i = 0; i < this.tracks.length; i ++ ) {
  20301. tracks.push( this.tracks[ i ].clone() );
  20302. }
  20303. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  20304. }
  20305. toJSON() {
  20306. return this.constructor.toJSON( this );
  20307. }
  20308. }
  20309. function getTrackTypeForValueTypeName( typeName ) {
  20310. switch ( typeName.toLowerCase() ) {
  20311. case 'scalar':
  20312. case 'double':
  20313. case 'float':
  20314. case 'number':
  20315. case 'integer':
  20316. return NumberKeyframeTrack;
  20317. case 'vector':
  20318. case 'vector2':
  20319. case 'vector3':
  20320. case 'vector4':
  20321. return VectorKeyframeTrack;
  20322. case 'color':
  20323. return ColorKeyframeTrack;
  20324. case 'quaternion':
  20325. return QuaternionKeyframeTrack;
  20326. case 'bool':
  20327. case 'boolean':
  20328. return BooleanKeyframeTrack;
  20329. case 'string':
  20330. return StringKeyframeTrack;
  20331. }
  20332. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  20333. }
  20334. function parseKeyframeTrack( json ) {
  20335. if ( json.type === undefined ) {
  20336. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  20337. }
  20338. const trackType = getTrackTypeForValueTypeName( json.type );
  20339. if ( json.times === undefined ) {
  20340. const times = [], values = [];
  20341. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  20342. json.times = times;
  20343. json.values = values;
  20344. }
  20345. // derived classes can define a static parse method
  20346. if ( trackType.parse !== undefined ) {
  20347. return trackType.parse( json );
  20348. } else {
  20349. // by default, we assume a constructor compatible with the base
  20350. return new trackType( json.name, json.times, json.values, json.interpolation );
  20351. }
  20352. }
  20353. const Cache = {
  20354. enabled: false,
  20355. files: {},
  20356. add: function ( key, file ) {
  20357. if ( this.enabled === false ) return;
  20358. // console.log( 'THREE.Cache', 'Adding key:', key );
  20359. this.files[ key ] = file;
  20360. },
  20361. get: function ( key ) {
  20362. if ( this.enabled === false ) return;
  20363. // console.log( 'THREE.Cache', 'Checking key:', key );
  20364. return this.files[ key ];
  20365. },
  20366. remove: function ( key ) {
  20367. delete this.files[ key ];
  20368. },
  20369. clear: function () {
  20370. this.files = {};
  20371. }
  20372. };
  20373. function LoadingManager( onLoad, onProgress, onError ) {
  20374. const scope = this;
  20375. let isLoading = false;
  20376. let itemsLoaded = 0;
  20377. let itemsTotal = 0;
  20378. let urlModifier = undefined;
  20379. const handlers = [];
  20380. // Refer to #5689 for the reason why we don't set .onStart
  20381. // in the constructor
  20382. this.onStart = undefined;
  20383. this.onLoad = onLoad;
  20384. this.onProgress = onProgress;
  20385. this.onError = onError;
  20386. this.itemStart = function ( url ) {
  20387. itemsTotal ++;
  20388. if ( isLoading === false ) {
  20389. if ( scope.onStart !== undefined ) {
  20390. scope.onStart( url, itemsLoaded, itemsTotal );
  20391. }
  20392. }
  20393. isLoading = true;
  20394. };
  20395. this.itemEnd = function ( url ) {
  20396. itemsLoaded ++;
  20397. if ( scope.onProgress !== undefined ) {
  20398. scope.onProgress( url, itemsLoaded, itemsTotal );
  20399. }
  20400. if ( itemsLoaded === itemsTotal ) {
  20401. isLoading = false;
  20402. if ( scope.onLoad !== undefined ) {
  20403. scope.onLoad();
  20404. }
  20405. }
  20406. };
  20407. this.itemError = function ( url ) {
  20408. if ( scope.onError !== undefined ) {
  20409. scope.onError( url );
  20410. }
  20411. };
  20412. this.resolveURL = function ( url ) {
  20413. if ( urlModifier ) {
  20414. return urlModifier( url );
  20415. }
  20416. return url;
  20417. };
  20418. this.setURLModifier = function ( transform ) {
  20419. urlModifier = transform;
  20420. return this;
  20421. };
  20422. this.addHandler = function ( regex, loader ) {
  20423. handlers.push( regex, loader );
  20424. return this;
  20425. };
  20426. this.removeHandler = function ( regex ) {
  20427. const index = handlers.indexOf( regex );
  20428. if ( index !== - 1 ) {
  20429. handlers.splice( index, 2 );
  20430. }
  20431. return this;
  20432. };
  20433. this.getHandler = function ( file ) {
  20434. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  20435. const regex = handlers[ i ];
  20436. const loader = handlers[ i + 1 ];
  20437. if ( regex.global ) regex.lastIndex = 0; // see #17920
  20438. if ( regex.test( file ) ) {
  20439. return loader;
  20440. }
  20441. }
  20442. return null;
  20443. };
  20444. }
  20445. const DefaultLoadingManager = new LoadingManager();
  20446. function Loader( manager ) {
  20447. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  20448. this.crossOrigin = 'anonymous';
  20449. this.withCredentials = false;
  20450. this.path = '';
  20451. this.resourcePath = '';
  20452. this.requestHeader = {};
  20453. }
  20454. Object.assign( Loader.prototype, {
  20455. load: function ( /* url, onLoad, onProgress, onError */ ) {},
  20456. loadAsync: function ( url, onProgress ) {
  20457. const scope = this;
  20458. return new Promise( function ( resolve, reject ) {
  20459. scope.load( url, resolve, onProgress, reject );
  20460. } );
  20461. },
  20462. parse: function ( /* data */ ) {},
  20463. setCrossOrigin: function ( crossOrigin ) {
  20464. this.crossOrigin = crossOrigin;
  20465. return this;
  20466. },
  20467. setWithCredentials: function ( value ) {
  20468. this.withCredentials = value;
  20469. return this;
  20470. },
  20471. setPath: function ( path ) {
  20472. this.path = path;
  20473. return this;
  20474. },
  20475. setResourcePath: function ( resourcePath ) {
  20476. this.resourcePath = resourcePath;
  20477. return this;
  20478. },
  20479. setRequestHeader: function ( requestHeader ) {
  20480. this.requestHeader = requestHeader;
  20481. return this;
  20482. }
  20483. } );
  20484. const loading = {};
  20485. function FileLoader( manager ) {
  20486. Loader.call( this, manager );
  20487. }
  20488. FileLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  20489. constructor: FileLoader,
  20490. load: function ( url, onLoad, onProgress, onError ) {
  20491. if ( url === undefined ) url = '';
  20492. if ( this.path !== undefined ) url = this.path + url;
  20493. url = this.manager.resolveURL( url );
  20494. const scope = this;
  20495. const cached = Cache.get( url );
  20496. if ( cached !== undefined ) {
  20497. scope.manager.itemStart( url );
  20498. setTimeout( function () {
  20499. if ( onLoad ) onLoad( cached );
  20500. scope.manager.itemEnd( url );
  20501. }, 0 );
  20502. return cached;
  20503. }
  20504. // Check if request is duplicate
  20505. if ( loading[ url ] !== undefined ) {
  20506. loading[ url ].push( {
  20507. onLoad: onLoad,
  20508. onProgress: onProgress,
  20509. onError: onError
  20510. } );
  20511. return;
  20512. }
  20513. // Check for data: URI
  20514. const dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  20515. const dataUriRegexResult = url.match( dataUriRegex );
  20516. let request;
  20517. // Safari can not handle Data URIs through XMLHttpRequest so process manually
  20518. if ( dataUriRegexResult ) {
  20519. const mimeType = dataUriRegexResult[ 1 ];
  20520. const isBase64 = !! dataUriRegexResult[ 2 ];
  20521. let data = dataUriRegexResult[ 3 ];
  20522. data = decodeURIComponent( data );
  20523. if ( isBase64 ) data = atob( data );
  20524. try {
  20525. let response;
  20526. const responseType = ( this.responseType || '' ).toLowerCase();
  20527. switch ( responseType ) {
  20528. case 'arraybuffer':
  20529. case 'blob':
  20530. const view = new Uint8Array( data.length );
  20531. for ( let i = 0; i < data.length; i ++ ) {
  20532. view[ i ] = data.charCodeAt( i );
  20533. }
  20534. if ( responseType === 'blob' ) {
  20535. response = new Blob( [ view.buffer ], { type: mimeType } );
  20536. } else {
  20537. response = view.buffer;
  20538. }
  20539. break;
  20540. case 'document':
  20541. const parser = new DOMParser();
  20542. response = parser.parseFromString( data, mimeType );
  20543. break;
  20544. case 'json':
  20545. response = JSON.parse( data );
  20546. break;
  20547. default: // 'text' or other
  20548. response = data;
  20549. break;
  20550. }
  20551. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  20552. setTimeout( function () {
  20553. if ( onLoad ) onLoad( response );
  20554. scope.manager.itemEnd( url );
  20555. }, 0 );
  20556. } catch ( error ) {
  20557. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  20558. setTimeout( function () {
  20559. if ( onError ) onError( error );
  20560. scope.manager.itemError( url );
  20561. scope.manager.itemEnd( url );
  20562. }, 0 );
  20563. }
  20564. } else {
  20565. // Initialise array for duplicate requests
  20566. loading[ url ] = [];
  20567. loading[ url ].push( {
  20568. onLoad: onLoad,
  20569. onProgress: onProgress,
  20570. onError: onError
  20571. } );
  20572. request = new XMLHttpRequest();
  20573. request.open( 'GET', url, true );
  20574. request.addEventListener( 'load', function ( event ) {
  20575. const response = this.response;
  20576. const callbacks = loading[ url ];
  20577. delete loading[ url ];
  20578. if ( this.status === 200 || this.status === 0 ) {
  20579. // Some browsers return HTTP Status 0 when using non-http protocol
  20580. // e.g. 'file://' or 'data://'. Handle as success.
  20581. if ( this.status === 0 ) console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  20582. // Add to cache only on HTTP success, so that we do not cache
  20583. // error response bodies as proper responses to requests.
  20584. Cache.add( url, response );
  20585. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  20586. const callback = callbacks[ i ];
  20587. if ( callback.onLoad ) callback.onLoad( response );
  20588. }
  20589. scope.manager.itemEnd( url );
  20590. } else {
  20591. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  20592. const callback = callbacks[ i ];
  20593. if ( callback.onError ) callback.onError( event );
  20594. }
  20595. scope.manager.itemError( url );
  20596. scope.manager.itemEnd( url );
  20597. }
  20598. }, false );
  20599. request.addEventListener( 'progress', function ( event ) {
  20600. const callbacks = loading[ url ];
  20601. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  20602. const callback = callbacks[ i ];
  20603. if ( callback.onProgress ) callback.onProgress( event );
  20604. }
  20605. }, false );
  20606. request.addEventListener( 'error', function ( event ) {
  20607. const callbacks = loading[ url ];
  20608. delete loading[ url ];
  20609. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  20610. const callback = callbacks[ i ];
  20611. if ( callback.onError ) callback.onError( event );
  20612. }
  20613. scope.manager.itemError( url );
  20614. scope.manager.itemEnd( url );
  20615. }, false );
  20616. request.addEventListener( 'abort', function ( event ) {
  20617. const callbacks = loading[ url ];
  20618. delete loading[ url ];
  20619. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  20620. const callback = callbacks[ i ];
  20621. if ( callback.onError ) callback.onError( event );
  20622. }
  20623. scope.manager.itemError( url );
  20624. scope.manager.itemEnd( url );
  20625. }, false );
  20626. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  20627. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  20628. if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' );
  20629. for ( const header in this.requestHeader ) {
  20630. request.setRequestHeader( header, this.requestHeader[ header ] );
  20631. }
  20632. request.send( null );
  20633. }
  20634. scope.manager.itemStart( url );
  20635. return request;
  20636. },
  20637. setResponseType: function ( value ) {
  20638. this.responseType = value;
  20639. return this;
  20640. },
  20641. setMimeType: function ( value ) {
  20642. this.mimeType = value;
  20643. return this;
  20644. }
  20645. } );
  20646. class AnimationLoader extends Loader {
  20647. constructor( manager ) {
  20648. super( manager );
  20649. }
  20650. load( url, onLoad, onProgress, onError ) {
  20651. const scope = this;
  20652. const loader = new FileLoader( this.manager );
  20653. loader.setPath( this.path );
  20654. loader.setRequestHeader( this.requestHeader );
  20655. loader.setWithCredentials( this.withCredentials );
  20656. loader.load( url, function ( text ) {
  20657. try {
  20658. onLoad( scope.parse( JSON.parse( text ) ) );
  20659. } catch ( e ) {
  20660. if ( onError ) {
  20661. onError( e );
  20662. } else {
  20663. console.error( e );
  20664. }
  20665. scope.manager.itemError( url );
  20666. }
  20667. }, onProgress, onError );
  20668. }
  20669. parse( json ) {
  20670. const animations = [];
  20671. for ( let i = 0; i < json.length; i ++ ) {
  20672. const clip = AnimationClip.parse( json[ i ] );
  20673. animations.push( clip );
  20674. }
  20675. return animations;
  20676. }
  20677. }
  20678. /**
  20679. * Abstract Base class to block based textures loader (dds, pvr, ...)
  20680. *
  20681. * Sub classes have to implement the parse() method which will be used in load().
  20682. */
  20683. function CompressedTextureLoader( manager ) {
  20684. Loader.call( this, manager );
  20685. }
  20686. CompressedTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  20687. constructor: CompressedTextureLoader,
  20688. load: function ( url, onLoad, onProgress, onError ) {
  20689. const scope = this;
  20690. const images = [];
  20691. const texture = new CompressedTexture();
  20692. const loader = new FileLoader( this.manager );
  20693. loader.setPath( this.path );
  20694. loader.setResponseType( 'arraybuffer' );
  20695. loader.setRequestHeader( this.requestHeader );
  20696. loader.setWithCredentials( scope.withCredentials );
  20697. let loaded = 0;
  20698. function loadTexture( i ) {
  20699. loader.load( url[ i ], function ( buffer ) {
  20700. const texDatas = scope.parse( buffer, true );
  20701. images[ i ] = {
  20702. width: texDatas.width,
  20703. height: texDatas.height,
  20704. format: texDatas.format,
  20705. mipmaps: texDatas.mipmaps
  20706. };
  20707. loaded += 1;
  20708. if ( loaded === 6 ) {
  20709. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  20710. texture.image = images;
  20711. texture.format = texDatas.format;
  20712. texture.needsUpdate = true;
  20713. if ( onLoad ) onLoad( texture );
  20714. }
  20715. }, onProgress, onError );
  20716. }
  20717. if ( Array.isArray( url ) ) {
  20718. for ( let i = 0, il = url.length; i < il; ++ i ) {
  20719. loadTexture( i );
  20720. }
  20721. } else {
  20722. // compressed cubemap texture stored in a single DDS file
  20723. loader.load( url, function ( buffer ) {
  20724. const texDatas = scope.parse( buffer, true );
  20725. if ( texDatas.isCubemap ) {
  20726. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  20727. for ( let f = 0; f < faces; f ++ ) {
  20728. images[ f ] = { mipmaps: [] };
  20729. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  20730. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  20731. images[ f ].format = texDatas.format;
  20732. images[ f ].width = texDatas.width;
  20733. images[ f ].height = texDatas.height;
  20734. }
  20735. }
  20736. texture.image = images;
  20737. } else {
  20738. texture.image.width = texDatas.width;
  20739. texture.image.height = texDatas.height;
  20740. texture.mipmaps = texDatas.mipmaps;
  20741. }
  20742. if ( texDatas.mipmapCount === 1 ) {
  20743. texture.minFilter = LinearFilter;
  20744. }
  20745. texture.format = texDatas.format;
  20746. texture.needsUpdate = true;
  20747. if ( onLoad ) onLoad( texture );
  20748. }, onProgress, onError );
  20749. }
  20750. return texture;
  20751. }
  20752. } );
  20753. class ImageLoader extends Loader {
  20754. constructor( manager ) {
  20755. super( manager );
  20756. }
  20757. load( url, onLoad, onProgress, onError ) {
  20758. if ( this.path !== undefined ) url = this.path + url;
  20759. url = this.manager.resolveURL( url );
  20760. const scope = this;
  20761. const cached = Cache.get( url );
  20762. if ( cached !== undefined ) {
  20763. scope.manager.itemStart( url );
  20764. setTimeout( function () {
  20765. if ( onLoad ) onLoad( cached );
  20766. scope.manager.itemEnd( url );
  20767. }, 0 );
  20768. return cached;
  20769. }
  20770. const image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  20771. function onImageLoad() {
  20772. image.removeEventListener( 'load', onImageLoad, false );
  20773. image.removeEventListener( 'error', onImageError, false );
  20774. Cache.add( url, this );
  20775. if ( onLoad ) onLoad( this );
  20776. scope.manager.itemEnd( url );
  20777. }
  20778. function onImageError( event ) {
  20779. image.removeEventListener( 'load', onImageLoad, false );
  20780. image.removeEventListener( 'error', onImageError, false );
  20781. if ( onError ) onError( event );
  20782. scope.manager.itemError( url );
  20783. scope.manager.itemEnd( url );
  20784. }
  20785. image.addEventListener( 'load', onImageLoad, false );
  20786. image.addEventListener( 'error', onImageError, false );
  20787. if ( url.substr( 0, 5 ) !== 'data:' ) {
  20788. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  20789. }
  20790. scope.manager.itemStart( url );
  20791. image.src = url;
  20792. return image;
  20793. }
  20794. }
  20795. class CubeTextureLoader extends Loader {
  20796. constructor( manager ) {
  20797. super( manager );
  20798. }
  20799. load( urls, onLoad, onProgress, onError ) {
  20800. const texture = new CubeTexture();
  20801. const loader = new ImageLoader( this.manager );
  20802. loader.setCrossOrigin( this.crossOrigin );
  20803. loader.setPath( this.path );
  20804. let loaded = 0;
  20805. function loadTexture( i ) {
  20806. loader.load( urls[ i ], function ( image ) {
  20807. texture.images[ i ] = image;
  20808. loaded ++;
  20809. if ( loaded === 6 ) {
  20810. texture.needsUpdate = true;
  20811. if ( onLoad ) onLoad( texture );
  20812. }
  20813. }, undefined, onError );
  20814. }
  20815. for ( let i = 0; i < urls.length; ++ i ) {
  20816. loadTexture( i );
  20817. }
  20818. return texture;
  20819. }
  20820. }
  20821. /**
  20822. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  20823. *
  20824. * Sub classes have to implement the parse() method which will be used in load().
  20825. */
  20826. function DataTextureLoader( manager ) {
  20827. Loader.call( this, manager );
  20828. }
  20829. DataTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  20830. constructor: DataTextureLoader,
  20831. load: function ( url, onLoad, onProgress, onError ) {
  20832. const scope = this;
  20833. const texture = new DataTexture();
  20834. const loader = new FileLoader( this.manager );
  20835. loader.setResponseType( 'arraybuffer' );
  20836. loader.setRequestHeader( this.requestHeader );
  20837. loader.setPath( this.path );
  20838. loader.setWithCredentials( scope.withCredentials );
  20839. loader.load( url, function ( buffer ) {
  20840. const texData = scope.parse( buffer );
  20841. if ( ! texData ) return;
  20842. if ( texData.image !== undefined ) {
  20843. texture.image = texData.image;
  20844. } else if ( texData.data !== undefined ) {
  20845. texture.image.width = texData.width;
  20846. texture.image.height = texData.height;
  20847. texture.image.data = texData.data;
  20848. }
  20849. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  20850. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  20851. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  20852. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  20853. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  20854. if ( texData.encoding !== undefined ) {
  20855. texture.encoding = texData.encoding;
  20856. }
  20857. if ( texData.flipY !== undefined ) {
  20858. texture.flipY = texData.flipY;
  20859. }
  20860. if ( texData.format !== undefined ) {
  20861. texture.format = texData.format;
  20862. }
  20863. if ( texData.type !== undefined ) {
  20864. texture.type = texData.type;
  20865. }
  20866. if ( texData.mipmaps !== undefined ) {
  20867. texture.mipmaps = texData.mipmaps;
  20868. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  20869. }
  20870. if ( texData.mipmapCount === 1 ) {
  20871. texture.minFilter = LinearFilter;
  20872. }
  20873. if ( texData.generateMipmaps !== undefined ) {
  20874. texture.generateMipmaps = texData.generateMipmaps;
  20875. }
  20876. texture.needsUpdate = true;
  20877. if ( onLoad ) onLoad( texture, texData );
  20878. }, onProgress, onError );
  20879. return texture;
  20880. }
  20881. } );
  20882. function TextureLoader( manager ) {
  20883. Loader.call( this, manager );
  20884. }
  20885. TextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  20886. constructor: TextureLoader,
  20887. load: function ( url, onLoad, onProgress, onError ) {
  20888. const texture = new Texture();
  20889. const loader = new ImageLoader( this.manager );
  20890. loader.setCrossOrigin( this.crossOrigin );
  20891. loader.setPath( this.path );
  20892. loader.load( url, function ( image ) {
  20893. texture.image = image;
  20894. // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  20895. const isJPEG = url.search( /\.jpe?g($|\?)/i ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
  20896. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  20897. texture.needsUpdate = true;
  20898. if ( onLoad !== undefined ) {
  20899. onLoad( texture );
  20900. }
  20901. }, onProgress, onError );
  20902. return texture;
  20903. }
  20904. } );
  20905. /**
  20906. * Extensible curve object.
  20907. *
  20908. * Some common of curve methods:
  20909. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  20910. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  20911. * .getPoints(), .getSpacedPoints()
  20912. * .getLength()
  20913. * .updateArcLengths()
  20914. *
  20915. * This following curves inherit from THREE.Curve:
  20916. *
  20917. * -- 2D curves --
  20918. * THREE.ArcCurve
  20919. * THREE.CubicBezierCurve
  20920. * THREE.EllipseCurve
  20921. * THREE.LineCurve
  20922. * THREE.QuadraticBezierCurve
  20923. * THREE.SplineCurve
  20924. *
  20925. * -- 3D curves --
  20926. * THREE.CatmullRomCurve3
  20927. * THREE.CubicBezierCurve3
  20928. * THREE.LineCurve3
  20929. * THREE.QuadraticBezierCurve3
  20930. *
  20931. * A series of curves can be represented as a THREE.CurvePath.
  20932. *
  20933. **/
  20934. function Curve() {
  20935. this.type = 'Curve';
  20936. this.arcLengthDivisions = 200;
  20937. }
  20938. Object.assign( Curve.prototype, {
  20939. // Virtual base class method to overwrite and implement in subclasses
  20940. // - t [0 .. 1]
  20941. getPoint: function ( /* t, optionalTarget */ ) {
  20942. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  20943. return null;
  20944. },
  20945. // Get point at relative position in curve according to arc length
  20946. // - u [0 .. 1]
  20947. getPointAt: function ( u, optionalTarget ) {
  20948. const t = this.getUtoTmapping( u );
  20949. return this.getPoint( t, optionalTarget );
  20950. },
  20951. // Get sequence of points using getPoint( t )
  20952. getPoints: function ( divisions = 5 ) {
  20953. const points = [];
  20954. for ( let d = 0; d <= divisions; d ++ ) {
  20955. points.push( this.getPoint( d / divisions ) );
  20956. }
  20957. return points;
  20958. },
  20959. // Get sequence of points using getPointAt( u )
  20960. getSpacedPoints: function ( divisions = 5 ) {
  20961. const points = [];
  20962. for ( let d = 0; d <= divisions; d ++ ) {
  20963. points.push( this.getPointAt( d / divisions ) );
  20964. }
  20965. return points;
  20966. },
  20967. // Get total curve arc length
  20968. getLength: function () {
  20969. const lengths = this.getLengths();
  20970. return lengths[ lengths.length - 1 ];
  20971. },
  20972. // Get list of cumulative segment lengths
  20973. getLengths: function ( divisions ) {
  20974. if ( divisions === undefined ) divisions = this.arcLengthDivisions;
  20975. if ( this.cacheArcLengths &&
  20976. ( this.cacheArcLengths.length === divisions + 1 ) &&
  20977. ! this.needsUpdate ) {
  20978. return this.cacheArcLengths;
  20979. }
  20980. this.needsUpdate = false;
  20981. const cache = [];
  20982. let current, last = this.getPoint( 0 );
  20983. let sum = 0;
  20984. cache.push( 0 );
  20985. for ( let p = 1; p <= divisions; p ++ ) {
  20986. current = this.getPoint( p / divisions );
  20987. sum += current.distanceTo( last );
  20988. cache.push( sum );
  20989. last = current;
  20990. }
  20991. this.cacheArcLengths = cache;
  20992. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  20993. },
  20994. updateArcLengths: function () {
  20995. this.needsUpdate = true;
  20996. this.getLengths();
  20997. },
  20998. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  20999. getUtoTmapping: function ( u, distance ) {
  21000. const arcLengths = this.getLengths();
  21001. let i = 0;
  21002. const il = arcLengths.length;
  21003. let targetArcLength; // The targeted u distance value to get
  21004. if ( distance ) {
  21005. targetArcLength = distance;
  21006. } else {
  21007. targetArcLength = u * arcLengths[ il - 1 ];
  21008. }
  21009. // binary search for the index with largest value smaller than target u distance
  21010. let low = 0, high = il - 1, comparison;
  21011. while ( low <= high ) {
  21012. 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
  21013. comparison = arcLengths[ i ] - targetArcLength;
  21014. if ( comparison < 0 ) {
  21015. low = i + 1;
  21016. } else if ( comparison > 0 ) {
  21017. high = i - 1;
  21018. } else {
  21019. high = i;
  21020. break;
  21021. // DONE
  21022. }
  21023. }
  21024. i = high;
  21025. if ( arcLengths[ i ] === targetArcLength ) {
  21026. return i / ( il - 1 );
  21027. }
  21028. // we could get finer grain at lengths, or use simple interpolation between two points
  21029. const lengthBefore = arcLengths[ i ];
  21030. const lengthAfter = arcLengths[ i + 1 ];
  21031. const segmentLength = lengthAfter - lengthBefore;
  21032. // determine where we are between the 'before' and 'after' points
  21033. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  21034. // add that fractional amount to t
  21035. const t = ( i + segmentFraction ) / ( il - 1 );
  21036. return t;
  21037. },
  21038. // Returns a unit vector tangent at t
  21039. // In case any sub curve does not implement its tangent derivation,
  21040. // 2 points a small delta apart will be used to find its gradient
  21041. // which seems to give a reasonable approximation
  21042. getTangent: function ( t, optionalTarget ) {
  21043. const delta = 0.0001;
  21044. let t1 = t - delta;
  21045. let t2 = t + delta;
  21046. // Capping in case of danger
  21047. if ( t1 < 0 ) t1 = 0;
  21048. if ( t2 > 1 ) t2 = 1;
  21049. const pt1 = this.getPoint( t1 );
  21050. const pt2 = this.getPoint( t2 );
  21051. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  21052. tangent.copy( pt2 ).sub( pt1 ).normalize();
  21053. return tangent;
  21054. },
  21055. getTangentAt: function ( u, optionalTarget ) {
  21056. const t = this.getUtoTmapping( u );
  21057. return this.getTangent( t, optionalTarget );
  21058. },
  21059. computeFrenetFrames: function ( segments, closed ) {
  21060. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  21061. const normal = new Vector3();
  21062. const tangents = [];
  21063. const normals = [];
  21064. const binormals = [];
  21065. const vec = new Vector3();
  21066. const mat = new Matrix4();
  21067. // compute the tangent vectors for each segment on the curve
  21068. for ( let i = 0; i <= segments; i ++ ) {
  21069. const u = i / segments;
  21070. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  21071. tangents[ i ].normalize();
  21072. }
  21073. // select an initial normal vector perpendicular to the first tangent vector,
  21074. // and in the direction of the minimum tangent xyz component
  21075. normals[ 0 ] = new Vector3();
  21076. binormals[ 0 ] = new Vector3();
  21077. let min = Number.MAX_VALUE;
  21078. const tx = Math.abs( tangents[ 0 ].x );
  21079. const ty = Math.abs( tangents[ 0 ].y );
  21080. const tz = Math.abs( tangents[ 0 ].z );
  21081. if ( tx <= min ) {
  21082. min = tx;
  21083. normal.set( 1, 0, 0 );
  21084. }
  21085. if ( ty <= min ) {
  21086. min = ty;
  21087. normal.set( 0, 1, 0 );
  21088. }
  21089. if ( tz <= min ) {
  21090. normal.set( 0, 0, 1 );
  21091. }
  21092. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  21093. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  21094. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  21095. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  21096. for ( let i = 1; i <= segments; i ++ ) {
  21097. normals[ i ] = normals[ i - 1 ].clone();
  21098. binormals[ i ] = binormals[ i - 1 ].clone();
  21099. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  21100. if ( vec.length() > Number.EPSILON ) {
  21101. vec.normalize();
  21102. const theta = Math.acos( MathUtils.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  21103. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  21104. }
  21105. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  21106. }
  21107. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  21108. if ( closed === true ) {
  21109. let theta = Math.acos( MathUtils.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  21110. theta /= segments;
  21111. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  21112. theta = - theta;
  21113. }
  21114. for ( let i = 1; i <= segments; i ++ ) {
  21115. // twist a little...
  21116. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  21117. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  21118. }
  21119. }
  21120. return {
  21121. tangents: tangents,
  21122. normals: normals,
  21123. binormals: binormals
  21124. };
  21125. },
  21126. clone: function () {
  21127. return new this.constructor().copy( this );
  21128. },
  21129. copy: function ( source ) {
  21130. this.arcLengthDivisions = source.arcLengthDivisions;
  21131. return this;
  21132. },
  21133. toJSON: function () {
  21134. const data = {
  21135. metadata: {
  21136. version: 4.5,
  21137. type: 'Curve',
  21138. generator: 'Curve.toJSON'
  21139. }
  21140. };
  21141. data.arcLengthDivisions = this.arcLengthDivisions;
  21142. data.type = this.type;
  21143. return data;
  21144. },
  21145. fromJSON: function ( json ) {
  21146. this.arcLengthDivisions = json.arcLengthDivisions;
  21147. return this;
  21148. }
  21149. } );
  21150. class EllipseCurve extends Curve {
  21151. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  21152. super();
  21153. this.type = 'EllipseCurve';
  21154. this.aX = aX;
  21155. this.aY = aY;
  21156. this.xRadius = xRadius;
  21157. this.yRadius = yRadius;
  21158. this.aStartAngle = aStartAngle;
  21159. this.aEndAngle = aEndAngle;
  21160. this.aClockwise = aClockwise;
  21161. this.aRotation = aRotation;
  21162. }
  21163. getPoint( t, optionalTarget ) {
  21164. const point = optionalTarget || new Vector2();
  21165. const twoPi = Math.PI * 2;
  21166. let deltaAngle = this.aEndAngle - this.aStartAngle;
  21167. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  21168. // ensures that deltaAngle is 0 .. 2 PI
  21169. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  21170. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  21171. if ( deltaAngle < Number.EPSILON ) {
  21172. if ( samePoints ) {
  21173. deltaAngle = 0;
  21174. } else {
  21175. deltaAngle = twoPi;
  21176. }
  21177. }
  21178. if ( this.aClockwise === true && ! samePoints ) {
  21179. if ( deltaAngle === twoPi ) {
  21180. deltaAngle = - twoPi;
  21181. } else {
  21182. deltaAngle = deltaAngle - twoPi;
  21183. }
  21184. }
  21185. const angle = this.aStartAngle + t * deltaAngle;
  21186. let x = this.aX + this.xRadius * Math.cos( angle );
  21187. let y = this.aY + this.yRadius * Math.sin( angle );
  21188. if ( this.aRotation !== 0 ) {
  21189. const cos = Math.cos( this.aRotation );
  21190. const sin = Math.sin( this.aRotation );
  21191. const tx = x - this.aX;
  21192. const ty = y - this.aY;
  21193. // Rotate the point about the center of the ellipse.
  21194. x = tx * cos - ty * sin + this.aX;
  21195. y = tx * sin + ty * cos + this.aY;
  21196. }
  21197. return point.set( x, y );
  21198. }
  21199. copy( source ) {
  21200. super.copy( source );
  21201. this.aX = source.aX;
  21202. this.aY = source.aY;
  21203. this.xRadius = source.xRadius;
  21204. this.yRadius = source.yRadius;
  21205. this.aStartAngle = source.aStartAngle;
  21206. this.aEndAngle = source.aEndAngle;
  21207. this.aClockwise = source.aClockwise;
  21208. this.aRotation = source.aRotation;
  21209. return this;
  21210. }
  21211. toJSON() {
  21212. const data = super.toJSON();
  21213. data.aX = this.aX;
  21214. data.aY = this.aY;
  21215. data.xRadius = this.xRadius;
  21216. data.yRadius = this.yRadius;
  21217. data.aStartAngle = this.aStartAngle;
  21218. data.aEndAngle = this.aEndAngle;
  21219. data.aClockwise = this.aClockwise;
  21220. data.aRotation = this.aRotation;
  21221. return data;
  21222. }
  21223. fromJSON( json ) {
  21224. super.fromJSON( json );
  21225. this.aX = json.aX;
  21226. this.aY = json.aY;
  21227. this.xRadius = json.xRadius;
  21228. this.yRadius = json.yRadius;
  21229. this.aStartAngle = json.aStartAngle;
  21230. this.aEndAngle = json.aEndAngle;
  21231. this.aClockwise = json.aClockwise;
  21232. this.aRotation = json.aRotation;
  21233. return this;
  21234. }
  21235. }
  21236. EllipseCurve.prototype.isEllipseCurve = true;
  21237. class ArcCurve extends EllipseCurve {
  21238. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  21239. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  21240. this.type = 'ArcCurve';
  21241. }
  21242. }
  21243. ArcCurve.prototype.isArcCurve = true;
  21244. /**
  21245. * Centripetal CatmullRom Curve - which is useful for avoiding
  21246. * cusps and self-intersections in non-uniform catmull rom curves.
  21247. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  21248. *
  21249. * curve.type accepts centripetal(default), chordal and catmullrom
  21250. * curve.tension is used for catmullrom which defaults to 0.5
  21251. */
  21252. /*
  21253. Based on an optimized c++ solution in
  21254. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  21255. - http://ideone.com/NoEbVM
  21256. This CubicPoly class could be used for reusing some variables and calculations,
  21257. but for three.js curve use, it could be possible inlined and flatten into a single function call
  21258. which can be placed in CurveUtils.
  21259. */
  21260. function CubicPoly() {
  21261. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  21262. /*
  21263. * Compute coefficients for a cubic polynomial
  21264. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  21265. * such that
  21266. * p(0) = x0, p(1) = x1
  21267. * and
  21268. * p'(0) = t0, p'(1) = t1.
  21269. */
  21270. function init( x0, x1, t0, t1 ) {
  21271. c0 = x0;
  21272. c1 = t0;
  21273. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  21274. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  21275. }
  21276. return {
  21277. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  21278. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  21279. },
  21280. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  21281. // compute tangents when parameterized in [t1,t2]
  21282. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  21283. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  21284. // rescale tangents for parametrization in [0,1]
  21285. t1 *= dt1;
  21286. t2 *= dt1;
  21287. init( x1, x2, t1, t2 );
  21288. },
  21289. calc: function ( t ) {
  21290. const t2 = t * t;
  21291. const t3 = t2 * t;
  21292. return c0 + c1 * t + c2 * t2 + c3 * t3;
  21293. }
  21294. };
  21295. }
  21296. //
  21297. const tmp = new Vector3();
  21298. const px = new CubicPoly(), py = new CubicPoly(), pz = new CubicPoly();
  21299. class CatmullRomCurve3 extends Curve {
  21300. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  21301. super();
  21302. this.type = 'CatmullRomCurve3';
  21303. this.points = points;
  21304. this.closed = closed;
  21305. this.curveType = curveType;
  21306. this.tension = tension;
  21307. }
  21308. getPoint( t, optionalTarget = new Vector3() ) {
  21309. const point = optionalTarget;
  21310. const points = this.points;
  21311. const l = points.length;
  21312. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  21313. let intPoint = Math.floor( p );
  21314. let weight = p - intPoint;
  21315. if ( this.closed ) {
  21316. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  21317. } else if ( weight === 0 && intPoint === l - 1 ) {
  21318. intPoint = l - 2;
  21319. weight = 1;
  21320. }
  21321. let p0, p3; // 4 points (p1 & p2 defined below)
  21322. if ( this.closed || intPoint > 0 ) {
  21323. p0 = points[ ( intPoint - 1 ) % l ];
  21324. } else {
  21325. // extrapolate first point
  21326. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  21327. p0 = tmp;
  21328. }
  21329. const p1 = points[ intPoint % l ];
  21330. const p2 = points[ ( intPoint + 1 ) % l ];
  21331. if ( this.closed || intPoint + 2 < l ) {
  21332. p3 = points[ ( intPoint + 2 ) % l ];
  21333. } else {
  21334. // extrapolate last point
  21335. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  21336. p3 = tmp;
  21337. }
  21338. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  21339. // init Centripetal / Chordal Catmull-Rom
  21340. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  21341. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  21342. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  21343. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  21344. // safety check for repeated points
  21345. if ( dt1 < 1e-4 ) dt1 = 1.0;
  21346. if ( dt0 < 1e-4 ) dt0 = dt1;
  21347. if ( dt2 < 1e-4 ) dt2 = dt1;
  21348. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  21349. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  21350. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  21351. } else if ( this.curveType === 'catmullrom' ) {
  21352. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  21353. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  21354. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  21355. }
  21356. point.set(
  21357. px.calc( weight ),
  21358. py.calc( weight ),
  21359. pz.calc( weight )
  21360. );
  21361. return point;
  21362. }
  21363. copy( source ) {
  21364. super.copy( source );
  21365. this.points = [];
  21366. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  21367. const point = source.points[ i ];
  21368. this.points.push( point.clone() );
  21369. }
  21370. this.closed = source.closed;
  21371. this.curveType = source.curveType;
  21372. this.tension = source.tension;
  21373. return this;
  21374. }
  21375. toJSON() {
  21376. const data = super.toJSON();
  21377. data.points = [];
  21378. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  21379. const point = this.points[ i ];
  21380. data.points.push( point.toArray() );
  21381. }
  21382. data.closed = this.closed;
  21383. data.curveType = this.curveType;
  21384. data.tension = this.tension;
  21385. return data;
  21386. }
  21387. fromJSON( json ) {
  21388. super.fromJSON( json );
  21389. this.points = [];
  21390. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  21391. const point = json.points[ i ];
  21392. this.points.push( new Vector3().fromArray( point ) );
  21393. }
  21394. this.closed = json.closed;
  21395. this.curveType = json.curveType;
  21396. this.tension = json.tension;
  21397. return this;
  21398. }
  21399. }
  21400. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  21401. /**
  21402. * Bezier Curves formulas obtained from
  21403. * http://en.wikipedia.org/wiki/Bézier_curve
  21404. */
  21405. function CatmullRom( t, p0, p1, p2, p3 ) {
  21406. const v0 = ( p2 - p0 ) * 0.5;
  21407. const v1 = ( p3 - p1 ) * 0.5;
  21408. const t2 = t * t;
  21409. const t3 = t * t2;
  21410. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  21411. }
  21412. //
  21413. function QuadraticBezierP0( t, p ) {
  21414. const k = 1 - t;
  21415. return k * k * p;
  21416. }
  21417. function QuadraticBezierP1( t, p ) {
  21418. return 2 * ( 1 - t ) * t * p;
  21419. }
  21420. function QuadraticBezierP2( t, p ) {
  21421. return t * t * p;
  21422. }
  21423. function QuadraticBezier( t, p0, p1, p2 ) {
  21424. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  21425. QuadraticBezierP2( t, p2 );
  21426. }
  21427. //
  21428. function CubicBezierP0( t, p ) {
  21429. const k = 1 - t;
  21430. return k * k * k * p;
  21431. }
  21432. function CubicBezierP1( t, p ) {
  21433. const k = 1 - t;
  21434. return 3 * k * k * t * p;
  21435. }
  21436. function CubicBezierP2( t, p ) {
  21437. return 3 * ( 1 - t ) * t * t * p;
  21438. }
  21439. function CubicBezierP3( t, p ) {
  21440. return t * t * t * p;
  21441. }
  21442. function CubicBezier( t, p0, p1, p2, p3 ) {
  21443. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  21444. CubicBezierP3( t, p3 );
  21445. }
  21446. class CubicBezierCurve extends Curve {
  21447. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  21448. super();
  21449. this.type = 'CubicBezierCurve';
  21450. this.v0 = v0;
  21451. this.v1 = v1;
  21452. this.v2 = v2;
  21453. this.v3 = v3;
  21454. }
  21455. getPoint( t, optionalTarget = new Vector2() ) {
  21456. const point = optionalTarget;
  21457. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  21458. point.set(
  21459. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  21460. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  21461. );
  21462. return point;
  21463. }
  21464. copy( source ) {
  21465. super.copy( source );
  21466. this.v0.copy( source.v0 );
  21467. this.v1.copy( source.v1 );
  21468. this.v2.copy( source.v2 );
  21469. this.v3.copy( source.v3 );
  21470. return this;
  21471. }
  21472. toJSON() {
  21473. const data = super.toJSON();
  21474. data.v0 = this.v0.toArray();
  21475. data.v1 = this.v1.toArray();
  21476. data.v2 = this.v2.toArray();
  21477. data.v3 = this.v3.toArray();
  21478. return data;
  21479. }
  21480. fromJSON( json ) {
  21481. super.fromJSON( json );
  21482. this.v0.fromArray( json.v0 );
  21483. this.v1.fromArray( json.v1 );
  21484. this.v2.fromArray( json.v2 );
  21485. this.v3.fromArray( json.v3 );
  21486. return this;
  21487. }
  21488. }
  21489. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  21490. class CubicBezierCurve3 extends Curve {
  21491. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  21492. super();
  21493. this.type = 'CubicBezierCurve3';
  21494. this.v0 = v0;
  21495. this.v1 = v1;
  21496. this.v2 = v2;
  21497. this.v3 = v3;
  21498. }
  21499. getPoint( t, optionalTarget = new Vector3() ) {
  21500. const point = optionalTarget;
  21501. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  21502. point.set(
  21503. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  21504. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  21505. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  21506. );
  21507. return point;
  21508. }
  21509. copy( source ) {
  21510. super.copy( source );
  21511. this.v0.copy( source.v0 );
  21512. this.v1.copy( source.v1 );
  21513. this.v2.copy( source.v2 );
  21514. this.v3.copy( source.v3 );
  21515. return this;
  21516. }
  21517. toJSON() {
  21518. const data = super.toJSON();
  21519. data.v0 = this.v0.toArray();
  21520. data.v1 = this.v1.toArray();
  21521. data.v2 = this.v2.toArray();
  21522. data.v3 = this.v3.toArray();
  21523. return data;
  21524. }
  21525. fromJSON( json ) {
  21526. super.fromJSON( json );
  21527. this.v0.fromArray( json.v0 );
  21528. this.v1.fromArray( json.v1 );
  21529. this.v2.fromArray( json.v2 );
  21530. this.v3.fromArray( json.v3 );
  21531. return this;
  21532. }
  21533. }
  21534. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  21535. class LineCurve extends Curve {
  21536. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  21537. super();
  21538. this.type = 'LineCurve';
  21539. this.v1 = v1;
  21540. this.v2 = v2;
  21541. }
  21542. getPoint( t, optionalTarget = new Vector2() ) {
  21543. const point = optionalTarget;
  21544. if ( t === 1 ) {
  21545. point.copy( this.v2 );
  21546. } else {
  21547. point.copy( this.v2 ).sub( this.v1 );
  21548. point.multiplyScalar( t ).add( this.v1 );
  21549. }
  21550. return point;
  21551. }
  21552. // Line curve is linear, so we can overwrite default getPointAt
  21553. getPointAt( u, optionalTarget ) {
  21554. return this.getPoint( u, optionalTarget );
  21555. }
  21556. getTangent( t, optionalTarget ) {
  21557. const tangent = optionalTarget || new Vector2();
  21558. tangent.copy( this.v2 ).sub( this.v1 ).normalize();
  21559. return tangent;
  21560. }
  21561. copy( source ) {
  21562. super.copy( source );
  21563. this.v1.copy( source.v1 );
  21564. this.v2.copy( source.v2 );
  21565. return this;
  21566. }
  21567. toJSON() {
  21568. const data = super.toJSON();
  21569. data.v1 = this.v1.toArray();
  21570. data.v2 = this.v2.toArray();
  21571. return data;
  21572. }
  21573. fromJSON( json ) {
  21574. super.fromJSON( json );
  21575. this.v1.fromArray( json.v1 );
  21576. this.v2.fromArray( json.v2 );
  21577. return this;
  21578. }
  21579. }
  21580. LineCurve.prototype.isLineCurve = true;
  21581. class LineCurve3 extends Curve {
  21582. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  21583. super();
  21584. this.type = 'LineCurve3';
  21585. this.isLineCurve3 = true;
  21586. this.v1 = v1;
  21587. this.v2 = v2;
  21588. }
  21589. getPoint( t, optionalTarget = new Vector3() ) {
  21590. const point = optionalTarget;
  21591. if ( t === 1 ) {
  21592. point.copy( this.v2 );
  21593. } else {
  21594. point.copy( this.v2 ).sub( this.v1 );
  21595. point.multiplyScalar( t ).add( this.v1 );
  21596. }
  21597. return point;
  21598. }
  21599. // Line curve is linear, so we can overwrite default getPointAt
  21600. getPointAt( u, optionalTarget ) {
  21601. return this.getPoint( u, optionalTarget );
  21602. }
  21603. copy( source ) {
  21604. super.copy( source );
  21605. this.v1.copy( source.v1 );
  21606. this.v2.copy( source.v2 );
  21607. return this;
  21608. }
  21609. toJSON() {
  21610. const data = super.toJSON();
  21611. data.v1 = this.v1.toArray();
  21612. data.v2 = this.v2.toArray();
  21613. return data;
  21614. }
  21615. fromJSON( json ) {
  21616. super.fromJSON( json );
  21617. this.v1.fromArray( json.v1 );
  21618. this.v2.fromArray( json.v2 );
  21619. return this;
  21620. }
  21621. }
  21622. class QuadraticBezierCurve extends Curve {
  21623. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  21624. super();
  21625. this.type = 'QuadraticBezierCurve';
  21626. this.v0 = v0;
  21627. this.v1 = v1;
  21628. this.v2 = v2;
  21629. }
  21630. getPoint( t, optionalTarget = new Vector2() ) {
  21631. const point = optionalTarget;
  21632. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  21633. point.set(
  21634. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  21635. QuadraticBezier( t, v0.y, v1.y, v2.y )
  21636. );
  21637. return point;
  21638. }
  21639. copy( source ) {
  21640. super.copy( source );
  21641. this.v0.copy( source.v0 );
  21642. this.v1.copy( source.v1 );
  21643. this.v2.copy( source.v2 );
  21644. return this;
  21645. }
  21646. toJSON() {
  21647. const data = super.toJSON();
  21648. data.v0 = this.v0.toArray();
  21649. data.v1 = this.v1.toArray();
  21650. data.v2 = this.v2.toArray();
  21651. return data;
  21652. }
  21653. fromJSON( json ) {
  21654. super.fromJSON( json );
  21655. this.v0.fromArray( json.v0 );
  21656. this.v1.fromArray( json.v1 );
  21657. this.v2.fromArray( json.v2 );
  21658. return this;
  21659. }
  21660. }
  21661. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  21662. class QuadraticBezierCurve3 extends Curve {
  21663. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  21664. super();
  21665. this.type = 'QuadraticBezierCurve3';
  21666. this.v0 = v0;
  21667. this.v1 = v1;
  21668. this.v2 = v2;
  21669. }
  21670. getPoint( t, optionalTarget = new Vector3() ) {
  21671. const point = optionalTarget;
  21672. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  21673. point.set(
  21674. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  21675. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  21676. QuadraticBezier( t, v0.z, v1.z, v2.z )
  21677. );
  21678. return point;
  21679. }
  21680. copy( source ) {
  21681. super.copy( source );
  21682. this.v0.copy( source.v0 );
  21683. this.v1.copy( source.v1 );
  21684. this.v2.copy( source.v2 );
  21685. return this;
  21686. }
  21687. toJSON() {
  21688. const data = super.toJSON();
  21689. data.v0 = this.v0.toArray();
  21690. data.v1 = this.v1.toArray();
  21691. data.v2 = this.v2.toArray();
  21692. return data;
  21693. }
  21694. fromJSON( json ) {
  21695. super.fromJSON( json );
  21696. this.v0.fromArray( json.v0 );
  21697. this.v1.fromArray( json.v1 );
  21698. this.v2.fromArray( json.v2 );
  21699. return this;
  21700. }
  21701. }
  21702. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  21703. class SplineCurve extends Curve {
  21704. constructor( points = [] ) {
  21705. super();
  21706. this.type = 'SplineCurve';
  21707. this.points = points;
  21708. }
  21709. getPoint( t, optionalTarget = new Vector2() ) {
  21710. const point = optionalTarget;
  21711. const points = this.points;
  21712. const p = ( points.length - 1 ) * t;
  21713. const intPoint = Math.floor( p );
  21714. const weight = p - intPoint;
  21715. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  21716. const p1 = points[ intPoint ];
  21717. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  21718. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  21719. point.set(
  21720. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  21721. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  21722. );
  21723. return point;
  21724. }
  21725. copy( source ) {
  21726. super.copy( source );
  21727. this.points = [];
  21728. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  21729. const point = source.points[ i ];
  21730. this.points.push( point.clone() );
  21731. }
  21732. return this;
  21733. }
  21734. toJSON() {
  21735. const data = super.toJSON();
  21736. data.points = [];
  21737. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  21738. const point = this.points[ i ];
  21739. data.points.push( point.toArray() );
  21740. }
  21741. return data;
  21742. }
  21743. fromJSON( json ) {
  21744. super.fromJSON( json );
  21745. this.points = [];
  21746. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  21747. const point = json.points[ i ];
  21748. this.points.push( new Vector2().fromArray( point ) );
  21749. }
  21750. return this;
  21751. }
  21752. }
  21753. SplineCurve.prototype.isSplineCurve = true;
  21754. var Curves = /*#__PURE__*/Object.freeze({
  21755. __proto__: null,
  21756. ArcCurve: ArcCurve,
  21757. CatmullRomCurve3: CatmullRomCurve3,
  21758. CubicBezierCurve: CubicBezierCurve,
  21759. CubicBezierCurve3: CubicBezierCurve3,
  21760. EllipseCurve: EllipseCurve,
  21761. LineCurve: LineCurve,
  21762. LineCurve3: LineCurve3,
  21763. QuadraticBezierCurve: QuadraticBezierCurve,
  21764. QuadraticBezierCurve3: QuadraticBezierCurve3,
  21765. SplineCurve: SplineCurve
  21766. });
  21767. /**************************************************************
  21768. * Curved Path - a curve path is simply a array of connected
  21769. * curves, but retains the api of a curve
  21770. **************************************************************/
  21771. class CurvePath extends Curve {
  21772. constructor() {
  21773. super();
  21774. this.type = 'CurvePath';
  21775. this.curves = [];
  21776. this.autoClose = false; // Automatically closes the path
  21777. }
  21778. add( curve ) {
  21779. this.curves.push( curve );
  21780. }
  21781. closePath() {
  21782. // Add a line curve if start and end of lines are not connected
  21783. const startPoint = this.curves[ 0 ].getPoint( 0 );
  21784. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  21785. if ( ! startPoint.equals( endPoint ) ) {
  21786. this.curves.push( new LineCurve( endPoint, startPoint ) );
  21787. }
  21788. }
  21789. // To get accurate point with reference to
  21790. // entire path distance at time t,
  21791. // following has to be done:
  21792. // 1. Length of each sub path have to be known
  21793. // 2. Locate and identify type of curve
  21794. // 3. Get t for the curve
  21795. // 4. Return curve.getPointAt(t')
  21796. getPoint( t ) {
  21797. const d = t * this.getLength();
  21798. const curveLengths = this.getCurveLengths();
  21799. let i = 0;
  21800. // To think about boundaries points.
  21801. while ( i < curveLengths.length ) {
  21802. if ( curveLengths[ i ] >= d ) {
  21803. const diff = curveLengths[ i ] - d;
  21804. const curve = this.curves[ i ];
  21805. const segmentLength = curve.getLength();
  21806. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  21807. return curve.getPointAt( u );
  21808. }
  21809. i ++;
  21810. }
  21811. return null;
  21812. // loop where sum != 0, sum > d , sum+1 <d
  21813. }
  21814. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  21815. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  21816. // getPoint() depends on getLength
  21817. getLength() {
  21818. const lens = this.getCurveLengths();
  21819. return lens[ lens.length - 1 ];
  21820. }
  21821. // cacheLengths must be recalculated.
  21822. updateArcLengths() {
  21823. this.needsUpdate = true;
  21824. this.cacheLengths = null;
  21825. this.getCurveLengths();
  21826. }
  21827. // Compute lengths and cache them
  21828. // We cannot overwrite getLengths() because UtoT mapping uses it.
  21829. getCurveLengths() {
  21830. // We use cache values if curves and cache array are same length
  21831. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  21832. return this.cacheLengths;
  21833. }
  21834. // Get length of sub-curve
  21835. // Push sums into cached array
  21836. const lengths = [];
  21837. let sums = 0;
  21838. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  21839. sums += this.curves[ i ].getLength();
  21840. lengths.push( sums );
  21841. }
  21842. this.cacheLengths = lengths;
  21843. return lengths;
  21844. }
  21845. getSpacedPoints( divisions = 40 ) {
  21846. const points = [];
  21847. for ( let i = 0; i <= divisions; i ++ ) {
  21848. points.push( this.getPoint( i / divisions ) );
  21849. }
  21850. if ( this.autoClose ) {
  21851. points.push( points[ 0 ] );
  21852. }
  21853. return points;
  21854. }
  21855. getPoints( divisions = 12 ) {
  21856. const points = [];
  21857. let last;
  21858. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  21859. const curve = curves[ i ];
  21860. const resolution = ( curve && curve.isEllipseCurve ) ? divisions * 2
  21861. : ( curve && ( curve.isLineCurve || curve.isLineCurve3 ) ) ? 1
  21862. : ( curve && curve.isSplineCurve ) ? divisions * curve.points.length
  21863. : divisions;
  21864. const pts = curve.getPoints( resolution );
  21865. for ( let j = 0; j < pts.length; j ++ ) {
  21866. const point = pts[ j ];
  21867. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  21868. points.push( point );
  21869. last = point;
  21870. }
  21871. }
  21872. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  21873. points.push( points[ 0 ] );
  21874. }
  21875. return points;
  21876. }
  21877. copy( source ) {
  21878. super.copy( source );
  21879. this.curves = [];
  21880. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  21881. const curve = source.curves[ i ];
  21882. this.curves.push( curve.clone() );
  21883. }
  21884. this.autoClose = source.autoClose;
  21885. return this;
  21886. }
  21887. toJSON() {
  21888. const data = super.toJSON();
  21889. data.autoClose = this.autoClose;
  21890. data.curves = [];
  21891. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  21892. const curve = this.curves[ i ];
  21893. data.curves.push( curve.toJSON() );
  21894. }
  21895. return data;
  21896. }
  21897. fromJSON( json ) {
  21898. super.fromJSON( json );
  21899. this.autoClose = json.autoClose;
  21900. this.curves = [];
  21901. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  21902. const curve = json.curves[ i ];
  21903. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  21904. }
  21905. return this;
  21906. }
  21907. }
  21908. class Path extends CurvePath {
  21909. constructor( points ) {
  21910. super();
  21911. this.type = 'Path';
  21912. this.currentPoint = new Vector2();
  21913. if ( points ) {
  21914. this.setFromPoints( points );
  21915. }
  21916. }
  21917. setFromPoints( points ) {
  21918. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  21919. for ( let i = 1, l = points.length; i < l; i ++ ) {
  21920. this.lineTo( points[ i ].x, points[ i ].y );
  21921. }
  21922. return this;
  21923. }
  21924. moveTo( x, y ) {
  21925. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  21926. return this;
  21927. }
  21928. lineTo( x, y ) {
  21929. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  21930. this.curves.push( curve );
  21931. this.currentPoint.set( x, y );
  21932. return this;
  21933. }
  21934. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  21935. const curve = new QuadraticBezierCurve(
  21936. this.currentPoint.clone(),
  21937. new Vector2( aCPx, aCPy ),
  21938. new Vector2( aX, aY )
  21939. );
  21940. this.curves.push( curve );
  21941. this.currentPoint.set( aX, aY );
  21942. return this;
  21943. }
  21944. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  21945. const curve = new CubicBezierCurve(
  21946. this.currentPoint.clone(),
  21947. new Vector2( aCP1x, aCP1y ),
  21948. new Vector2( aCP2x, aCP2y ),
  21949. new Vector2( aX, aY )
  21950. );
  21951. this.curves.push( curve );
  21952. this.currentPoint.set( aX, aY );
  21953. return this;
  21954. }
  21955. splineThru( pts /*Array of Vector*/ ) {
  21956. const npts = [ this.currentPoint.clone() ].concat( pts );
  21957. const curve = new SplineCurve( npts );
  21958. this.curves.push( curve );
  21959. this.currentPoint.copy( pts[ pts.length - 1 ] );
  21960. return this;
  21961. }
  21962. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  21963. const x0 = this.currentPoint.x;
  21964. const y0 = this.currentPoint.y;
  21965. this.absarc( aX + x0, aY + y0, aRadius,
  21966. aStartAngle, aEndAngle, aClockwise );
  21967. return this;
  21968. }
  21969. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  21970. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  21971. return this;
  21972. }
  21973. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  21974. const x0 = this.currentPoint.x;
  21975. const y0 = this.currentPoint.y;
  21976. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  21977. return this;
  21978. }
  21979. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  21980. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  21981. if ( this.curves.length > 0 ) {
  21982. // if a previous curve is present, attempt to join
  21983. const firstPoint = curve.getPoint( 0 );
  21984. if ( ! firstPoint.equals( this.currentPoint ) ) {
  21985. this.lineTo( firstPoint.x, firstPoint.y );
  21986. }
  21987. }
  21988. this.curves.push( curve );
  21989. const lastPoint = curve.getPoint( 1 );
  21990. this.currentPoint.copy( lastPoint );
  21991. return this;
  21992. }
  21993. copy( source ) {
  21994. super.copy( source );
  21995. this.currentPoint.copy( source.currentPoint );
  21996. return this;
  21997. }
  21998. toJSON() {
  21999. const data = super.toJSON();
  22000. data.currentPoint = this.currentPoint.toArray();
  22001. return data;
  22002. }
  22003. fromJSON( json ) {
  22004. super.fromJSON( json );
  22005. this.currentPoint.fromArray( json.currentPoint );
  22006. return this;
  22007. }
  22008. }
  22009. class Shape extends Path {
  22010. constructor( points ) {
  22011. super( points );
  22012. this.uuid = MathUtils.generateUUID();
  22013. this.type = 'Shape';
  22014. this.holes = [];
  22015. }
  22016. getPointsHoles( divisions ) {
  22017. const holesPts = [];
  22018. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  22019. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  22020. }
  22021. return holesPts;
  22022. }
  22023. // get points of shape and holes (keypoints based on segments parameter)
  22024. extractPoints( divisions ) {
  22025. return {
  22026. shape: this.getPoints( divisions ),
  22027. holes: this.getPointsHoles( divisions )
  22028. };
  22029. }
  22030. copy( source ) {
  22031. super.copy( source );
  22032. this.holes = [];
  22033. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  22034. const hole = source.holes[ i ];
  22035. this.holes.push( hole.clone() );
  22036. }
  22037. return this;
  22038. }
  22039. toJSON() {
  22040. const data = super.toJSON();
  22041. data.uuid = this.uuid;
  22042. data.holes = [];
  22043. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  22044. const hole = this.holes[ i ];
  22045. data.holes.push( hole.toJSON() );
  22046. }
  22047. return data;
  22048. }
  22049. fromJSON( json ) {
  22050. super.fromJSON( json );
  22051. this.uuid = json.uuid;
  22052. this.holes = [];
  22053. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  22054. const hole = json.holes[ i ];
  22055. this.holes.push( new Path().fromJSON( hole ) );
  22056. }
  22057. return this;
  22058. }
  22059. }
  22060. class Light extends Object3D {
  22061. constructor( color, intensity = 1 ) {
  22062. super();
  22063. this.type = 'Light';
  22064. this.color = new Color( color );
  22065. this.intensity = intensity;
  22066. }
  22067. copy( source ) {
  22068. super.copy( source );
  22069. this.color.copy( source.color );
  22070. this.intensity = source.intensity;
  22071. return this;
  22072. }
  22073. toJSON( meta ) {
  22074. const data = super.toJSON( meta );
  22075. data.object.color = this.color.getHex();
  22076. data.object.intensity = this.intensity;
  22077. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  22078. if ( this.distance !== undefined ) data.object.distance = this.distance;
  22079. if ( this.angle !== undefined ) data.object.angle = this.angle;
  22080. if ( this.decay !== undefined ) data.object.decay = this.decay;
  22081. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  22082. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  22083. return data;
  22084. }
  22085. }
  22086. Light.prototype.isLight = true;
  22087. class HemisphereLight extends Light {
  22088. constructor( skyColor, groundColor, intensity ) {
  22089. super( skyColor, intensity );
  22090. this.type = 'HemisphereLight';
  22091. this.position.copy( Object3D.DefaultUp );
  22092. this.updateMatrix();
  22093. this.groundColor = new Color( groundColor );
  22094. }
  22095. copy( source ) {
  22096. Light.prototype.copy.call( this, source );
  22097. this.groundColor.copy( source.groundColor );
  22098. return this;
  22099. }
  22100. }
  22101. HemisphereLight.prototype.isHemisphereLight = true;
  22102. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  22103. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  22104. const _lookTarget = /*@__PURE__*/ new Vector3();
  22105. class LightShadow {
  22106. constructor( camera ) {
  22107. this.camera = camera;
  22108. this.bias = 0;
  22109. this.normalBias = 0;
  22110. this.radius = 1;
  22111. this.mapSize = new Vector2( 512, 512 );
  22112. this.map = null;
  22113. this.mapPass = null;
  22114. this.matrix = new Matrix4();
  22115. this.autoUpdate = true;
  22116. this.needsUpdate = false;
  22117. this._frustum = new Frustum();
  22118. this._frameExtents = new Vector2( 1, 1 );
  22119. this._viewportCount = 1;
  22120. this._viewports = [
  22121. new Vector4( 0, 0, 1, 1 )
  22122. ];
  22123. }
  22124. getViewportCount() {
  22125. return this._viewportCount;
  22126. }
  22127. getFrustum() {
  22128. return this._frustum;
  22129. }
  22130. updateMatrices( light ) {
  22131. const shadowCamera = this.camera;
  22132. const shadowMatrix = this.matrix;
  22133. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  22134. shadowCamera.position.copy( _lightPositionWorld );
  22135. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  22136. shadowCamera.lookAt( _lookTarget );
  22137. shadowCamera.updateMatrixWorld();
  22138. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  22139. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  22140. shadowMatrix.set(
  22141. 0.5, 0.0, 0.0, 0.5,
  22142. 0.0, 0.5, 0.0, 0.5,
  22143. 0.0, 0.0, 0.5, 0.5,
  22144. 0.0, 0.0, 0.0, 1.0
  22145. );
  22146. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  22147. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  22148. }
  22149. getViewport( viewportIndex ) {
  22150. return this._viewports[ viewportIndex ];
  22151. }
  22152. getFrameExtents() {
  22153. return this._frameExtents;
  22154. }
  22155. copy( source ) {
  22156. this.camera = source.camera.clone();
  22157. this.bias = source.bias;
  22158. this.radius = source.radius;
  22159. this.mapSize.copy( source.mapSize );
  22160. return this;
  22161. }
  22162. clone() {
  22163. return new this.constructor().copy( this );
  22164. }
  22165. toJSON() {
  22166. const object = {};
  22167. if ( this.bias !== 0 ) object.bias = this.bias;
  22168. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  22169. if ( this.radius !== 1 ) object.radius = this.radius;
  22170. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  22171. object.camera = this.camera.toJSON( false ).object;
  22172. delete object.camera.matrix;
  22173. return object;
  22174. }
  22175. }
  22176. class SpotLightShadow extends LightShadow {
  22177. constructor() {
  22178. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  22179. this.focus = 1;
  22180. }
  22181. updateMatrices( light ) {
  22182. const camera = this.camera;
  22183. const fov = MathUtils.RAD2DEG * 2 * light.angle * this.focus;
  22184. const aspect = this.mapSize.width / this.mapSize.height;
  22185. const far = light.distance || camera.far;
  22186. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  22187. camera.fov = fov;
  22188. camera.aspect = aspect;
  22189. camera.far = far;
  22190. camera.updateProjectionMatrix();
  22191. }
  22192. super.updateMatrices( light );
  22193. }
  22194. }
  22195. SpotLightShadow.prototype.isSpotLightShadow = true;
  22196. class SpotLight extends Light {
  22197. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 1 ) {
  22198. super( color, intensity );
  22199. this.type = 'SpotLight';
  22200. this.position.copy( Object3D.DefaultUp );
  22201. this.updateMatrix();
  22202. this.target = new Object3D();
  22203. this.distance = distance;
  22204. this.angle = angle;
  22205. this.penumbra = penumbra;
  22206. this.decay = decay; // for physically correct lights, should be 2.
  22207. this.shadow = new SpotLightShadow();
  22208. }
  22209. get power() {
  22210. // intensity = power per solid angle.
  22211. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  22212. return this.intensity * Math.PI;
  22213. }
  22214. set power( power ) {
  22215. // intensity = power per solid angle.
  22216. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  22217. this.intensity = power / Math.PI;
  22218. }
  22219. copy( source ) {
  22220. super.copy( source );
  22221. this.distance = source.distance;
  22222. this.angle = source.angle;
  22223. this.penumbra = source.penumbra;
  22224. this.decay = source.decay;
  22225. this.target = source.target.clone();
  22226. this.shadow = source.shadow.clone();
  22227. return this;
  22228. }
  22229. }
  22230. SpotLight.prototype.isSpotLight = true;
  22231. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  22232. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  22233. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  22234. class PointLightShadow extends LightShadow {
  22235. constructor() {
  22236. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  22237. this._frameExtents = new Vector2( 4, 2 );
  22238. this._viewportCount = 6;
  22239. this._viewports = [
  22240. // These viewports map a cube-map onto a 2D texture with the
  22241. // following orientation:
  22242. //
  22243. // xzXZ
  22244. // y Y
  22245. //
  22246. // X - Positive x direction
  22247. // x - Negative x direction
  22248. // Y - Positive y direction
  22249. // y - Negative y direction
  22250. // Z - Positive z direction
  22251. // z - Negative z direction
  22252. // positive X
  22253. new Vector4( 2, 1, 1, 1 ),
  22254. // negative X
  22255. new Vector4( 0, 1, 1, 1 ),
  22256. // positive Z
  22257. new Vector4( 3, 1, 1, 1 ),
  22258. // negative Z
  22259. new Vector4( 1, 1, 1, 1 ),
  22260. // positive Y
  22261. new Vector4( 3, 0, 1, 1 ),
  22262. // negative Y
  22263. new Vector4( 1, 0, 1, 1 )
  22264. ];
  22265. this._cubeDirections = [
  22266. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  22267. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  22268. ];
  22269. this._cubeUps = [
  22270. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  22271. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  22272. ];
  22273. }
  22274. updateMatrices( light, viewportIndex = 0 ) {
  22275. const camera = this.camera;
  22276. const shadowMatrix = this.matrix;
  22277. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  22278. camera.position.copy( _lightPositionWorld$1 );
  22279. _lookTarget$1.copy( camera.position );
  22280. _lookTarget$1.add( this._cubeDirections[ viewportIndex ] );
  22281. camera.up.copy( this._cubeUps[ viewportIndex ] );
  22282. camera.lookAt( _lookTarget$1 );
  22283. camera.updateMatrixWorld();
  22284. shadowMatrix.makeTranslation( - _lightPositionWorld$1.x, - _lightPositionWorld$1.y, - _lightPositionWorld$1.z );
  22285. _projScreenMatrix$1.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  22286. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  22287. }
  22288. }
  22289. PointLightShadow.prototype.isPointLightShadow = true;
  22290. class PointLight extends Light {
  22291. constructor( color, intensity, distance = 0, decay = 1 ) {
  22292. super( color, intensity );
  22293. this.type = 'PointLight';
  22294. this.distance = distance;
  22295. this.decay = decay; // for physically correct lights, should be 2.
  22296. this.shadow = new PointLightShadow();
  22297. }
  22298. get power() {
  22299. // intensity = power per solid angle.
  22300. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  22301. return this.intensity * 4 * Math.PI;
  22302. }
  22303. set power( power ) {
  22304. // intensity = power per solid angle.
  22305. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  22306. this.intensity = power / ( 4 * Math.PI );
  22307. }
  22308. copy( source ) {
  22309. super.copy( source );
  22310. this.distance = source.distance;
  22311. this.decay = source.decay;
  22312. this.shadow = source.shadow.clone();
  22313. return this;
  22314. }
  22315. }
  22316. PointLight.prototype.isPointLight = true;
  22317. class OrthographicCamera extends Camera {
  22318. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  22319. super();
  22320. this.type = 'OrthographicCamera';
  22321. this.zoom = 1;
  22322. this.view = null;
  22323. this.left = left;
  22324. this.right = right;
  22325. this.top = top;
  22326. this.bottom = bottom;
  22327. this.near = near;
  22328. this.far = far;
  22329. this.updateProjectionMatrix();
  22330. }
  22331. copy( source, recursive ) {
  22332. super.copy( source, recursive );
  22333. this.left = source.left;
  22334. this.right = source.right;
  22335. this.top = source.top;
  22336. this.bottom = source.bottom;
  22337. this.near = source.near;
  22338. this.far = source.far;
  22339. this.zoom = source.zoom;
  22340. this.view = source.view === null ? null : Object.assign( {}, source.view );
  22341. return this;
  22342. }
  22343. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  22344. if ( this.view === null ) {
  22345. this.view = {
  22346. enabled: true,
  22347. fullWidth: 1,
  22348. fullHeight: 1,
  22349. offsetX: 0,
  22350. offsetY: 0,
  22351. width: 1,
  22352. height: 1
  22353. };
  22354. }
  22355. this.view.enabled = true;
  22356. this.view.fullWidth = fullWidth;
  22357. this.view.fullHeight = fullHeight;
  22358. this.view.offsetX = x;
  22359. this.view.offsetY = y;
  22360. this.view.width = width;
  22361. this.view.height = height;
  22362. this.updateProjectionMatrix();
  22363. }
  22364. clearViewOffset() {
  22365. if ( this.view !== null ) {
  22366. this.view.enabled = false;
  22367. }
  22368. this.updateProjectionMatrix();
  22369. }
  22370. updateProjectionMatrix() {
  22371. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  22372. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  22373. const cx = ( this.right + this.left ) / 2;
  22374. const cy = ( this.top + this.bottom ) / 2;
  22375. let left = cx - dx;
  22376. let right = cx + dx;
  22377. let top = cy + dy;
  22378. let bottom = cy - dy;
  22379. if ( this.view !== null && this.view.enabled ) {
  22380. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  22381. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  22382. left += scaleW * this.view.offsetX;
  22383. right = left + scaleW * this.view.width;
  22384. top -= scaleH * this.view.offsetY;
  22385. bottom = top - scaleH * this.view.height;
  22386. }
  22387. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  22388. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  22389. }
  22390. toJSON( meta ) {
  22391. const data = Object3D.prototype.toJSON.call( this, meta );
  22392. data.object.zoom = this.zoom;
  22393. data.object.left = this.left;
  22394. data.object.right = this.right;
  22395. data.object.top = this.top;
  22396. data.object.bottom = this.bottom;
  22397. data.object.near = this.near;
  22398. data.object.far = this.far;
  22399. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  22400. return data;
  22401. }
  22402. }
  22403. OrthographicCamera.prototype.isOrthographicCamera = true;
  22404. class DirectionalLightShadow extends LightShadow {
  22405. constructor() {
  22406. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  22407. }
  22408. }
  22409. DirectionalLightShadow.prototype.isDirectionalLightShadow = true;
  22410. class DirectionalLight extends Light {
  22411. constructor( color, intensity ) {
  22412. super( color, intensity );
  22413. this.type = 'DirectionalLight';
  22414. this.position.copy( Object3D.DefaultUp );
  22415. this.updateMatrix();
  22416. this.target = new Object3D();
  22417. this.shadow = new DirectionalLightShadow();
  22418. }
  22419. copy( source ) {
  22420. super.copy( source );
  22421. this.target = source.target.clone();
  22422. this.shadow = source.shadow.clone();
  22423. return this;
  22424. }
  22425. }
  22426. DirectionalLight.prototype.isDirectionalLight = true;
  22427. class AmbientLight extends Light {
  22428. constructor( color, intensity ) {
  22429. super( color, intensity );
  22430. this.type = 'AmbientLight';
  22431. }
  22432. }
  22433. AmbientLight.prototype.isAmbientLight = true;
  22434. class RectAreaLight extends Light {
  22435. constructor( color, intensity, width = 10, height = 10 ) {
  22436. super( color, intensity );
  22437. this.type = 'RectAreaLight';
  22438. this.width = width;
  22439. this.height = height;
  22440. }
  22441. copy( source ) {
  22442. super.copy( source );
  22443. this.width = source.width;
  22444. this.height = source.height;
  22445. return this;
  22446. }
  22447. toJSON( meta ) {
  22448. const data = super.toJSON( meta );
  22449. data.object.width = this.width;
  22450. data.object.height = this.height;
  22451. return data;
  22452. }
  22453. }
  22454. RectAreaLight.prototype.isRectAreaLight = true;
  22455. /**
  22456. * Primary reference:
  22457. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  22458. *
  22459. * Secondary reference:
  22460. * https://www.ppsloan.org/publications/StupidSH36.pdf
  22461. */
  22462. // 3-band SH defined by 9 coefficients
  22463. class SphericalHarmonics3 {
  22464. constructor() {
  22465. this.coefficients = [];
  22466. for ( let i = 0; i < 9; i ++ ) {
  22467. this.coefficients.push( new Vector3() );
  22468. }
  22469. }
  22470. set( coefficients ) {
  22471. for ( let i = 0; i < 9; i ++ ) {
  22472. this.coefficients[ i ].copy( coefficients[ i ] );
  22473. }
  22474. return this;
  22475. }
  22476. zero() {
  22477. for ( let i = 0; i < 9; i ++ ) {
  22478. this.coefficients[ i ].set( 0, 0, 0 );
  22479. }
  22480. return this;
  22481. }
  22482. // get the radiance in the direction of the normal
  22483. // target is a Vector3
  22484. getAt( normal, target ) {
  22485. // normal is assumed to be unit length
  22486. const x = normal.x, y = normal.y, z = normal.z;
  22487. const coeff = this.coefficients;
  22488. // band 0
  22489. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  22490. // band 1
  22491. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  22492. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  22493. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  22494. // band 2
  22495. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  22496. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  22497. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  22498. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  22499. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  22500. return target;
  22501. }
  22502. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  22503. // target is a Vector3
  22504. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  22505. getIrradianceAt( normal, target ) {
  22506. // normal is assumed to be unit length
  22507. const x = normal.x, y = normal.y, z = normal.z;
  22508. const coeff = this.coefficients;
  22509. // band 0
  22510. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  22511. // band 1
  22512. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  22513. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  22514. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  22515. // band 2
  22516. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  22517. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  22518. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  22519. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  22520. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  22521. return target;
  22522. }
  22523. add( sh ) {
  22524. for ( let i = 0; i < 9; i ++ ) {
  22525. this.coefficients[ i ].add( sh.coefficients[ i ] );
  22526. }
  22527. return this;
  22528. }
  22529. addScaledSH( sh, s ) {
  22530. for ( let i = 0; i < 9; i ++ ) {
  22531. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  22532. }
  22533. return this;
  22534. }
  22535. scale( s ) {
  22536. for ( let i = 0; i < 9; i ++ ) {
  22537. this.coefficients[ i ].multiplyScalar( s );
  22538. }
  22539. return this;
  22540. }
  22541. lerp( sh, alpha ) {
  22542. for ( let i = 0; i < 9; i ++ ) {
  22543. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  22544. }
  22545. return this;
  22546. }
  22547. equals( sh ) {
  22548. for ( let i = 0; i < 9; i ++ ) {
  22549. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  22550. return false;
  22551. }
  22552. }
  22553. return true;
  22554. }
  22555. copy( sh ) {
  22556. return this.set( sh.coefficients );
  22557. }
  22558. clone() {
  22559. return new this.constructor().copy( this );
  22560. }
  22561. fromArray( array, offset = 0 ) {
  22562. const coefficients = this.coefficients;
  22563. for ( let i = 0; i < 9; i ++ ) {
  22564. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  22565. }
  22566. return this;
  22567. }
  22568. toArray( array = [], offset = 0 ) {
  22569. const coefficients = this.coefficients;
  22570. for ( let i = 0; i < 9; i ++ ) {
  22571. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  22572. }
  22573. return array;
  22574. }
  22575. // evaluate the basis functions
  22576. // shBasis is an Array[ 9 ]
  22577. static getBasisAt( normal, shBasis ) {
  22578. // normal is assumed to be unit length
  22579. const x = normal.x, y = normal.y, z = normal.z;
  22580. // band 0
  22581. shBasis[ 0 ] = 0.282095;
  22582. // band 1
  22583. shBasis[ 1 ] = 0.488603 * y;
  22584. shBasis[ 2 ] = 0.488603 * z;
  22585. shBasis[ 3 ] = 0.488603 * x;
  22586. // band 2
  22587. shBasis[ 4 ] = 1.092548 * x * y;
  22588. shBasis[ 5 ] = 1.092548 * y * z;
  22589. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  22590. shBasis[ 7 ] = 1.092548 * x * z;
  22591. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  22592. }
  22593. }
  22594. SphericalHarmonics3.prototype.isSphericalHarmonics3 = true;
  22595. class LightProbe extends Light {
  22596. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  22597. super( undefined, intensity );
  22598. this.sh = sh;
  22599. }
  22600. copy( source ) {
  22601. super.copy( source );
  22602. this.sh.copy( source.sh );
  22603. return this;
  22604. }
  22605. fromJSON( json ) {
  22606. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  22607. this.sh.fromArray( json.sh );
  22608. return this;
  22609. }
  22610. toJSON( meta ) {
  22611. const data = super.toJSON( meta );
  22612. data.object.sh = this.sh.toArray();
  22613. return data;
  22614. }
  22615. }
  22616. LightProbe.prototype.isLightProbe = true;
  22617. class MaterialLoader extends Loader {
  22618. constructor( manager ) {
  22619. super( manager );
  22620. this.textures = {};
  22621. }
  22622. load( url, onLoad, onProgress, onError ) {
  22623. const scope = this;
  22624. const loader = new FileLoader( scope.manager );
  22625. loader.setPath( scope.path );
  22626. loader.setRequestHeader( scope.requestHeader );
  22627. loader.setWithCredentials( scope.withCredentials );
  22628. loader.load( url, function ( text ) {
  22629. try {
  22630. onLoad( scope.parse( JSON.parse( text ) ) );
  22631. } catch ( e ) {
  22632. if ( onError ) {
  22633. onError( e );
  22634. } else {
  22635. console.error( e );
  22636. }
  22637. scope.manager.itemError( url );
  22638. }
  22639. }, onProgress, onError );
  22640. }
  22641. parse( json ) {
  22642. const textures = this.textures;
  22643. function getTexture( name ) {
  22644. if ( textures[ name ] === undefined ) {
  22645. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  22646. }
  22647. return textures[ name ];
  22648. }
  22649. const material = new Materials[ json.type ]();
  22650. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  22651. if ( json.name !== undefined ) material.name = json.name;
  22652. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  22653. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  22654. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  22655. if ( json.sheen !== undefined ) material.sheen = new Color().setHex( json.sheen );
  22656. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  22657. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  22658. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  22659. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  22660. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  22661. if ( json.fog !== undefined ) material.fog = json.fog;
  22662. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  22663. if ( json.blending !== undefined ) material.blending = json.blending;
  22664. if ( json.combine !== undefined ) material.combine = json.combine;
  22665. if ( json.side !== undefined ) material.side = json.side;
  22666. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  22667. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  22668. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  22669. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  22670. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  22671. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  22672. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  22673. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  22674. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  22675. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  22676. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  22677. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  22678. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  22679. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  22680. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  22681. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  22682. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  22683. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  22684. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  22685. if ( json.linewidth !== 1 ) material.linewidth = json.linewidth;
  22686. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  22687. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  22688. if ( json.scale !== undefined ) material.scale = json.scale;
  22689. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  22690. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  22691. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  22692. if ( json.skinning !== undefined ) material.skinning = json.skinning;
  22693. if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets;
  22694. if ( json.morphNormals !== undefined ) material.morphNormals = json.morphNormals;
  22695. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  22696. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  22697. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  22698. if ( json.vertexTangents !== undefined ) material.vertexTangents = json.vertexTangents;
  22699. if ( json.visible !== undefined ) material.visible = json.visible;
  22700. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  22701. if ( json.userData !== undefined ) material.userData = json.userData;
  22702. if ( json.vertexColors !== undefined ) {
  22703. if ( typeof json.vertexColors === 'number' ) {
  22704. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  22705. } else {
  22706. material.vertexColors = json.vertexColors;
  22707. }
  22708. }
  22709. // Shader Material
  22710. if ( json.uniforms !== undefined ) {
  22711. for ( const name in json.uniforms ) {
  22712. const uniform = json.uniforms[ name ];
  22713. material.uniforms[ name ] = {};
  22714. switch ( uniform.type ) {
  22715. case 't':
  22716. material.uniforms[ name ].value = getTexture( uniform.value );
  22717. break;
  22718. case 'c':
  22719. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  22720. break;
  22721. case 'v2':
  22722. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  22723. break;
  22724. case 'v3':
  22725. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  22726. break;
  22727. case 'v4':
  22728. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  22729. break;
  22730. case 'm3':
  22731. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  22732. break;
  22733. case 'm4':
  22734. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  22735. break;
  22736. default:
  22737. material.uniforms[ name ].value = uniform.value;
  22738. }
  22739. }
  22740. }
  22741. if ( json.defines !== undefined ) material.defines = json.defines;
  22742. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  22743. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  22744. if ( json.extensions !== undefined ) {
  22745. for ( const key in json.extensions ) {
  22746. material.extensions[ key ] = json.extensions[ key ];
  22747. }
  22748. }
  22749. // Deprecated
  22750. if ( json.shading !== undefined ) material.flatShading = json.shading === 1; // THREE.FlatShading
  22751. // for PointsMaterial
  22752. if ( json.size !== undefined ) material.size = json.size;
  22753. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  22754. // maps
  22755. if ( json.map !== undefined ) material.map = getTexture( json.map );
  22756. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  22757. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  22758. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  22759. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  22760. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  22761. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  22762. if ( json.normalScale !== undefined ) {
  22763. let normalScale = json.normalScale;
  22764. if ( Array.isArray( normalScale ) === false ) {
  22765. // Blender exporter used to export a scalar. See #7459
  22766. normalScale = [ normalScale, normalScale ];
  22767. }
  22768. material.normalScale = new Vector2().fromArray( normalScale );
  22769. }
  22770. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  22771. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  22772. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  22773. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  22774. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  22775. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  22776. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  22777. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  22778. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  22779. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  22780. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  22781. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  22782. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  22783. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  22784. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  22785. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  22786. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  22787. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  22788. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  22789. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  22790. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  22791. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  22792. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  22793. return material;
  22794. }
  22795. setTextures( value ) {
  22796. this.textures = value;
  22797. return this;
  22798. }
  22799. }
  22800. const LoaderUtils = {
  22801. decodeText: function ( array ) {
  22802. if ( typeof TextDecoder !== 'undefined' ) {
  22803. return new TextDecoder().decode( array );
  22804. }
  22805. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  22806. // throws a "maximum call stack size exceeded" error for large arrays.
  22807. let s = '';
  22808. for ( let i = 0, il = array.length; i < il; i ++ ) {
  22809. // Implicitly assumes little-endian.
  22810. s += String.fromCharCode( array[ i ] );
  22811. }
  22812. try {
  22813. // merges multi-byte utf-8 characters.
  22814. return decodeURIComponent( escape( s ) );
  22815. } catch ( e ) { // see #16358
  22816. return s;
  22817. }
  22818. },
  22819. extractUrlBase: function ( url ) {
  22820. const index = url.lastIndexOf( '/' );
  22821. if ( index === - 1 ) return './';
  22822. return url.substr( 0, index + 1 );
  22823. }
  22824. };
  22825. function InstancedBufferGeometry() {
  22826. BufferGeometry.call( this );
  22827. this.type = 'InstancedBufferGeometry';
  22828. this.instanceCount = Infinity;
  22829. }
  22830. InstancedBufferGeometry.prototype = Object.assign( Object.create( BufferGeometry.prototype ), {
  22831. constructor: InstancedBufferGeometry,
  22832. isInstancedBufferGeometry: true,
  22833. copy: function ( source ) {
  22834. BufferGeometry.prototype.copy.call( this, source );
  22835. this.instanceCount = source.instanceCount;
  22836. return this;
  22837. },
  22838. clone: function () {
  22839. return new this.constructor().copy( this );
  22840. },
  22841. toJSON: function () {
  22842. const data = BufferGeometry.prototype.toJSON.call( this );
  22843. data.instanceCount = this.instanceCount;
  22844. data.isInstancedBufferGeometry = true;
  22845. return data;
  22846. }
  22847. } );
  22848. function InstancedBufferAttribute( array, itemSize, normalized, meshPerAttribute ) {
  22849. if ( typeof ( normalized ) === 'number' ) {
  22850. meshPerAttribute = normalized;
  22851. normalized = false;
  22852. console.error( 'THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.' );
  22853. }
  22854. BufferAttribute.call( this, array, itemSize, normalized );
  22855. this.meshPerAttribute = meshPerAttribute || 1;
  22856. }
  22857. InstancedBufferAttribute.prototype = Object.assign( Object.create( BufferAttribute.prototype ), {
  22858. constructor: InstancedBufferAttribute,
  22859. isInstancedBufferAttribute: true,
  22860. copy: function ( source ) {
  22861. BufferAttribute.prototype.copy.call( this, source );
  22862. this.meshPerAttribute = source.meshPerAttribute;
  22863. return this;
  22864. },
  22865. toJSON: function () {
  22866. const data = BufferAttribute.prototype.toJSON.call( this );
  22867. data.meshPerAttribute = this.meshPerAttribute;
  22868. data.isInstancedBufferAttribute = true;
  22869. return data;
  22870. }
  22871. } );
  22872. class BufferGeometryLoader extends Loader {
  22873. constructor( manager ) {
  22874. super( manager );
  22875. }
  22876. load( url, onLoad, onProgress, onError ) {
  22877. const scope = this;
  22878. const loader = new FileLoader( scope.manager );
  22879. loader.setPath( scope.path );
  22880. loader.setRequestHeader( scope.requestHeader );
  22881. loader.setWithCredentials( scope.withCredentials );
  22882. loader.load( url, function ( text ) {
  22883. try {
  22884. onLoad( scope.parse( JSON.parse( text ) ) );
  22885. } catch ( e ) {
  22886. if ( onError ) {
  22887. onError( e );
  22888. } else {
  22889. console.error( e );
  22890. }
  22891. scope.manager.itemError( url );
  22892. }
  22893. }, onProgress, onError );
  22894. }
  22895. parse( json ) {
  22896. const interleavedBufferMap = {};
  22897. const arrayBufferMap = {};
  22898. function getInterleavedBuffer( json, uuid ) {
  22899. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  22900. const interleavedBuffers = json.interleavedBuffers;
  22901. const interleavedBuffer = interleavedBuffers[ uuid ];
  22902. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  22903. const array = getTypedArray( interleavedBuffer.type, buffer );
  22904. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  22905. ib.uuid = interleavedBuffer.uuid;
  22906. interleavedBufferMap[ uuid ] = ib;
  22907. return ib;
  22908. }
  22909. function getArrayBuffer( json, uuid ) {
  22910. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  22911. const arrayBuffers = json.arrayBuffers;
  22912. const arrayBuffer = arrayBuffers[ uuid ];
  22913. const ab = new Uint32Array( arrayBuffer ).buffer;
  22914. arrayBufferMap[ uuid ] = ab;
  22915. return ab;
  22916. }
  22917. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  22918. const index = json.data.index;
  22919. if ( index !== undefined ) {
  22920. const typedArray = getTypedArray( index.type, index.array );
  22921. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  22922. }
  22923. const attributes = json.data.attributes;
  22924. for ( const key in attributes ) {
  22925. const attribute = attributes[ key ];
  22926. let bufferAttribute;
  22927. if ( attribute.isInterleavedBufferAttribute ) {
  22928. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  22929. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  22930. } else {
  22931. const typedArray = getTypedArray( attribute.type, attribute.array );
  22932. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  22933. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  22934. }
  22935. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  22936. geometry.setAttribute( key, bufferAttribute );
  22937. }
  22938. const morphAttributes = json.data.morphAttributes;
  22939. if ( morphAttributes ) {
  22940. for ( const key in morphAttributes ) {
  22941. const attributeArray = morphAttributes[ key ];
  22942. const array = [];
  22943. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  22944. const attribute = attributeArray[ i ];
  22945. let bufferAttribute;
  22946. if ( attribute.isInterleavedBufferAttribute ) {
  22947. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  22948. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  22949. } else {
  22950. const typedArray = getTypedArray( attribute.type, attribute.array );
  22951. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  22952. }
  22953. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  22954. array.push( bufferAttribute );
  22955. }
  22956. geometry.morphAttributes[ key ] = array;
  22957. }
  22958. }
  22959. const morphTargetsRelative = json.data.morphTargetsRelative;
  22960. if ( morphTargetsRelative ) {
  22961. geometry.morphTargetsRelative = true;
  22962. }
  22963. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  22964. if ( groups !== undefined ) {
  22965. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  22966. const group = groups[ i ];
  22967. geometry.addGroup( group.start, group.count, group.materialIndex );
  22968. }
  22969. }
  22970. const boundingSphere = json.data.boundingSphere;
  22971. if ( boundingSphere !== undefined ) {
  22972. const center = new Vector3();
  22973. if ( boundingSphere.center !== undefined ) {
  22974. center.fromArray( boundingSphere.center );
  22975. }
  22976. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  22977. }
  22978. if ( json.name ) geometry.name = json.name;
  22979. if ( json.userData ) geometry.userData = json.userData;
  22980. return geometry;
  22981. }
  22982. }
  22983. class ObjectLoader extends Loader {
  22984. constructor( manager ) {
  22985. super( manager );
  22986. }
  22987. load( url, onLoad, onProgress, onError ) {
  22988. const scope = this;
  22989. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  22990. this.resourcePath = this.resourcePath || path;
  22991. const loader = new FileLoader( this.manager );
  22992. loader.setPath( this.path );
  22993. loader.setRequestHeader( this.requestHeader );
  22994. loader.setWithCredentials( this.withCredentials );
  22995. loader.load( url, function ( text ) {
  22996. let json = null;
  22997. try {
  22998. json = JSON.parse( text );
  22999. } catch ( error ) {
  23000. if ( onError !== undefined ) onError( error );
  23001. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  23002. return;
  23003. }
  23004. const metadata = json.metadata;
  23005. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  23006. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  23007. return;
  23008. }
  23009. scope.parse( json, onLoad );
  23010. }, onProgress, onError );
  23011. }
  23012. parse( json, onLoad ) {
  23013. const animations = this.parseAnimations( json.animations );
  23014. const shapes = this.parseShapes( json.shapes );
  23015. const geometries = this.parseGeometries( json.geometries, shapes );
  23016. const images = this.parseImages( json.images, function () {
  23017. if ( onLoad !== undefined ) onLoad( object );
  23018. } );
  23019. const textures = this.parseTextures( json.textures, images );
  23020. const materials = this.parseMaterials( json.materials, textures );
  23021. const object = this.parseObject( json.object, geometries, materials, animations );
  23022. const skeletons = this.parseSkeletons( json.skeletons, object );
  23023. this.bindSkeletons( object, skeletons );
  23024. //
  23025. if ( onLoad !== undefined ) {
  23026. let hasImages = false;
  23027. for ( const uuid in images ) {
  23028. if ( images[ uuid ] instanceof HTMLImageElement ) {
  23029. hasImages = true;
  23030. break;
  23031. }
  23032. }
  23033. if ( hasImages === false ) onLoad( object );
  23034. }
  23035. return object;
  23036. }
  23037. parseShapes( json ) {
  23038. const shapes = {};
  23039. if ( json !== undefined ) {
  23040. for ( let i = 0, l = json.length; i < l; i ++ ) {
  23041. const shape = new Shape().fromJSON( json[ i ] );
  23042. shapes[ shape.uuid ] = shape;
  23043. }
  23044. }
  23045. return shapes;
  23046. }
  23047. parseSkeletons( json, object ) {
  23048. const skeletons = {};
  23049. const bones = {};
  23050. // generate bone lookup table
  23051. object.traverse( function ( child ) {
  23052. if ( child.isBone ) bones[ child.uuid ] = child;
  23053. } );
  23054. // create skeletons
  23055. if ( json !== undefined ) {
  23056. for ( let i = 0, l = json.length; i < l; i ++ ) {
  23057. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  23058. skeletons[ skeleton.uuid ] = skeleton;
  23059. }
  23060. }
  23061. return skeletons;
  23062. }
  23063. parseGeometries( json, shapes ) {
  23064. const geometries = {};
  23065. let geometryShapes;
  23066. if ( json !== undefined ) {
  23067. const bufferGeometryLoader = new BufferGeometryLoader();
  23068. for ( let i = 0, l = json.length; i < l; i ++ ) {
  23069. let geometry;
  23070. const data = json[ i ];
  23071. switch ( data.type ) {
  23072. case 'PlaneGeometry':
  23073. case 'PlaneBufferGeometry':
  23074. geometry = new Geometries[ data.type ](
  23075. data.width,
  23076. data.height,
  23077. data.widthSegments,
  23078. data.heightSegments
  23079. );
  23080. break;
  23081. case 'BoxGeometry':
  23082. case 'BoxBufferGeometry':
  23083. geometry = new Geometries[ data.type ](
  23084. data.width,
  23085. data.height,
  23086. data.depth,
  23087. data.widthSegments,
  23088. data.heightSegments,
  23089. data.depthSegments
  23090. );
  23091. break;
  23092. case 'CircleGeometry':
  23093. case 'CircleBufferGeometry':
  23094. geometry = new Geometries[ data.type ](
  23095. data.radius,
  23096. data.segments,
  23097. data.thetaStart,
  23098. data.thetaLength
  23099. );
  23100. break;
  23101. case 'CylinderGeometry':
  23102. case 'CylinderBufferGeometry':
  23103. geometry = new Geometries[ data.type ](
  23104. data.radiusTop,
  23105. data.radiusBottom,
  23106. data.height,
  23107. data.radialSegments,
  23108. data.heightSegments,
  23109. data.openEnded,
  23110. data.thetaStart,
  23111. data.thetaLength
  23112. );
  23113. break;
  23114. case 'ConeGeometry':
  23115. case 'ConeBufferGeometry':
  23116. geometry = new Geometries[ data.type ](
  23117. data.radius,
  23118. data.height,
  23119. data.radialSegments,
  23120. data.heightSegments,
  23121. data.openEnded,
  23122. data.thetaStart,
  23123. data.thetaLength
  23124. );
  23125. break;
  23126. case 'SphereGeometry':
  23127. case 'SphereBufferGeometry':
  23128. geometry = new Geometries[ data.type ](
  23129. data.radius,
  23130. data.widthSegments,
  23131. data.heightSegments,
  23132. data.phiStart,
  23133. data.phiLength,
  23134. data.thetaStart,
  23135. data.thetaLength
  23136. );
  23137. break;
  23138. case 'DodecahedronGeometry':
  23139. case 'DodecahedronBufferGeometry':
  23140. case 'IcosahedronGeometry':
  23141. case 'IcosahedronBufferGeometry':
  23142. case 'OctahedronGeometry':
  23143. case 'OctahedronBufferGeometry':
  23144. case 'TetrahedronGeometry':
  23145. case 'TetrahedronBufferGeometry':
  23146. geometry = new Geometries[ data.type ](
  23147. data.radius,
  23148. data.detail
  23149. );
  23150. break;
  23151. case 'RingGeometry':
  23152. case 'RingBufferGeometry':
  23153. geometry = new Geometries[ data.type ](
  23154. data.innerRadius,
  23155. data.outerRadius,
  23156. data.thetaSegments,
  23157. data.phiSegments,
  23158. data.thetaStart,
  23159. data.thetaLength
  23160. );
  23161. break;
  23162. case 'TorusGeometry':
  23163. case 'TorusBufferGeometry':
  23164. geometry = new Geometries[ data.type ](
  23165. data.radius,
  23166. data.tube,
  23167. data.radialSegments,
  23168. data.tubularSegments,
  23169. data.arc
  23170. );
  23171. break;
  23172. case 'TorusKnotGeometry':
  23173. case 'TorusKnotBufferGeometry':
  23174. geometry = new Geometries[ data.type ](
  23175. data.radius,
  23176. data.tube,
  23177. data.tubularSegments,
  23178. data.radialSegments,
  23179. data.p,
  23180. data.q
  23181. );
  23182. break;
  23183. case 'TubeGeometry':
  23184. case 'TubeBufferGeometry':
  23185. // This only works for built-in curves (e.g. CatmullRomCurve3).
  23186. // User defined curves or instances of CurvePath will not be deserialized.
  23187. geometry = new Geometries[ data.type ](
  23188. new Curves[ data.path.type ]().fromJSON( data.path ),
  23189. data.tubularSegments,
  23190. data.radius,
  23191. data.radialSegments,
  23192. data.closed
  23193. );
  23194. break;
  23195. case 'LatheGeometry':
  23196. case 'LatheBufferGeometry':
  23197. geometry = new Geometries[ data.type ](
  23198. data.points,
  23199. data.segments,
  23200. data.phiStart,
  23201. data.phiLength
  23202. );
  23203. break;
  23204. case 'PolyhedronGeometry':
  23205. case 'PolyhedronBufferGeometry':
  23206. geometry = new Geometries[ data.type ](
  23207. data.vertices,
  23208. data.indices,
  23209. data.radius,
  23210. data.details
  23211. );
  23212. break;
  23213. case 'ShapeGeometry':
  23214. case 'ShapeBufferGeometry':
  23215. geometryShapes = [];
  23216. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  23217. const shape = shapes[ data.shapes[ j ] ];
  23218. geometryShapes.push( shape );
  23219. }
  23220. geometry = new Geometries[ data.type ](
  23221. geometryShapes,
  23222. data.curveSegments
  23223. );
  23224. break;
  23225. case 'ExtrudeGeometry':
  23226. case 'ExtrudeBufferGeometry':
  23227. geometryShapes = [];
  23228. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  23229. const shape = shapes[ data.shapes[ j ] ];
  23230. geometryShapes.push( shape );
  23231. }
  23232. const extrudePath = data.options.extrudePath;
  23233. if ( extrudePath !== undefined ) {
  23234. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  23235. }
  23236. geometry = new Geometries[ data.type ](
  23237. geometryShapes,
  23238. data.options
  23239. );
  23240. break;
  23241. case 'BufferGeometry':
  23242. case 'InstancedBufferGeometry':
  23243. geometry = bufferGeometryLoader.parse( data );
  23244. break;
  23245. case 'Geometry':
  23246. console.error( 'THREE.ObjectLoader: Loading "Geometry" is not supported anymore.' );
  23247. break;
  23248. default:
  23249. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  23250. continue;
  23251. }
  23252. geometry.uuid = data.uuid;
  23253. if ( data.name !== undefined ) geometry.name = data.name;
  23254. if ( geometry.isBufferGeometry === true && data.userData !== undefined ) geometry.userData = data.userData;
  23255. geometries[ data.uuid ] = geometry;
  23256. }
  23257. }
  23258. return geometries;
  23259. }
  23260. parseMaterials( json, textures ) {
  23261. const cache = {}; // MultiMaterial
  23262. const materials = {};
  23263. if ( json !== undefined ) {
  23264. const loader = new MaterialLoader();
  23265. loader.setTextures( textures );
  23266. for ( let i = 0, l = json.length; i < l; i ++ ) {
  23267. const data = json[ i ];
  23268. if ( data.type === 'MultiMaterial' ) {
  23269. // Deprecated
  23270. const array = [];
  23271. for ( let j = 0; j < data.materials.length; j ++ ) {
  23272. const material = data.materials[ j ];
  23273. if ( cache[ material.uuid ] === undefined ) {
  23274. cache[ material.uuid ] = loader.parse( material );
  23275. }
  23276. array.push( cache[ material.uuid ] );
  23277. }
  23278. materials[ data.uuid ] = array;
  23279. } else {
  23280. if ( cache[ data.uuid ] === undefined ) {
  23281. cache[ data.uuid ] = loader.parse( data );
  23282. }
  23283. materials[ data.uuid ] = cache[ data.uuid ];
  23284. }
  23285. }
  23286. }
  23287. return materials;
  23288. }
  23289. parseAnimations( json ) {
  23290. const animations = {};
  23291. if ( json !== undefined ) {
  23292. for ( let i = 0; i < json.length; i ++ ) {
  23293. const data = json[ i ];
  23294. const clip = AnimationClip.parse( data );
  23295. animations[ clip.uuid ] = clip;
  23296. }
  23297. }
  23298. return animations;
  23299. }
  23300. parseImages( json, onLoad ) {
  23301. const scope = this;
  23302. const images = {};
  23303. let loader;
  23304. function loadImage( url ) {
  23305. scope.manager.itemStart( url );
  23306. return loader.load( url, function () {
  23307. scope.manager.itemEnd( url );
  23308. }, undefined, function () {
  23309. scope.manager.itemError( url );
  23310. scope.manager.itemEnd( url );
  23311. } );
  23312. }
  23313. function deserializeImage( image ) {
  23314. if ( typeof image === 'string' ) {
  23315. const url = image;
  23316. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  23317. return loadImage( path );
  23318. } else {
  23319. if ( image.data ) {
  23320. return {
  23321. data: getTypedArray( image.type, image.data ),
  23322. width: image.width,
  23323. height: image.height
  23324. };
  23325. } else {
  23326. return null;
  23327. }
  23328. }
  23329. }
  23330. if ( json !== undefined && json.length > 0 ) {
  23331. const manager = new LoadingManager( onLoad );
  23332. loader = new ImageLoader( manager );
  23333. loader.setCrossOrigin( this.crossOrigin );
  23334. for ( let i = 0, il = json.length; i < il; i ++ ) {
  23335. const image = json[ i ];
  23336. const url = image.url;
  23337. if ( Array.isArray( url ) ) {
  23338. // load array of images e.g CubeTexture
  23339. images[ image.uuid ] = [];
  23340. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  23341. const currentUrl = url[ j ];
  23342. const deserializedImage = deserializeImage( currentUrl );
  23343. if ( deserializedImage !== null ) {
  23344. if ( deserializedImage instanceof HTMLImageElement ) {
  23345. images[ image.uuid ].push( deserializedImage );
  23346. } else {
  23347. // special case: handle array of data textures for cube textures
  23348. images[ image.uuid ].push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  23349. }
  23350. }
  23351. }
  23352. } else {
  23353. // load single image
  23354. const deserializedImage = deserializeImage( image.url );
  23355. if ( deserializedImage !== null ) {
  23356. images[ image.uuid ] = deserializedImage;
  23357. }
  23358. }
  23359. }
  23360. }
  23361. return images;
  23362. }
  23363. parseTextures( json, images ) {
  23364. function parseConstant( value, type ) {
  23365. if ( typeof value === 'number' ) return value;
  23366. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  23367. return type[ value ];
  23368. }
  23369. const textures = {};
  23370. if ( json !== undefined ) {
  23371. for ( let i = 0, l = json.length; i < l; i ++ ) {
  23372. const data = json[ i ];
  23373. if ( data.image === undefined ) {
  23374. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  23375. }
  23376. if ( images[ data.image ] === undefined ) {
  23377. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  23378. }
  23379. let texture;
  23380. const image = images[ data.image ];
  23381. if ( Array.isArray( image ) ) {
  23382. texture = new CubeTexture( image );
  23383. if ( image.length === 6 ) texture.needsUpdate = true;
  23384. } else {
  23385. if ( image && image.data ) {
  23386. texture = new DataTexture( image.data, image.width, image.height );
  23387. } else {
  23388. texture = new Texture( image );
  23389. }
  23390. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  23391. }
  23392. texture.uuid = data.uuid;
  23393. if ( data.name !== undefined ) texture.name = data.name;
  23394. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  23395. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  23396. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  23397. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  23398. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  23399. if ( data.wrap !== undefined ) {
  23400. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  23401. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  23402. }
  23403. if ( data.format !== undefined ) texture.format = data.format;
  23404. if ( data.type !== undefined ) texture.type = data.type;
  23405. if ( data.encoding !== undefined ) texture.encoding = data.encoding;
  23406. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  23407. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  23408. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  23409. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  23410. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  23411. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  23412. textures[ data.uuid ] = texture;
  23413. }
  23414. }
  23415. return textures;
  23416. }
  23417. parseObject( data, geometries, materials, animations ) {
  23418. let object;
  23419. function getGeometry( name ) {
  23420. if ( geometries[ name ] === undefined ) {
  23421. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  23422. }
  23423. return geometries[ name ];
  23424. }
  23425. function getMaterial( name ) {
  23426. if ( name === undefined ) return undefined;
  23427. if ( Array.isArray( name ) ) {
  23428. const array = [];
  23429. for ( let i = 0, l = name.length; i < l; i ++ ) {
  23430. const uuid = name[ i ];
  23431. if ( materials[ uuid ] === undefined ) {
  23432. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  23433. }
  23434. array.push( materials[ uuid ] );
  23435. }
  23436. return array;
  23437. }
  23438. if ( materials[ name ] === undefined ) {
  23439. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  23440. }
  23441. return materials[ name ];
  23442. }
  23443. let geometry, material;
  23444. switch ( data.type ) {
  23445. case 'Scene':
  23446. object = new Scene();
  23447. if ( data.background !== undefined ) {
  23448. if ( Number.isInteger( data.background ) ) {
  23449. object.background = new Color( data.background );
  23450. }
  23451. }
  23452. if ( data.fog !== undefined ) {
  23453. if ( data.fog.type === 'Fog' ) {
  23454. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  23455. } else if ( data.fog.type === 'FogExp2' ) {
  23456. object.fog = new FogExp2( data.fog.color, data.fog.density );
  23457. }
  23458. }
  23459. break;
  23460. case 'PerspectiveCamera':
  23461. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  23462. if ( data.focus !== undefined ) object.focus = data.focus;
  23463. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  23464. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  23465. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  23466. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  23467. break;
  23468. case 'OrthographicCamera':
  23469. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  23470. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  23471. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  23472. break;
  23473. case 'AmbientLight':
  23474. object = new AmbientLight( data.color, data.intensity );
  23475. break;
  23476. case 'DirectionalLight':
  23477. object = new DirectionalLight( data.color, data.intensity );
  23478. break;
  23479. case 'PointLight':
  23480. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  23481. break;
  23482. case 'RectAreaLight':
  23483. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  23484. break;
  23485. case 'SpotLight':
  23486. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  23487. break;
  23488. case 'HemisphereLight':
  23489. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  23490. break;
  23491. case 'LightProbe':
  23492. object = new LightProbe().fromJSON( data );
  23493. break;
  23494. case 'SkinnedMesh':
  23495. geometry = getGeometry( data.geometry );
  23496. material = getMaterial( data.material );
  23497. object = new SkinnedMesh( geometry, material );
  23498. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  23499. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  23500. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  23501. break;
  23502. case 'Mesh':
  23503. geometry = getGeometry( data.geometry );
  23504. material = getMaterial( data.material );
  23505. object = new Mesh( geometry, material );
  23506. break;
  23507. case 'InstancedMesh':
  23508. geometry = getGeometry( data.geometry );
  23509. material = getMaterial( data.material );
  23510. const count = data.count;
  23511. const instanceMatrix = data.instanceMatrix;
  23512. object = new InstancedMesh( geometry, material, count );
  23513. object.instanceMatrix = new BufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  23514. break;
  23515. case 'LOD':
  23516. object = new LOD();
  23517. break;
  23518. case 'Line':
  23519. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  23520. break;
  23521. case 'LineLoop':
  23522. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  23523. break;
  23524. case 'LineSegments':
  23525. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  23526. break;
  23527. case 'PointCloud':
  23528. case 'Points':
  23529. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  23530. break;
  23531. case 'Sprite':
  23532. object = new Sprite( getMaterial( data.material ) );
  23533. break;
  23534. case 'Group':
  23535. object = new Group();
  23536. break;
  23537. case 'Bone':
  23538. object = new Bone();
  23539. break;
  23540. default:
  23541. object = new Object3D();
  23542. }
  23543. object.uuid = data.uuid;
  23544. if ( data.name !== undefined ) object.name = data.name;
  23545. if ( data.matrix !== undefined ) {
  23546. object.matrix.fromArray( data.matrix );
  23547. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  23548. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  23549. } else {
  23550. if ( data.position !== undefined ) object.position.fromArray( data.position );
  23551. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  23552. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  23553. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  23554. }
  23555. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  23556. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  23557. if ( data.shadow ) {
  23558. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  23559. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  23560. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  23561. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  23562. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  23563. }
  23564. if ( data.visible !== undefined ) object.visible = data.visible;
  23565. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  23566. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  23567. if ( data.userData !== undefined ) object.userData = data.userData;
  23568. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  23569. if ( data.children !== undefined ) {
  23570. const children = data.children;
  23571. for ( let i = 0; i < children.length; i ++ ) {
  23572. object.add( this.parseObject( children[ i ], geometries, materials, animations ) );
  23573. }
  23574. }
  23575. if ( data.animations !== undefined ) {
  23576. const objectAnimations = data.animations;
  23577. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  23578. const uuid = objectAnimations[ i ];
  23579. object.animations.push( animations[ uuid ] );
  23580. }
  23581. }
  23582. if ( data.type === 'LOD' ) {
  23583. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  23584. const levels = data.levels;
  23585. for ( let l = 0; l < levels.length; l ++ ) {
  23586. const level = levels[ l ];
  23587. const child = object.getObjectByProperty( 'uuid', level.object );
  23588. if ( child !== undefined ) {
  23589. object.addLevel( child, level.distance );
  23590. }
  23591. }
  23592. }
  23593. return object;
  23594. }
  23595. bindSkeletons( object, skeletons ) {
  23596. if ( Object.keys( skeletons ).length === 0 ) return;
  23597. object.traverse( function ( child ) {
  23598. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  23599. const skeleton = skeletons[ child.skeleton ];
  23600. if ( skeleton === undefined ) {
  23601. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  23602. } else {
  23603. child.bind( skeleton, child.bindMatrix );
  23604. }
  23605. }
  23606. } );
  23607. }
  23608. /* DEPRECATED */
  23609. setTexturePath( value ) {
  23610. console.warn( 'THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().' );
  23611. return this.setResourcePath( value );
  23612. }
  23613. }
  23614. const TEXTURE_MAPPING = {
  23615. UVMapping: UVMapping,
  23616. CubeReflectionMapping: CubeReflectionMapping,
  23617. CubeRefractionMapping: CubeRefractionMapping,
  23618. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  23619. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  23620. CubeUVReflectionMapping: CubeUVReflectionMapping,
  23621. CubeUVRefractionMapping: CubeUVRefractionMapping
  23622. };
  23623. const TEXTURE_WRAPPING = {
  23624. RepeatWrapping: RepeatWrapping,
  23625. ClampToEdgeWrapping: ClampToEdgeWrapping,
  23626. MirroredRepeatWrapping: MirroredRepeatWrapping
  23627. };
  23628. const TEXTURE_FILTER = {
  23629. NearestFilter: NearestFilter,
  23630. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  23631. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  23632. LinearFilter: LinearFilter,
  23633. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  23634. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  23635. };
  23636. function ImageBitmapLoader( manager ) {
  23637. if ( typeof createImageBitmap === 'undefined' ) {
  23638. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  23639. }
  23640. if ( typeof fetch === 'undefined' ) {
  23641. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  23642. }
  23643. Loader.call( this, manager );
  23644. this.options = { premultiplyAlpha: 'none' };
  23645. }
  23646. ImageBitmapLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  23647. constructor: ImageBitmapLoader,
  23648. isImageBitmapLoader: true,
  23649. setOptions: function setOptions( options ) {
  23650. this.options = options;
  23651. return this;
  23652. },
  23653. load: function ( url, onLoad, onProgress, onError ) {
  23654. if ( url === undefined ) url = '';
  23655. if ( this.path !== undefined ) url = this.path + url;
  23656. url = this.manager.resolveURL( url );
  23657. const scope = this;
  23658. const cached = Cache.get( url );
  23659. if ( cached !== undefined ) {
  23660. scope.manager.itemStart( url );
  23661. setTimeout( function () {
  23662. if ( onLoad ) onLoad( cached );
  23663. scope.manager.itemEnd( url );
  23664. }, 0 );
  23665. return cached;
  23666. }
  23667. const fetchOptions = {};
  23668. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  23669. fetchOptions.headers = this.requestHeader;
  23670. fetch( url, fetchOptions ).then( function ( res ) {
  23671. return res.blob();
  23672. } ).then( function ( blob ) {
  23673. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  23674. } ).then( function ( imageBitmap ) {
  23675. Cache.add( url, imageBitmap );
  23676. if ( onLoad ) onLoad( imageBitmap );
  23677. scope.manager.itemEnd( url );
  23678. } ).catch( function ( e ) {
  23679. if ( onError ) onError( e );
  23680. scope.manager.itemError( url );
  23681. scope.manager.itemEnd( url );
  23682. } );
  23683. scope.manager.itemStart( url );
  23684. }
  23685. } );
  23686. class ShapePath {
  23687. constructor() {
  23688. this.type = 'ShapePath';
  23689. this.color = new Color();
  23690. this.subPaths = [];
  23691. this.currentPath = null;
  23692. }
  23693. moveTo( x, y ) {
  23694. this.currentPath = new Path();
  23695. this.subPaths.push( this.currentPath );
  23696. this.currentPath.moveTo( x, y );
  23697. return this;
  23698. }
  23699. lineTo( x, y ) {
  23700. this.currentPath.lineTo( x, y );
  23701. return this;
  23702. }
  23703. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  23704. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  23705. return this;
  23706. }
  23707. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  23708. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  23709. return this;
  23710. }
  23711. splineThru( pts ) {
  23712. this.currentPath.splineThru( pts );
  23713. return this;
  23714. }
  23715. toShapes( isCCW, noHoles ) {
  23716. function toShapesNoHoles( inSubpaths ) {
  23717. const shapes = [];
  23718. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  23719. const tmpPath = inSubpaths[ i ];
  23720. const tmpShape = new Shape();
  23721. tmpShape.curves = tmpPath.curves;
  23722. shapes.push( tmpShape );
  23723. }
  23724. return shapes;
  23725. }
  23726. function isPointInsidePolygon( inPt, inPolygon ) {
  23727. const polyLen = inPolygon.length;
  23728. // inPt on polygon contour => immediate success or
  23729. // toggling of inside/outside at every single! intersection point of an edge
  23730. // with the horizontal line through inPt, left of inPt
  23731. // not counting lowerY endpoints of edges and whole edges on that line
  23732. let inside = false;
  23733. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  23734. let edgeLowPt = inPolygon[ p ];
  23735. let edgeHighPt = inPolygon[ q ];
  23736. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  23737. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  23738. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  23739. // not parallel
  23740. if ( edgeDy < 0 ) {
  23741. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  23742. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  23743. }
  23744. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  23745. if ( inPt.y === edgeLowPt.y ) {
  23746. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  23747. // continue; // no intersection or edgeLowPt => doesn't count !!!
  23748. } else {
  23749. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  23750. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  23751. if ( perpEdge < 0 ) continue;
  23752. inside = ! inside; // true intersection left of inPt
  23753. }
  23754. } else {
  23755. // parallel or collinear
  23756. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  23757. // edge lies on the same horizontal line as inPt
  23758. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  23759. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  23760. // continue;
  23761. }
  23762. }
  23763. return inside;
  23764. }
  23765. const isClockWise = ShapeUtils.isClockWise;
  23766. const subPaths = this.subPaths;
  23767. if ( subPaths.length === 0 ) return [];
  23768. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  23769. let solid, tmpPath, tmpShape;
  23770. const shapes = [];
  23771. if ( subPaths.length === 1 ) {
  23772. tmpPath = subPaths[ 0 ];
  23773. tmpShape = new Shape();
  23774. tmpShape.curves = tmpPath.curves;
  23775. shapes.push( tmpShape );
  23776. return shapes;
  23777. }
  23778. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  23779. holesFirst = isCCW ? ! holesFirst : holesFirst;
  23780. // console.log("Holes first", holesFirst);
  23781. const betterShapeHoles = [];
  23782. const newShapes = [];
  23783. let newShapeHoles = [];
  23784. let mainIdx = 0;
  23785. let tmpPoints;
  23786. newShapes[ mainIdx ] = undefined;
  23787. newShapeHoles[ mainIdx ] = [];
  23788. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  23789. tmpPath = subPaths[ i ];
  23790. tmpPoints = tmpPath.getPoints();
  23791. solid = isClockWise( tmpPoints );
  23792. solid = isCCW ? ! solid : solid;
  23793. if ( solid ) {
  23794. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  23795. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  23796. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  23797. if ( holesFirst ) mainIdx ++;
  23798. newShapeHoles[ mainIdx ] = [];
  23799. //console.log('cw', i);
  23800. } else {
  23801. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  23802. //console.log('ccw', i);
  23803. }
  23804. }
  23805. // only Holes? -> probably all Shapes with wrong orientation
  23806. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  23807. if ( newShapes.length > 1 ) {
  23808. let ambiguous = false;
  23809. const toChange = [];
  23810. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  23811. betterShapeHoles[ sIdx ] = [];
  23812. }
  23813. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  23814. const sho = newShapeHoles[ sIdx ];
  23815. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  23816. const ho = sho[ hIdx ];
  23817. let hole_unassigned = true;
  23818. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  23819. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  23820. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  23821. if ( hole_unassigned ) {
  23822. hole_unassigned = false;
  23823. betterShapeHoles[ s2Idx ].push( ho );
  23824. } else {
  23825. ambiguous = true;
  23826. }
  23827. }
  23828. }
  23829. if ( hole_unassigned ) {
  23830. betterShapeHoles[ sIdx ].push( ho );
  23831. }
  23832. }
  23833. }
  23834. // console.log("ambiguous: ", ambiguous);
  23835. if ( toChange.length > 0 ) {
  23836. // console.log("to change: ", toChange);
  23837. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  23838. }
  23839. }
  23840. let tmpHoles;
  23841. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  23842. tmpShape = newShapes[ i ].s;
  23843. shapes.push( tmpShape );
  23844. tmpHoles = newShapeHoles[ i ];
  23845. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  23846. tmpShape.holes.push( tmpHoles[ j ].h );
  23847. }
  23848. }
  23849. //console.log("shape", shapes);
  23850. return shapes;
  23851. }
  23852. }
  23853. class Font {
  23854. constructor( data ) {
  23855. this.type = 'Font';
  23856. this.data = data;
  23857. }
  23858. generateShapes( text, size = 100 ) {
  23859. const shapes = [];
  23860. const paths = createPaths( text, size, this.data );
  23861. for ( let p = 0, pl = paths.length; p < pl; p ++ ) {
  23862. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  23863. }
  23864. return shapes;
  23865. }
  23866. }
  23867. function createPaths( text, size, data ) {
  23868. const chars = Array.from( text );
  23869. const scale = size / data.resolution;
  23870. const line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale;
  23871. const paths = [];
  23872. let offsetX = 0, offsetY = 0;
  23873. for ( let i = 0; i < chars.length; i ++ ) {
  23874. const char = chars[ i ];
  23875. if ( char === '\n' ) {
  23876. offsetX = 0;
  23877. offsetY -= line_height;
  23878. } else {
  23879. const ret = createPath( char, scale, offsetX, offsetY, data );
  23880. offsetX += ret.offsetX;
  23881. paths.push( ret.path );
  23882. }
  23883. }
  23884. return paths;
  23885. }
  23886. function createPath( char, scale, offsetX, offsetY, data ) {
  23887. const glyph = data.glyphs[ char ] || data.glyphs[ '?' ];
  23888. if ( ! glyph ) {
  23889. console.error( 'THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.' );
  23890. return;
  23891. }
  23892. const path = new ShapePath();
  23893. let x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  23894. if ( glyph.o ) {
  23895. const outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  23896. for ( let i = 0, l = outline.length; i < l; ) {
  23897. const action = outline[ i ++ ];
  23898. switch ( action ) {
  23899. case 'm': // moveTo
  23900. x = outline[ i ++ ] * scale + offsetX;
  23901. y = outline[ i ++ ] * scale + offsetY;
  23902. path.moveTo( x, y );
  23903. break;
  23904. case 'l': // lineTo
  23905. x = outline[ i ++ ] * scale + offsetX;
  23906. y = outline[ i ++ ] * scale + offsetY;
  23907. path.lineTo( x, y );
  23908. break;
  23909. case 'q': // quadraticCurveTo
  23910. cpx = outline[ i ++ ] * scale + offsetX;
  23911. cpy = outline[ i ++ ] * scale + offsetY;
  23912. cpx1 = outline[ i ++ ] * scale + offsetX;
  23913. cpy1 = outline[ i ++ ] * scale + offsetY;
  23914. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  23915. break;
  23916. case 'b': // bezierCurveTo
  23917. cpx = outline[ i ++ ] * scale + offsetX;
  23918. cpy = outline[ i ++ ] * scale + offsetY;
  23919. cpx1 = outline[ i ++ ] * scale + offsetX;
  23920. cpy1 = outline[ i ++ ] * scale + offsetY;
  23921. cpx2 = outline[ i ++ ] * scale + offsetX;
  23922. cpy2 = outline[ i ++ ] * scale + offsetY;
  23923. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  23924. break;
  23925. }
  23926. }
  23927. }
  23928. return { offsetX: glyph.ha * scale, path: path };
  23929. }
  23930. Font.prototype.isFont = true;
  23931. class FontLoader extends Loader {
  23932. constructor( manager ) {
  23933. super( manager );
  23934. }
  23935. load( url, onLoad, onProgress, onError ) {
  23936. const scope = this;
  23937. const loader = new FileLoader( this.manager );
  23938. loader.setPath( this.path );
  23939. loader.setRequestHeader( this.requestHeader );
  23940. loader.setWithCredentials( scope.withCredentials );
  23941. loader.load( url, function ( text ) {
  23942. let json;
  23943. try {
  23944. json = JSON.parse( text );
  23945. } catch ( e ) {
  23946. console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
  23947. json = JSON.parse( text.substring( 65, text.length - 2 ) );
  23948. }
  23949. const font = scope.parse( json );
  23950. if ( onLoad ) onLoad( font );
  23951. }, onProgress, onError );
  23952. }
  23953. parse( json ) {
  23954. return new Font( json );
  23955. }
  23956. }
  23957. let _context;
  23958. const AudioContext = {
  23959. getContext: function () {
  23960. if ( _context === undefined ) {
  23961. _context = new ( window.AudioContext || window.webkitAudioContext )();
  23962. }
  23963. return _context;
  23964. },
  23965. setContext: function ( value ) {
  23966. _context = value;
  23967. }
  23968. };
  23969. class AudioLoader extends Loader {
  23970. constructor( manager ) {
  23971. super( manager );
  23972. }
  23973. load( url, onLoad, onProgress, onError ) {
  23974. const scope = this;
  23975. const loader = new FileLoader( this.manager );
  23976. loader.setResponseType( 'arraybuffer' );
  23977. loader.setPath( this.path );
  23978. loader.setRequestHeader( this.requestHeader );
  23979. loader.setWithCredentials( this.withCredentials );
  23980. loader.load( url, function ( buffer ) {
  23981. try {
  23982. // Create a copy of the buffer. The `decodeAudioData` method
  23983. // detaches the buffer when complete, preventing reuse.
  23984. const bufferCopy = buffer.slice( 0 );
  23985. const context = AudioContext.getContext();
  23986. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  23987. onLoad( audioBuffer );
  23988. } );
  23989. } catch ( e ) {
  23990. if ( onError ) {
  23991. onError( e );
  23992. } else {
  23993. console.error( e );
  23994. }
  23995. scope.manager.itemError( url );
  23996. }
  23997. }, onProgress, onError );
  23998. }
  23999. }
  24000. class HemisphereLightProbe extends LightProbe {
  24001. constructor( skyColor, groundColor, intensity = 1 ) {
  24002. super( undefined, intensity );
  24003. const color1 = new Color().set( skyColor );
  24004. const color2 = new Color().set( groundColor );
  24005. const sky = new Vector3( color1.r, color1.g, color1.b );
  24006. const ground = new Vector3( color2.r, color2.g, color2.b );
  24007. // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  24008. const c0 = Math.sqrt( Math.PI );
  24009. const c1 = c0 * Math.sqrt( 0.75 );
  24010. this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 );
  24011. this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 );
  24012. }
  24013. }
  24014. HemisphereLightProbe.prototype.isHemisphereLightProbe = true;
  24015. class AmbientLightProbe extends LightProbe {
  24016. constructor( color, intensity = 1 ) {
  24017. super( undefined, intensity );
  24018. const color1 = new Color().set( color );
  24019. // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  24020. this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) );
  24021. }
  24022. }
  24023. AmbientLightProbe.prototype.isAmbientLightProbe = true;
  24024. const _eyeRight = new Matrix4();
  24025. const _eyeLeft = new Matrix4();
  24026. class StereoCamera {
  24027. constructor() {
  24028. this.type = 'StereoCamera';
  24029. this.aspect = 1;
  24030. this.eyeSep = 0.064;
  24031. this.cameraL = new PerspectiveCamera();
  24032. this.cameraL.layers.enable( 1 );
  24033. this.cameraL.matrixAutoUpdate = false;
  24034. this.cameraR = new PerspectiveCamera();
  24035. this.cameraR.layers.enable( 2 );
  24036. this.cameraR.matrixAutoUpdate = false;
  24037. this._cache = {
  24038. focus: null,
  24039. fov: null,
  24040. aspect: null,
  24041. near: null,
  24042. far: null,
  24043. zoom: null,
  24044. eyeSep: null
  24045. };
  24046. }
  24047. update( camera ) {
  24048. const cache = this._cache;
  24049. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  24050. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  24051. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  24052. if ( needsUpdate ) {
  24053. cache.focus = camera.focus;
  24054. cache.fov = camera.fov;
  24055. cache.aspect = camera.aspect * this.aspect;
  24056. cache.near = camera.near;
  24057. cache.far = camera.far;
  24058. cache.zoom = camera.zoom;
  24059. cache.eyeSep = this.eyeSep;
  24060. // Off-axis stereoscopic effect based on
  24061. // http://paulbourke.net/stereographics/stereorender/
  24062. const projectionMatrix = camera.projectionMatrix.clone();
  24063. const eyeSepHalf = cache.eyeSep / 2;
  24064. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  24065. const ymax = ( cache.near * Math.tan( MathUtils.DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  24066. let xmin, xmax;
  24067. // translate xOffset
  24068. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  24069. _eyeRight.elements[ 12 ] = eyeSepHalf;
  24070. // for left eye
  24071. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  24072. xmax = ymax * cache.aspect + eyeSepOnProjection;
  24073. projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  24074. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  24075. this.cameraL.projectionMatrix.copy( projectionMatrix );
  24076. // for right eye
  24077. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  24078. xmax = ymax * cache.aspect - eyeSepOnProjection;
  24079. projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  24080. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  24081. this.cameraR.projectionMatrix.copy( projectionMatrix );
  24082. }
  24083. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  24084. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  24085. }
  24086. }
  24087. class Clock {
  24088. constructor( autoStart ) {
  24089. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  24090. this.startTime = 0;
  24091. this.oldTime = 0;
  24092. this.elapsedTime = 0;
  24093. this.running = false;
  24094. }
  24095. start() {
  24096. this.startTime = now();
  24097. this.oldTime = this.startTime;
  24098. this.elapsedTime = 0;
  24099. this.running = true;
  24100. }
  24101. stop() {
  24102. this.getElapsedTime();
  24103. this.running = false;
  24104. this.autoStart = false;
  24105. }
  24106. getElapsedTime() {
  24107. this.getDelta();
  24108. return this.elapsedTime;
  24109. }
  24110. getDelta() {
  24111. let diff = 0;
  24112. if ( this.autoStart && ! this.running ) {
  24113. this.start();
  24114. return 0;
  24115. }
  24116. if ( this.running ) {
  24117. const newTime = now();
  24118. diff = ( newTime - this.oldTime ) / 1000;
  24119. this.oldTime = newTime;
  24120. this.elapsedTime += diff;
  24121. }
  24122. return diff;
  24123. }
  24124. }
  24125. function now() {
  24126. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  24127. }
  24128. const _position$2 = /*@__PURE__*/ new Vector3();
  24129. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  24130. const _scale$1 = /*@__PURE__*/ new Vector3();
  24131. const _orientation = /*@__PURE__*/ new Vector3();
  24132. class AudioListener extends Object3D {
  24133. constructor() {
  24134. super();
  24135. this.type = 'AudioListener';
  24136. this.context = AudioContext.getContext();
  24137. this.gain = this.context.createGain();
  24138. this.gain.connect( this.context.destination );
  24139. this.filter = null;
  24140. this.timeDelta = 0;
  24141. // private
  24142. this._clock = new Clock();
  24143. }
  24144. getInput() {
  24145. return this.gain;
  24146. }
  24147. removeFilter() {
  24148. if ( this.filter !== null ) {
  24149. this.gain.disconnect( this.filter );
  24150. this.filter.disconnect( this.context.destination );
  24151. this.gain.connect( this.context.destination );
  24152. this.filter = null;
  24153. }
  24154. return this;
  24155. }
  24156. getFilter() {
  24157. return this.filter;
  24158. }
  24159. setFilter( value ) {
  24160. if ( this.filter !== null ) {
  24161. this.gain.disconnect( this.filter );
  24162. this.filter.disconnect( this.context.destination );
  24163. } else {
  24164. this.gain.disconnect( this.context.destination );
  24165. }
  24166. this.filter = value;
  24167. this.gain.connect( this.filter );
  24168. this.filter.connect( this.context.destination );
  24169. return this;
  24170. }
  24171. getMasterVolume() {
  24172. return this.gain.gain.value;
  24173. }
  24174. setMasterVolume( value ) {
  24175. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  24176. return this;
  24177. }
  24178. updateMatrixWorld( force ) {
  24179. super.updateMatrixWorld( force );
  24180. const listener = this.context.listener;
  24181. const up = this.up;
  24182. this.timeDelta = this._clock.getDelta();
  24183. this.matrixWorld.decompose( _position$2, _quaternion$3, _scale$1 );
  24184. _orientation.set( 0, 0, - 1 ).applyQuaternion( _quaternion$3 );
  24185. if ( listener.positionX ) {
  24186. // code path for Chrome (see #14393)
  24187. const endTime = this.context.currentTime + this.timeDelta;
  24188. listener.positionX.linearRampToValueAtTime( _position$2.x, endTime );
  24189. listener.positionY.linearRampToValueAtTime( _position$2.y, endTime );
  24190. listener.positionZ.linearRampToValueAtTime( _position$2.z, endTime );
  24191. listener.forwardX.linearRampToValueAtTime( _orientation.x, endTime );
  24192. listener.forwardY.linearRampToValueAtTime( _orientation.y, endTime );
  24193. listener.forwardZ.linearRampToValueAtTime( _orientation.z, endTime );
  24194. listener.upX.linearRampToValueAtTime( up.x, endTime );
  24195. listener.upY.linearRampToValueAtTime( up.y, endTime );
  24196. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  24197. } else {
  24198. listener.setPosition( _position$2.x, _position$2.y, _position$2.z );
  24199. listener.setOrientation( _orientation.x, _orientation.y, _orientation.z, up.x, up.y, up.z );
  24200. }
  24201. }
  24202. }
  24203. class Audio extends Object3D {
  24204. constructor( listener ) {
  24205. super();
  24206. this.type = 'Audio';
  24207. this.listener = listener;
  24208. this.context = listener.context;
  24209. this.gain = this.context.createGain();
  24210. this.gain.connect( listener.getInput() );
  24211. this.autoplay = false;
  24212. this.buffer = null;
  24213. this.detune = 0;
  24214. this.loop = false;
  24215. this.loopStart = 0;
  24216. this.loopEnd = 0;
  24217. this.offset = 0;
  24218. this.duration = undefined;
  24219. this.playbackRate = 1;
  24220. this.isPlaying = false;
  24221. this.hasPlaybackControl = true;
  24222. this.source = null;
  24223. this.sourceType = 'empty';
  24224. this._startedAt = 0;
  24225. this._progress = 0;
  24226. this._connected = false;
  24227. this.filters = [];
  24228. }
  24229. getOutput() {
  24230. return this.gain;
  24231. }
  24232. setNodeSource( audioNode ) {
  24233. this.hasPlaybackControl = false;
  24234. this.sourceType = 'audioNode';
  24235. this.source = audioNode;
  24236. this.connect();
  24237. return this;
  24238. }
  24239. setMediaElementSource( mediaElement ) {
  24240. this.hasPlaybackControl = false;
  24241. this.sourceType = 'mediaNode';
  24242. this.source = this.context.createMediaElementSource( mediaElement );
  24243. this.connect();
  24244. return this;
  24245. }
  24246. setMediaStreamSource( mediaStream ) {
  24247. this.hasPlaybackControl = false;
  24248. this.sourceType = 'mediaStreamNode';
  24249. this.source = this.context.createMediaStreamSource( mediaStream );
  24250. this.connect();
  24251. return this;
  24252. }
  24253. setBuffer( audioBuffer ) {
  24254. this.buffer = audioBuffer;
  24255. this.sourceType = 'buffer';
  24256. if ( this.autoplay ) this.play();
  24257. return this;
  24258. }
  24259. play( delay = 0 ) {
  24260. if ( this.isPlaying === true ) {
  24261. console.warn( 'THREE.Audio: Audio is already playing.' );
  24262. return;
  24263. }
  24264. if ( this.hasPlaybackControl === false ) {
  24265. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  24266. return;
  24267. }
  24268. this._startedAt = this.context.currentTime + delay;
  24269. const source = this.context.createBufferSource();
  24270. source.buffer = this.buffer;
  24271. source.loop = this.loop;
  24272. source.loopStart = this.loopStart;
  24273. source.loopEnd = this.loopEnd;
  24274. source.onended = this.onEnded.bind( this );
  24275. source.start( this._startedAt, this._progress + this.offset, this.duration );
  24276. this.isPlaying = true;
  24277. this.source = source;
  24278. this.setDetune( this.detune );
  24279. this.setPlaybackRate( this.playbackRate );
  24280. return this.connect();
  24281. }
  24282. pause() {
  24283. if ( this.hasPlaybackControl === false ) {
  24284. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  24285. return;
  24286. }
  24287. if ( this.isPlaying === true ) {
  24288. // update current progress
  24289. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  24290. if ( this.loop === true ) {
  24291. // ensure _progress does not exceed duration with looped audios
  24292. this._progress = this._progress % ( this.duration || this.buffer.duration );
  24293. }
  24294. this.source.stop();
  24295. this.source.onended = null;
  24296. this.isPlaying = false;
  24297. }
  24298. return this;
  24299. }
  24300. stop() {
  24301. if ( this.hasPlaybackControl === false ) {
  24302. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  24303. return;
  24304. }
  24305. this._progress = 0;
  24306. this.source.stop();
  24307. this.source.onended = null;
  24308. this.isPlaying = false;
  24309. return this;
  24310. }
  24311. connect() {
  24312. if ( this.filters.length > 0 ) {
  24313. this.source.connect( this.filters[ 0 ] );
  24314. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  24315. this.filters[ i - 1 ].connect( this.filters[ i ] );
  24316. }
  24317. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  24318. } else {
  24319. this.source.connect( this.getOutput() );
  24320. }
  24321. this._connected = true;
  24322. return this;
  24323. }
  24324. disconnect() {
  24325. if ( this.filters.length > 0 ) {
  24326. this.source.disconnect( this.filters[ 0 ] );
  24327. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  24328. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  24329. }
  24330. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  24331. } else {
  24332. this.source.disconnect( this.getOutput() );
  24333. }
  24334. this._connected = false;
  24335. return this;
  24336. }
  24337. getFilters() {
  24338. return this.filters;
  24339. }
  24340. setFilters( value ) {
  24341. if ( ! value ) value = [];
  24342. if ( this._connected === true ) {
  24343. this.disconnect();
  24344. this.filters = value.slice();
  24345. this.connect();
  24346. } else {
  24347. this.filters = value.slice();
  24348. }
  24349. return this;
  24350. }
  24351. setDetune( value ) {
  24352. this.detune = value;
  24353. if ( this.source.detune === undefined ) return; // only set detune when available
  24354. if ( this.isPlaying === true ) {
  24355. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  24356. }
  24357. return this;
  24358. }
  24359. getDetune() {
  24360. return this.detune;
  24361. }
  24362. getFilter() {
  24363. return this.getFilters()[ 0 ];
  24364. }
  24365. setFilter( filter ) {
  24366. return this.setFilters( filter ? [ filter ] : [] );
  24367. }
  24368. setPlaybackRate( value ) {
  24369. if ( this.hasPlaybackControl === false ) {
  24370. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  24371. return;
  24372. }
  24373. this.playbackRate = value;
  24374. if ( this.isPlaying === true ) {
  24375. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  24376. }
  24377. return this;
  24378. }
  24379. getPlaybackRate() {
  24380. return this.playbackRate;
  24381. }
  24382. onEnded() {
  24383. this.isPlaying = false;
  24384. }
  24385. getLoop() {
  24386. if ( this.hasPlaybackControl === false ) {
  24387. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  24388. return false;
  24389. }
  24390. return this.loop;
  24391. }
  24392. setLoop( value ) {
  24393. if ( this.hasPlaybackControl === false ) {
  24394. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  24395. return;
  24396. }
  24397. this.loop = value;
  24398. if ( this.isPlaying === true ) {
  24399. this.source.loop = this.loop;
  24400. }
  24401. return this;
  24402. }
  24403. setLoopStart( value ) {
  24404. this.loopStart = value;
  24405. return this;
  24406. }
  24407. setLoopEnd( value ) {
  24408. this.loopEnd = value;
  24409. return this;
  24410. }
  24411. getVolume() {
  24412. return this.gain.gain.value;
  24413. }
  24414. setVolume( value ) {
  24415. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  24416. return this;
  24417. }
  24418. }
  24419. const _position$3 = /*@__PURE__*/ new Vector3();
  24420. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  24421. const _scale$2 = /*@__PURE__*/ new Vector3();
  24422. const _orientation$1 = /*@__PURE__*/ new Vector3();
  24423. class PositionalAudio extends Audio {
  24424. constructor( listener ) {
  24425. super( listener );
  24426. this.panner = this.context.createPanner();
  24427. this.panner.panningModel = 'HRTF';
  24428. this.panner.connect( this.gain );
  24429. }
  24430. getOutput() {
  24431. return this.panner;
  24432. }
  24433. getRefDistance() {
  24434. return this.panner.refDistance;
  24435. }
  24436. setRefDistance( value ) {
  24437. this.panner.refDistance = value;
  24438. return this;
  24439. }
  24440. getRolloffFactor() {
  24441. return this.panner.rolloffFactor;
  24442. }
  24443. setRolloffFactor( value ) {
  24444. this.panner.rolloffFactor = value;
  24445. return this;
  24446. }
  24447. getDistanceModel() {
  24448. return this.panner.distanceModel;
  24449. }
  24450. setDistanceModel( value ) {
  24451. this.panner.distanceModel = value;
  24452. return this;
  24453. }
  24454. getMaxDistance() {
  24455. return this.panner.maxDistance;
  24456. }
  24457. setMaxDistance( value ) {
  24458. this.panner.maxDistance = value;
  24459. return this;
  24460. }
  24461. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  24462. this.panner.coneInnerAngle = coneInnerAngle;
  24463. this.panner.coneOuterAngle = coneOuterAngle;
  24464. this.panner.coneOuterGain = coneOuterGain;
  24465. return this;
  24466. }
  24467. updateMatrixWorld( force ) {
  24468. super.updateMatrixWorld( force );
  24469. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  24470. this.matrixWorld.decompose( _position$3, _quaternion$4, _scale$2 );
  24471. _orientation$1.set( 0, 0, 1 ).applyQuaternion( _quaternion$4 );
  24472. const panner = this.panner;
  24473. if ( panner.positionX ) {
  24474. // code path for Chrome and Firefox (see #14393)
  24475. const endTime = this.context.currentTime + this.listener.timeDelta;
  24476. panner.positionX.linearRampToValueAtTime( _position$3.x, endTime );
  24477. panner.positionY.linearRampToValueAtTime( _position$3.y, endTime );
  24478. panner.positionZ.linearRampToValueAtTime( _position$3.z, endTime );
  24479. panner.orientationX.linearRampToValueAtTime( _orientation$1.x, endTime );
  24480. panner.orientationY.linearRampToValueAtTime( _orientation$1.y, endTime );
  24481. panner.orientationZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  24482. } else {
  24483. panner.setPosition( _position$3.x, _position$3.y, _position$3.z );
  24484. panner.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z );
  24485. }
  24486. }
  24487. }
  24488. class AudioAnalyser {
  24489. constructor( audio, fftSize = 2048 ) {
  24490. this.analyser = audio.context.createAnalyser();
  24491. this.analyser.fftSize = fftSize;
  24492. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  24493. audio.getOutput().connect( this.analyser );
  24494. }
  24495. getFrequencyData() {
  24496. this.analyser.getByteFrequencyData( this.data );
  24497. return this.data;
  24498. }
  24499. getAverageFrequency() {
  24500. let value = 0;
  24501. const data = this.getFrequencyData();
  24502. for ( let i = 0; i < data.length; i ++ ) {
  24503. value += data[ i ];
  24504. }
  24505. return value / data.length;
  24506. }
  24507. }
  24508. class PropertyMixer {
  24509. constructor( binding, typeName, valueSize ) {
  24510. this.binding = binding;
  24511. this.valueSize = valueSize;
  24512. let mixFunction,
  24513. mixFunctionAdditive,
  24514. setIdentity;
  24515. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  24516. //
  24517. // interpolators can use .buffer as their .result
  24518. // the data then goes to 'incoming'
  24519. //
  24520. // 'accu0' and 'accu1' are used frame-interleaved for
  24521. // the cumulative result and are compared to detect
  24522. // changes
  24523. //
  24524. // 'orig' stores the original state of the property
  24525. //
  24526. // 'add' is used for additive cumulative results
  24527. //
  24528. // 'work' is optional and is only present for quaternion types. It is used
  24529. // to store intermediate quaternion multiplication results
  24530. switch ( typeName ) {
  24531. case 'quaternion':
  24532. mixFunction = this._slerp;
  24533. mixFunctionAdditive = this._slerpAdditive;
  24534. setIdentity = this._setAdditiveIdentityQuaternion;
  24535. this.buffer = new Float64Array( valueSize * 6 );
  24536. this._workIndex = 5;
  24537. break;
  24538. case 'string':
  24539. case 'bool':
  24540. mixFunction = this._select;
  24541. // Use the regular mix function and for additive on these types,
  24542. // additive is not relevant for non-numeric types
  24543. mixFunctionAdditive = this._select;
  24544. setIdentity = this._setAdditiveIdentityOther;
  24545. this.buffer = new Array( valueSize * 5 );
  24546. break;
  24547. default:
  24548. mixFunction = this._lerp;
  24549. mixFunctionAdditive = this._lerpAdditive;
  24550. setIdentity = this._setAdditiveIdentityNumeric;
  24551. this.buffer = new Float64Array( valueSize * 5 );
  24552. }
  24553. this._mixBufferRegion = mixFunction;
  24554. this._mixBufferRegionAdditive = mixFunctionAdditive;
  24555. this._setIdentity = setIdentity;
  24556. this._origIndex = 3;
  24557. this._addIndex = 4;
  24558. this.cumulativeWeight = 0;
  24559. this.cumulativeWeightAdditive = 0;
  24560. this.useCount = 0;
  24561. this.referenceCount = 0;
  24562. }
  24563. // accumulate data in the 'incoming' region into 'accu<i>'
  24564. accumulate( accuIndex, weight ) {
  24565. // note: happily accumulating nothing when weight = 0, the caller knows
  24566. // the weight and shouldn't have made the call in the first place
  24567. const buffer = this.buffer,
  24568. stride = this.valueSize,
  24569. offset = accuIndex * stride + stride;
  24570. let currentWeight = this.cumulativeWeight;
  24571. if ( currentWeight === 0 ) {
  24572. // accuN := incoming * weight
  24573. for ( let i = 0; i !== stride; ++ i ) {
  24574. buffer[ offset + i ] = buffer[ i ];
  24575. }
  24576. currentWeight = weight;
  24577. } else {
  24578. // accuN := accuN + incoming * weight
  24579. currentWeight += weight;
  24580. const mix = weight / currentWeight;
  24581. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  24582. }
  24583. this.cumulativeWeight = currentWeight;
  24584. }
  24585. // accumulate data in the 'incoming' region into 'add'
  24586. accumulateAdditive( weight ) {
  24587. const buffer = this.buffer,
  24588. stride = this.valueSize,
  24589. offset = stride * this._addIndex;
  24590. if ( this.cumulativeWeightAdditive === 0 ) {
  24591. // add = identity
  24592. this._setIdentity();
  24593. }
  24594. // add := add + incoming * weight
  24595. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  24596. this.cumulativeWeightAdditive += weight;
  24597. }
  24598. // apply the state of 'accu<i>' to the binding when accus differ
  24599. apply( accuIndex ) {
  24600. const stride = this.valueSize,
  24601. buffer = this.buffer,
  24602. offset = accuIndex * stride + stride,
  24603. weight = this.cumulativeWeight,
  24604. weightAdditive = this.cumulativeWeightAdditive,
  24605. binding = this.binding;
  24606. this.cumulativeWeight = 0;
  24607. this.cumulativeWeightAdditive = 0;
  24608. if ( weight < 1 ) {
  24609. // accuN := accuN + original * ( 1 - cumulativeWeight )
  24610. const originalValueOffset = stride * this._origIndex;
  24611. this._mixBufferRegion(
  24612. buffer, offset, originalValueOffset, 1 - weight, stride );
  24613. }
  24614. if ( weightAdditive > 0 ) {
  24615. // accuN := accuN + additive accuN
  24616. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  24617. }
  24618. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  24619. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  24620. // value has changed -> update scene graph
  24621. binding.setValue( buffer, offset );
  24622. break;
  24623. }
  24624. }
  24625. }
  24626. // remember the state of the bound property and copy it to both accus
  24627. saveOriginalState() {
  24628. const binding = this.binding;
  24629. const buffer = this.buffer,
  24630. stride = this.valueSize,
  24631. originalValueOffset = stride * this._origIndex;
  24632. binding.getValue( buffer, originalValueOffset );
  24633. // accu[0..1] := orig -- initially detect changes against the original
  24634. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  24635. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  24636. }
  24637. // Add to identity for additive
  24638. this._setIdentity();
  24639. this.cumulativeWeight = 0;
  24640. this.cumulativeWeightAdditive = 0;
  24641. }
  24642. // apply the state previously taken via 'saveOriginalState' to the binding
  24643. restoreOriginalState() {
  24644. const originalValueOffset = this.valueSize * 3;
  24645. this.binding.setValue( this.buffer, originalValueOffset );
  24646. }
  24647. _setAdditiveIdentityNumeric() {
  24648. const startIndex = this._addIndex * this.valueSize;
  24649. const endIndex = startIndex + this.valueSize;
  24650. for ( let i = startIndex; i < endIndex; i ++ ) {
  24651. this.buffer[ i ] = 0;
  24652. }
  24653. }
  24654. _setAdditiveIdentityQuaternion() {
  24655. this._setAdditiveIdentityNumeric();
  24656. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  24657. }
  24658. _setAdditiveIdentityOther() {
  24659. const startIndex = this._origIndex * this.valueSize;
  24660. const targetIndex = this._addIndex * this.valueSize;
  24661. for ( let i = 0; i < this.valueSize; i ++ ) {
  24662. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  24663. }
  24664. }
  24665. // mix functions
  24666. _select( buffer, dstOffset, srcOffset, t, stride ) {
  24667. if ( t >= 0.5 ) {
  24668. for ( let i = 0; i !== stride; ++ i ) {
  24669. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  24670. }
  24671. }
  24672. }
  24673. _slerp( buffer, dstOffset, srcOffset, t ) {
  24674. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  24675. }
  24676. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  24677. const workOffset = this._workIndex * stride;
  24678. // Store result in intermediate buffer offset
  24679. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  24680. // Slerp to the intermediate result
  24681. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  24682. }
  24683. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  24684. const s = 1 - t;
  24685. for ( let i = 0; i !== stride; ++ i ) {
  24686. const j = dstOffset + i;
  24687. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  24688. }
  24689. }
  24690. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  24691. for ( let i = 0; i !== stride; ++ i ) {
  24692. const j = dstOffset + i;
  24693. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  24694. }
  24695. }
  24696. }
  24697. // Characters [].:/ are reserved for track binding syntax.
  24698. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  24699. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  24700. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  24701. // only latin characters, and the unicode \p{L} is not yet supported. So
  24702. // instead, we exclude reserved characters and match everything else.
  24703. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  24704. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  24705. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  24706. // be matched to parse the rest of the track name.
  24707. const _directoryRe = /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  24708. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  24709. const _nodeRe = /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  24710. // Object on target node, and accessor. May not contain reserved
  24711. // characters. Accessor may contain any character except closing bracket.
  24712. const _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  24713. // Property and accessor. May not contain reserved characters. Accessor may
  24714. // contain any non-bracket characters.
  24715. const _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  24716. const _trackRe = new RegExp( ''
  24717. + '^'
  24718. + _directoryRe
  24719. + _nodeRe
  24720. + _objectRe
  24721. + _propertyRe
  24722. + '$'
  24723. );
  24724. const _supportedObjectNames = [ 'material', 'materials', 'bones' ];
  24725. function Composite( targetGroup, path, optionalParsedPath ) {
  24726. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  24727. this._targetGroup = targetGroup;
  24728. this._bindings = targetGroup.subscribe_( path, parsedPath );
  24729. }
  24730. Object.assign( Composite.prototype, {
  24731. getValue: function ( array, offset ) {
  24732. this.bind(); // bind all binding
  24733. const firstValidIndex = this._targetGroup.nCachedObjects_,
  24734. binding = this._bindings[ firstValidIndex ];
  24735. // and only call .getValue on the first
  24736. if ( binding !== undefined ) binding.getValue( array, offset );
  24737. },
  24738. setValue: function ( array, offset ) {
  24739. const bindings = this._bindings;
  24740. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  24741. bindings[ i ].setValue( array, offset );
  24742. }
  24743. },
  24744. bind: function () {
  24745. const bindings = this._bindings;
  24746. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  24747. bindings[ i ].bind();
  24748. }
  24749. },
  24750. unbind: function () {
  24751. const bindings = this._bindings;
  24752. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  24753. bindings[ i ].unbind();
  24754. }
  24755. }
  24756. } );
  24757. function PropertyBinding( rootNode, path, parsedPath ) {
  24758. this.path = path;
  24759. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  24760. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
  24761. this.rootNode = rootNode;
  24762. }
  24763. Object.assign( PropertyBinding, {
  24764. Composite: Composite,
  24765. create: function ( root, path, parsedPath ) {
  24766. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  24767. return new PropertyBinding( root, path, parsedPath );
  24768. } else {
  24769. return new PropertyBinding.Composite( root, path, parsedPath );
  24770. }
  24771. },
  24772. /**
  24773. * Replaces spaces with underscores and removes unsupported characters from
  24774. * node names, to ensure compatibility with parseTrackName().
  24775. *
  24776. * @param {string} name Node name to be sanitized.
  24777. * @return {string}
  24778. */
  24779. sanitizeNodeName: function ( name ) {
  24780. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  24781. },
  24782. parseTrackName: function ( trackName ) {
  24783. const matches = _trackRe.exec( trackName );
  24784. if ( ! matches ) {
  24785. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  24786. }
  24787. const results = {
  24788. // directoryName: matches[ 1 ], // (tschw) currently unused
  24789. nodeName: matches[ 2 ],
  24790. objectName: matches[ 3 ],
  24791. objectIndex: matches[ 4 ],
  24792. propertyName: matches[ 5 ], // required
  24793. propertyIndex: matches[ 6 ]
  24794. };
  24795. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  24796. if ( lastDot !== undefined && lastDot !== - 1 ) {
  24797. const objectName = results.nodeName.substring( lastDot + 1 );
  24798. // Object names must be checked against an allowlist. Otherwise, there
  24799. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  24800. // 'bar' could be the objectName, or part of a nodeName (which can
  24801. // include '.' characters).
  24802. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  24803. results.nodeName = results.nodeName.substring( 0, lastDot );
  24804. results.objectName = objectName;
  24805. }
  24806. }
  24807. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  24808. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  24809. }
  24810. return results;
  24811. },
  24812. findNode: function ( root, nodeName ) {
  24813. if ( ! nodeName || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  24814. return root;
  24815. }
  24816. // search into skeleton bones.
  24817. if ( root.skeleton ) {
  24818. const bone = root.skeleton.getBoneByName( nodeName );
  24819. if ( bone !== undefined ) {
  24820. return bone;
  24821. }
  24822. }
  24823. // search into node subtree.
  24824. if ( root.children ) {
  24825. const searchNodeSubtree = function ( children ) {
  24826. for ( let i = 0; i < children.length; i ++ ) {
  24827. const childNode = children[ i ];
  24828. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  24829. return childNode;
  24830. }
  24831. const result = searchNodeSubtree( childNode.children );
  24832. if ( result ) return result;
  24833. }
  24834. return null;
  24835. };
  24836. const subTreeNode = searchNodeSubtree( root.children );
  24837. if ( subTreeNode ) {
  24838. return subTreeNode;
  24839. }
  24840. }
  24841. return null;
  24842. }
  24843. } );
  24844. Object.assign( PropertyBinding.prototype, { // prototype, continued
  24845. // these are used to "bind" a nonexistent property
  24846. _getValue_unavailable: function () {},
  24847. _setValue_unavailable: function () {},
  24848. BindingType: {
  24849. Direct: 0,
  24850. EntireArray: 1,
  24851. ArrayElement: 2,
  24852. HasFromToArray: 3
  24853. },
  24854. Versioning: {
  24855. None: 0,
  24856. NeedsUpdate: 1,
  24857. MatrixWorldNeedsUpdate: 2
  24858. },
  24859. GetterByBindingType: [
  24860. function getValue_direct( buffer, offset ) {
  24861. buffer[ offset ] = this.node[ this.propertyName ];
  24862. },
  24863. function getValue_array( buffer, offset ) {
  24864. const source = this.resolvedProperty;
  24865. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  24866. buffer[ offset ++ ] = source[ i ];
  24867. }
  24868. },
  24869. function getValue_arrayElement( buffer, offset ) {
  24870. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  24871. },
  24872. function getValue_toArray( buffer, offset ) {
  24873. this.resolvedProperty.toArray( buffer, offset );
  24874. }
  24875. ],
  24876. SetterByBindingTypeAndVersioning: [
  24877. [
  24878. // Direct
  24879. function setValue_direct( buffer, offset ) {
  24880. this.targetObject[ this.propertyName ] = buffer[ offset ];
  24881. },
  24882. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  24883. this.targetObject[ this.propertyName ] = buffer[ offset ];
  24884. this.targetObject.needsUpdate = true;
  24885. },
  24886. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  24887. this.targetObject[ this.propertyName ] = buffer[ offset ];
  24888. this.targetObject.matrixWorldNeedsUpdate = true;
  24889. }
  24890. ], [
  24891. // EntireArray
  24892. function setValue_array( buffer, offset ) {
  24893. const dest = this.resolvedProperty;
  24894. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  24895. dest[ i ] = buffer[ offset ++ ];
  24896. }
  24897. },
  24898. function setValue_array_setNeedsUpdate( buffer, offset ) {
  24899. const dest = this.resolvedProperty;
  24900. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  24901. dest[ i ] = buffer[ offset ++ ];
  24902. }
  24903. this.targetObject.needsUpdate = true;
  24904. },
  24905. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  24906. const dest = this.resolvedProperty;
  24907. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  24908. dest[ i ] = buffer[ offset ++ ];
  24909. }
  24910. this.targetObject.matrixWorldNeedsUpdate = true;
  24911. }
  24912. ], [
  24913. // ArrayElement
  24914. function setValue_arrayElement( buffer, offset ) {
  24915. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  24916. },
  24917. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  24918. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  24919. this.targetObject.needsUpdate = true;
  24920. },
  24921. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  24922. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  24923. this.targetObject.matrixWorldNeedsUpdate = true;
  24924. }
  24925. ], [
  24926. // HasToFromArray
  24927. function setValue_fromArray( buffer, offset ) {
  24928. this.resolvedProperty.fromArray( buffer, offset );
  24929. },
  24930. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  24931. this.resolvedProperty.fromArray( buffer, offset );
  24932. this.targetObject.needsUpdate = true;
  24933. },
  24934. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  24935. this.resolvedProperty.fromArray( buffer, offset );
  24936. this.targetObject.matrixWorldNeedsUpdate = true;
  24937. }
  24938. ]
  24939. ],
  24940. getValue: function getValue_unbound( targetArray, offset ) {
  24941. this.bind();
  24942. this.getValue( targetArray, offset );
  24943. // Note: This class uses a State pattern on a per-method basis:
  24944. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  24945. // prototype version of these methods with one that represents
  24946. // the bound state. When the property is not found, the methods
  24947. // become no-ops.
  24948. },
  24949. setValue: function getValue_unbound( sourceArray, offset ) {
  24950. this.bind();
  24951. this.setValue( sourceArray, offset );
  24952. },
  24953. // create getter / setter pair for a property in the scene graph
  24954. bind: function () {
  24955. let targetObject = this.node;
  24956. const parsedPath = this.parsedPath;
  24957. const objectName = parsedPath.objectName;
  24958. const propertyName = parsedPath.propertyName;
  24959. let propertyIndex = parsedPath.propertyIndex;
  24960. if ( ! targetObject ) {
  24961. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode;
  24962. this.node = targetObject;
  24963. }
  24964. // set fail state so we can just 'return' on error
  24965. this.getValue = this._getValue_unavailable;
  24966. this.setValue = this._setValue_unavailable;
  24967. // ensure there is a value node
  24968. if ( ! targetObject ) {
  24969. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  24970. return;
  24971. }
  24972. if ( objectName ) {
  24973. let objectIndex = parsedPath.objectIndex;
  24974. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  24975. switch ( objectName ) {
  24976. case 'materials':
  24977. if ( ! targetObject.material ) {
  24978. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  24979. return;
  24980. }
  24981. if ( ! targetObject.material.materials ) {
  24982. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  24983. return;
  24984. }
  24985. targetObject = targetObject.material.materials;
  24986. break;
  24987. case 'bones':
  24988. if ( ! targetObject.skeleton ) {
  24989. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  24990. return;
  24991. }
  24992. // potential future optimization: skip this if propertyIndex is already an integer
  24993. // and convert the integer string to a true integer.
  24994. targetObject = targetObject.skeleton.bones;
  24995. // support resolving morphTarget names into indices.
  24996. for ( let i = 0; i < targetObject.length; i ++ ) {
  24997. if ( targetObject[ i ].name === objectIndex ) {
  24998. objectIndex = i;
  24999. break;
  25000. }
  25001. }
  25002. break;
  25003. default:
  25004. if ( targetObject[ objectName ] === undefined ) {
  25005. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  25006. return;
  25007. }
  25008. targetObject = targetObject[ objectName ];
  25009. }
  25010. if ( objectIndex !== undefined ) {
  25011. if ( targetObject[ objectIndex ] === undefined ) {
  25012. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  25013. return;
  25014. }
  25015. targetObject = targetObject[ objectIndex ];
  25016. }
  25017. }
  25018. // resolve property
  25019. const nodeProperty = targetObject[ propertyName ];
  25020. if ( nodeProperty === undefined ) {
  25021. const nodeName = parsedPath.nodeName;
  25022. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  25023. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  25024. return;
  25025. }
  25026. // determine versioning scheme
  25027. let versioning = this.Versioning.None;
  25028. this.targetObject = targetObject;
  25029. if ( targetObject.needsUpdate !== undefined ) { // material
  25030. versioning = this.Versioning.NeedsUpdate;
  25031. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  25032. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  25033. }
  25034. // determine how the property gets bound
  25035. let bindingType = this.BindingType.Direct;
  25036. if ( propertyIndex !== undefined ) {
  25037. // access a sub element of the property array (only primitives are supported right now)
  25038. if ( propertyName === 'morphTargetInfluences' ) {
  25039. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  25040. // support resolving morphTarget names into indices.
  25041. if ( ! targetObject.geometry ) {
  25042. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  25043. return;
  25044. }
  25045. if ( targetObject.geometry.isBufferGeometry ) {
  25046. if ( ! targetObject.geometry.morphAttributes ) {
  25047. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  25048. return;
  25049. }
  25050. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  25051. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  25052. }
  25053. } else {
  25054. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this );
  25055. return;
  25056. }
  25057. }
  25058. bindingType = this.BindingType.ArrayElement;
  25059. this.resolvedProperty = nodeProperty;
  25060. this.propertyIndex = propertyIndex;
  25061. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  25062. // must use copy for Object3D.Euler/Quaternion
  25063. bindingType = this.BindingType.HasFromToArray;
  25064. this.resolvedProperty = nodeProperty;
  25065. } else if ( Array.isArray( nodeProperty ) ) {
  25066. bindingType = this.BindingType.EntireArray;
  25067. this.resolvedProperty = nodeProperty;
  25068. } else {
  25069. this.propertyName = propertyName;
  25070. }
  25071. // select getter / setter
  25072. this.getValue = this.GetterByBindingType[ bindingType ];
  25073. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  25074. },
  25075. unbind: function () {
  25076. this.node = null;
  25077. // back to the prototype version of getValue / setValue
  25078. // note: avoiding to mutate the shape of 'this' via 'delete'
  25079. this.getValue = this._getValue_unbound;
  25080. this.setValue = this._setValue_unbound;
  25081. }
  25082. } );
  25083. // DECLARE ALIAS AFTER assign prototype
  25084. Object.assign( PropertyBinding.prototype, {
  25085. // initial state of these methods that calls 'bind'
  25086. _getValue_unbound: PropertyBinding.prototype.getValue,
  25087. _setValue_unbound: PropertyBinding.prototype.setValue,
  25088. } );
  25089. /**
  25090. *
  25091. * A group of objects that receives a shared animation state.
  25092. *
  25093. * Usage:
  25094. *
  25095. * - Add objects you would otherwise pass as 'root' to the
  25096. * constructor or the .clipAction method of AnimationMixer.
  25097. *
  25098. * - Instead pass this object as 'root'.
  25099. *
  25100. * - You can also add and remove objects later when the mixer
  25101. * is running.
  25102. *
  25103. * Note:
  25104. *
  25105. * Objects of this class appear as one object to the mixer,
  25106. * so cache control of the individual objects must be done
  25107. * on the group.
  25108. *
  25109. * Limitation:
  25110. *
  25111. * - The animated properties must be compatible among the
  25112. * all objects in the group.
  25113. *
  25114. * - A single property can either be controlled through a
  25115. * target group or directly, but not both.
  25116. */
  25117. class AnimationObjectGroup {
  25118. constructor() {
  25119. this.uuid = MathUtils.generateUUID();
  25120. // cached objects followed by the active ones
  25121. this._objects = Array.prototype.slice.call( arguments );
  25122. this.nCachedObjects_ = 0; // threshold
  25123. // note: read by PropertyBinding.Composite
  25124. const indices = {};
  25125. this._indicesByUUID = indices; // for bookkeeping
  25126. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  25127. indices[ arguments[ i ].uuid ] = i;
  25128. }
  25129. this._paths = []; // inside: string
  25130. this._parsedPaths = []; // inside: { we don't care, here }
  25131. this._bindings = []; // inside: Array< PropertyBinding >
  25132. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  25133. const scope = this;
  25134. this.stats = {
  25135. objects: {
  25136. get total() {
  25137. return scope._objects.length;
  25138. },
  25139. get inUse() {
  25140. return this.total - scope.nCachedObjects_;
  25141. }
  25142. },
  25143. get bindingsPerObject() {
  25144. return scope._bindings.length;
  25145. }
  25146. };
  25147. }
  25148. add() {
  25149. const objects = this._objects,
  25150. indicesByUUID = this._indicesByUUID,
  25151. paths = this._paths,
  25152. parsedPaths = this._parsedPaths,
  25153. bindings = this._bindings,
  25154. nBindings = bindings.length;
  25155. let knownObject = undefined,
  25156. nObjects = objects.length,
  25157. nCachedObjects = this.nCachedObjects_;
  25158. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  25159. const object = arguments[ i ],
  25160. uuid = object.uuid;
  25161. let index = indicesByUUID[ uuid ];
  25162. if ( index === undefined ) {
  25163. // unknown object -> add it to the ACTIVE region
  25164. index = nObjects ++;
  25165. indicesByUUID[ uuid ] = index;
  25166. objects.push( object );
  25167. // accounting is done, now do the same for all bindings
  25168. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  25169. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  25170. }
  25171. } else if ( index < nCachedObjects ) {
  25172. knownObject = objects[ index ];
  25173. // move existing object to the ACTIVE region
  25174. const firstActiveIndex = -- nCachedObjects,
  25175. lastCachedObject = objects[ firstActiveIndex ];
  25176. indicesByUUID[ lastCachedObject.uuid ] = index;
  25177. objects[ index ] = lastCachedObject;
  25178. indicesByUUID[ uuid ] = firstActiveIndex;
  25179. objects[ firstActiveIndex ] = object;
  25180. // accounting is done, now do the same for all bindings
  25181. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  25182. const bindingsForPath = bindings[ j ],
  25183. lastCached = bindingsForPath[ firstActiveIndex ];
  25184. let binding = bindingsForPath[ index ];
  25185. bindingsForPath[ index ] = lastCached;
  25186. if ( binding === undefined ) {
  25187. // since we do not bother to create new bindings
  25188. // for objects that are cached, the binding may
  25189. // or may not exist
  25190. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  25191. }
  25192. bindingsForPath[ firstActiveIndex ] = binding;
  25193. }
  25194. } else if ( objects[ index ] !== knownObject ) {
  25195. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  25196. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  25197. } // else the object is already where we want it to be
  25198. } // for arguments
  25199. this.nCachedObjects_ = nCachedObjects;
  25200. }
  25201. remove() {
  25202. const objects = this._objects,
  25203. indicesByUUID = this._indicesByUUID,
  25204. bindings = this._bindings,
  25205. nBindings = bindings.length;
  25206. let nCachedObjects = this.nCachedObjects_;
  25207. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  25208. const object = arguments[ i ],
  25209. uuid = object.uuid,
  25210. index = indicesByUUID[ uuid ];
  25211. if ( index !== undefined && index >= nCachedObjects ) {
  25212. // move existing object into the CACHED region
  25213. const lastCachedIndex = nCachedObjects ++,
  25214. firstActiveObject = objects[ lastCachedIndex ];
  25215. indicesByUUID[ firstActiveObject.uuid ] = index;
  25216. objects[ index ] = firstActiveObject;
  25217. indicesByUUID[ uuid ] = lastCachedIndex;
  25218. objects[ lastCachedIndex ] = object;
  25219. // accounting is done, now do the same for all bindings
  25220. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  25221. const bindingsForPath = bindings[ j ],
  25222. firstActive = bindingsForPath[ lastCachedIndex ],
  25223. binding = bindingsForPath[ index ];
  25224. bindingsForPath[ index ] = firstActive;
  25225. bindingsForPath[ lastCachedIndex ] = binding;
  25226. }
  25227. }
  25228. } // for arguments
  25229. this.nCachedObjects_ = nCachedObjects;
  25230. }
  25231. // remove & forget
  25232. uncache() {
  25233. const objects = this._objects,
  25234. indicesByUUID = this._indicesByUUID,
  25235. bindings = this._bindings,
  25236. nBindings = bindings.length;
  25237. let nCachedObjects = this.nCachedObjects_,
  25238. nObjects = objects.length;
  25239. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  25240. const object = arguments[ i ],
  25241. uuid = object.uuid,
  25242. index = indicesByUUID[ uuid ];
  25243. if ( index !== undefined ) {
  25244. delete indicesByUUID[ uuid ];
  25245. if ( index < nCachedObjects ) {
  25246. // object is cached, shrink the CACHED region
  25247. const firstActiveIndex = -- nCachedObjects,
  25248. lastCachedObject = objects[ firstActiveIndex ],
  25249. lastIndex = -- nObjects,
  25250. lastObject = objects[ lastIndex ];
  25251. // last cached object takes this object's place
  25252. indicesByUUID[ lastCachedObject.uuid ] = index;
  25253. objects[ index ] = lastCachedObject;
  25254. // last object goes to the activated slot and pop
  25255. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  25256. objects[ firstActiveIndex ] = lastObject;
  25257. objects.pop();
  25258. // accounting is done, now do the same for all bindings
  25259. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  25260. const bindingsForPath = bindings[ j ],
  25261. lastCached = bindingsForPath[ firstActiveIndex ],
  25262. last = bindingsForPath[ lastIndex ];
  25263. bindingsForPath[ index ] = lastCached;
  25264. bindingsForPath[ firstActiveIndex ] = last;
  25265. bindingsForPath.pop();
  25266. }
  25267. } else {
  25268. // object is active, just swap with the last and pop
  25269. const lastIndex = -- nObjects,
  25270. lastObject = objects[ lastIndex ];
  25271. if ( lastIndex > 0 ) {
  25272. indicesByUUID[ lastObject.uuid ] = index;
  25273. }
  25274. objects[ index ] = lastObject;
  25275. objects.pop();
  25276. // accounting is done, now do the same for all bindings
  25277. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  25278. const bindingsForPath = bindings[ j ];
  25279. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  25280. bindingsForPath.pop();
  25281. }
  25282. } // cached or active
  25283. } // if object is known
  25284. } // for arguments
  25285. this.nCachedObjects_ = nCachedObjects;
  25286. }
  25287. // Internal interface used by befriended PropertyBinding.Composite:
  25288. subscribe_( path, parsedPath ) {
  25289. // returns an array of bindings for the given path that is changed
  25290. // according to the contained objects in the group
  25291. const indicesByPath = this._bindingsIndicesByPath;
  25292. let index = indicesByPath[ path ];
  25293. const bindings = this._bindings;
  25294. if ( index !== undefined ) return bindings[ index ];
  25295. const paths = this._paths,
  25296. parsedPaths = this._parsedPaths,
  25297. objects = this._objects,
  25298. nObjects = objects.length,
  25299. nCachedObjects = this.nCachedObjects_,
  25300. bindingsForPath = new Array( nObjects );
  25301. index = bindings.length;
  25302. indicesByPath[ path ] = index;
  25303. paths.push( path );
  25304. parsedPaths.push( parsedPath );
  25305. bindings.push( bindingsForPath );
  25306. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  25307. const object = objects[ i ];
  25308. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  25309. }
  25310. return bindingsForPath;
  25311. }
  25312. unsubscribe_( path ) {
  25313. // tells the group to forget about a property path and no longer
  25314. // update the array previously obtained with 'subscribe_'
  25315. const indicesByPath = this._bindingsIndicesByPath,
  25316. index = indicesByPath[ path ];
  25317. if ( index !== undefined ) {
  25318. const paths = this._paths,
  25319. parsedPaths = this._parsedPaths,
  25320. bindings = this._bindings,
  25321. lastBindingsIndex = bindings.length - 1,
  25322. lastBindings = bindings[ lastBindingsIndex ],
  25323. lastBindingsPath = path[ lastBindingsIndex ];
  25324. indicesByPath[ lastBindingsPath ] = index;
  25325. bindings[ index ] = lastBindings;
  25326. bindings.pop();
  25327. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  25328. parsedPaths.pop();
  25329. paths[ index ] = paths[ lastBindingsIndex ];
  25330. paths.pop();
  25331. }
  25332. }
  25333. }
  25334. AnimationObjectGroup.prototype.isAnimationObjectGroup = true;
  25335. class AnimationAction {
  25336. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  25337. this._mixer = mixer;
  25338. this._clip = clip;
  25339. this._localRoot = localRoot;
  25340. this.blendMode = blendMode;
  25341. const tracks = clip.tracks,
  25342. nTracks = tracks.length,
  25343. interpolants = new Array( nTracks );
  25344. const interpolantSettings = {
  25345. endingStart: ZeroCurvatureEnding,
  25346. endingEnd: ZeroCurvatureEnding
  25347. };
  25348. for ( let i = 0; i !== nTracks; ++ i ) {
  25349. const interpolant = tracks[ i ].createInterpolant( null );
  25350. interpolants[ i ] = interpolant;
  25351. interpolant.settings = interpolantSettings;
  25352. }
  25353. this._interpolantSettings = interpolantSettings;
  25354. this._interpolants = interpolants; // bound by the mixer
  25355. // inside: PropertyMixer (managed by the mixer)
  25356. this._propertyBindings = new Array( nTracks );
  25357. this._cacheIndex = null; // for the memory manager
  25358. this._byClipCacheIndex = null; // for the memory manager
  25359. this._timeScaleInterpolant = null;
  25360. this._weightInterpolant = null;
  25361. this.loop = LoopRepeat;
  25362. this._loopCount = - 1;
  25363. // global mixer time when the action is to be started
  25364. // it's set back to 'null' upon start of the action
  25365. this._startTime = null;
  25366. // scaled local time of the action
  25367. // gets clamped or wrapped to 0..clip.duration according to loop
  25368. this.time = 0;
  25369. this.timeScale = 1;
  25370. this._effectiveTimeScale = 1;
  25371. this.weight = 1;
  25372. this._effectiveWeight = 1;
  25373. this.repetitions = Infinity; // no. of repetitions when looping
  25374. this.paused = false; // true -> zero effective time scale
  25375. this.enabled = true; // false -> zero effective weight
  25376. this.clampWhenFinished = false;// keep feeding the last frame?
  25377. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  25378. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  25379. }
  25380. // State & Scheduling
  25381. play() {
  25382. this._mixer._activateAction( this );
  25383. return this;
  25384. }
  25385. stop() {
  25386. this._mixer._deactivateAction( this );
  25387. return this.reset();
  25388. }
  25389. reset() {
  25390. this.paused = false;
  25391. this.enabled = true;
  25392. this.time = 0; // restart clip
  25393. this._loopCount = - 1;// forget previous loops
  25394. this._startTime = null;// forget scheduling
  25395. return this.stopFading().stopWarping();
  25396. }
  25397. isRunning() {
  25398. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  25399. this._startTime === null && this._mixer._isActiveAction( this );
  25400. }
  25401. // return true when play has been called
  25402. isScheduled() {
  25403. return this._mixer._isActiveAction( this );
  25404. }
  25405. startAt( time ) {
  25406. this._startTime = time;
  25407. return this;
  25408. }
  25409. setLoop( mode, repetitions ) {
  25410. this.loop = mode;
  25411. this.repetitions = repetitions;
  25412. return this;
  25413. }
  25414. // Weight
  25415. // set the weight stopping any scheduled fading
  25416. // although .enabled = false yields an effective weight of zero, this
  25417. // method does *not* change .enabled, because it would be confusing
  25418. setEffectiveWeight( weight ) {
  25419. this.weight = weight;
  25420. // note: same logic as when updated at runtime
  25421. this._effectiveWeight = this.enabled ? weight : 0;
  25422. return this.stopFading();
  25423. }
  25424. // return the weight considering fading and .enabled
  25425. getEffectiveWeight() {
  25426. return this._effectiveWeight;
  25427. }
  25428. fadeIn( duration ) {
  25429. return this._scheduleFading( duration, 0, 1 );
  25430. }
  25431. fadeOut( duration ) {
  25432. return this._scheduleFading( duration, 1, 0 );
  25433. }
  25434. crossFadeFrom( fadeOutAction, duration, warp ) {
  25435. fadeOutAction.fadeOut( duration );
  25436. this.fadeIn( duration );
  25437. if ( warp ) {
  25438. const fadeInDuration = this._clip.duration,
  25439. fadeOutDuration = fadeOutAction._clip.duration,
  25440. startEndRatio = fadeOutDuration / fadeInDuration,
  25441. endStartRatio = fadeInDuration / fadeOutDuration;
  25442. fadeOutAction.warp( 1.0, startEndRatio, duration );
  25443. this.warp( endStartRatio, 1.0, duration );
  25444. }
  25445. return this;
  25446. }
  25447. crossFadeTo( fadeInAction, duration, warp ) {
  25448. return fadeInAction.crossFadeFrom( this, duration, warp );
  25449. }
  25450. stopFading() {
  25451. const weightInterpolant = this._weightInterpolant;
  25452. if ( weightInterpolant !== null ) {
  25453. this._weightInterpolant = null;
  25454. this._mixer._takeBackControlInterpolant( weightInterpolant );
  25455. }
  25456. return this;
  25457. }
  25458. // Time Scale Control
  25459. // set the time scale stopping any scheduled warping
  25460. // although .paused = true yields an effective time scale of zero, this
  25461. // method does *not* change .paused, because it would be confusing
  25462. setEffectiveTimeScale( timeScale ) {
  25463. this.timeScale = timeScale;
  25464. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  25465. return this.stopWarping();
  25466. }
  25467. // return the time scale considering warping and .paused
  25468. getEffectiveTimeScale() {
  25469. return this._effectiveTimeScale;
  25470. }
  25471. setDuration( duration ) {
  25472. this.timeScale = this._clip.duration / duration;
  25473. return this.stopWarping();
  25474. }
  25475. syncWith( action ) {
  25476. this.time = action.time;
  25477. this.timeScale = action.timeScale;
  25478. return this.stopWarping();
  25479. }
  25480. halt( duration ) {
  25481. return this.warp( this._effectiveTimeScale, 0, duration );
  25482. }
  25483. warp( startTimeScale, endTimeScale, duration ) {
  25484. const mixer = this._mixer,
  25485. now = mixer.time,
  25486. timeScale = this.timeScale;
  25487. let interpolant = this._timeScaleInterpolant;
  25488. if ( interpolant === null ) {
  25489. interpolant = mixer._lendControlInterpolant();
  25490. this._timeScaleInterpolant = interpolant;
  25491. }
  25492. const times = interpolant.parameterPositions,
  25493. values = interpolant.sampleValues;
  25494. times[ 0 ] = now;
  25495. times[ 1 ] = now + duration;
  25496. values[ 0 ] = startTimeScale / timeScale;
  25497. values[ 1 ] = endTimeScale / timeScale;
  25498. return this;
  25499. }
  25500. stopWarping() {
  25501. const timeScaleInterpolant = this._timeScaleInterpolant;
  25502. if ( timeScaleInterpolant !== null ) {
  25503. this._timeScaleInterpolant = null;
  25504. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  25505. }
  25506. return this;
  25507. }
  25508. // Object Accessors
  25509. getMixer() {
  25510. return this._mixer;
  25511. }
  25512. getClip() {
  25513. return this._clip;
  25514. }
  25515. getRoot() {
  25516. return this._localRoot || this._mixer._root;
  25517. }
  25518. // Interna
  25519. _update( time, deltaTime, timeDirection, accuIndex ) {
  25520. // called by the mixer
  25521. if ( ! this.enabled ) {
  25522. // call ._updateWeight() to update ._effectiveWeight
  25523. this._updateWeight( time );
  25524. return;
  25525. }
  25526. const startTime = this._startTime;
  25527. if ( startTime !== null ) {
  25528. // check for scheduled start of action
  25529. const timeRunning = ( time - startTime ) * timeDirection;
  25530. if ( timeRunning < 0 || timeDirection === 0 ) {
  25531. return; // yet to come / don't decide when delta = 0
  25532. }
  25533. // start
  25534. this._startTime = null; // unschedule
  25535. deltaTime = timeDirection * timeRunning;
  25536. }
  25537. // apply time scale and advance time
  25538. deltaTime *= this._updateTimeScale( time );
  25539. const clipTime = this._updateTime( deltaTime );
  25540. // note: _updateTime may disable the action resulting in
  25541. // an effective weight of 0
  25542. const weight = this._updateWeight( time );
  25543. if ( weight > 0 ) {
  25544. const interpolants = this._interpolants;
  25545. const propertyMixers = this._propertyBindings;
  25546. switch ( this.blendMode ) {
  25547. case AdditiveAnimationBlendMode:
  25548. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  25549. interpolants[ j ].evaluate( clipTime );
  25550. propertyMixers[ j ].accumulateAdditive( weight );
  25551. }
  25552. break;
  25553. case NormalAnimationBlendMode:
  25554. default:
  25555. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  25556. interpolants[ j ].evaluate( clipTime );
  25557. propertyMixers[ j ].accumulate( accuIndex, weight );
  25558. }
  25559. }
  25560. }
  25561. }
  25562. _updateWeight( time ) {
  25563. let weight = 0;
  25564. if ( this.enabled ) {
  25565. weight = this.weight;
  25566. const interpolant = this._weightInterpolant;
  25567. if ( interpolant !== null ) {
  25568. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  25569. weight *= interpolantValue;
  25570. if ( time > interpolant.parameterPositions[ 1 ] ) {
  25571. this.stopFading();
  25572. if ( interpolantValue === 0 ) {
  25573. // faded out, disable
  25574. this.enabled = false;
  25575. }
  25576. }
  25577. }
  25578. }
  25579. this._effectiveWeight = weight;
  25580. return weight;
  25581. }
  25582. _updateTimeScale( time ) {
  25583. let timeScale = 0;
  25584. if ( ! this.paused ) {
  25585. timeScale = this.timeScale;
  25586. const interpolant = this._timeScaleInterpolant;
  25587. if ( interpolant !== null ) {
  25588. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  25589. timeScale *= interpolantValue;
  25590. if ( time > interpolant.parameterPositions[ 1 ] ) {
  25591. this.stopWarping();
  25592. if ( timeScale === 0 ) {
  25593. // motion has halted, pause
  25594. this.paused = true;
  25595. } else {
  25596. // warp done - apply final time scale
  25597. this.timeScale = timeScale;
  25598. }
  25599. }
  25600. }
  25601. }
  25602. this._effectiveTimeScale = timeScale;
  25603. return timeScale;
  25604. }
  25605. _updateTime( deltaTime ) {
  25606. const duration = this._clip.duration;
  25607. const loop = this.loop;
  25608. let time = this.time + deltaTime;
  25609. let loopCount = this._loopCount;
  25610. const pingPong = ( loop === LoopPingPong );
  25611. if ( deltaTime === 0 ) {
  25612. if ( loopCount === - 1 ) return time;
  25613. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  25614. }
  25615. if ( loop === LoopOnce ) {
  25616. if ( loopCount === - 1 ) {
  25617. // just started
  25618. this._loopCount = 0;
  25619. this._setEndings( true, true, false );
  25620. }
  25621. handle_stop: {
  25622. if ( time >= duration ) {
  25623. time = duration;
  25624. } else if ( time < 0 ) {
  25625. time = 0;
  25626. } else {
  25627. this.time = time;
  25628. break handle_stop;
  25629. }
  25630. if ( this.clampWhenFinished ) this.paused = true;
  25631. else this.enabled = false;
  25632. this.time = time;
  25633. this._mixer.dispatchEvent( {
  25634. type: 'finished', action: this,
  25635. direction: deltaTime < 0 ? - 1 : 1
  25636. } );
  25637. }
  25638. } else { // repetitive Repeat or PingPong
  25639. if ( loopCount === - 1 ) {
  25640. // just started
  25641. if ( deltaTime >= 0 ) {
  25642. loopCount = 0;
  25643. this._setEndings( true, this.repetitions === 0, pingPong );
  25644. } else {
  25645. // when looping in reverse direction, the initial
  25646. // transition through zero counts as a repetition,
  25647. // so leave loopCount at -1
  25648. this._setEndings( this.repetitions === 0, true, pingPong );
  25649. }
  25650. }
  25651. if ( time >= duration || time < 0 ) {
  25652. // wrap around
  25653. const loopDelta = Math.floor( time / duration ); // signed
  25654. time -= duration * loopDelta;
  25655. loopCount += Math.abs( loopDelta );
  25656. const pending = this.repetitions - loopCount;
  25657. if ( pending <= 0 ) {
  25658. // have to stop (switch state, clamp time, fire event)
  25659. if ( this.clampWhenFinished ) this.paused = true;
  25660. else this.enabled = false;
  25661. time = deltaTime > 0 ? duration : 0;
  25662. this.time = time;
  25663. this._mixer.dispatchEvent( {
  25664. type: 'finished', action: this,
  25665. direction: deltaTime > 0 ? 1 : - 1
  25666. } );
  25667. } else {
  25668. // keep running
  25669. if ( pending === 1 ) {
  25670. // entering the last round
  25671. const atStart = deltaTime < 0;
  25672. this._setEndings( atStart, ! atStart, pingPong );
  25673. } else {
  25674. this._setEndings( false, false, pingPong );
  25675. }
  25676. this._loopCount = loopCount;
  25677. this.time = time;
  25678. this._mixer.dispatchEvent( {
  25679. type: 'loop', action: this, loopDelta: loopDelta
  25680. } );
  25681. }
  25682. } else {
  25683. this.time = time;
  25684. }
  25685. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  25686. // invert time for the "pong round"
  25687. return duration - time;
  25688. }
  25689. }
  25690. return time;
  25691. }
  25692. _setEndings( atStart, atEnd, pingPong ) {
  25693. const settings = this._interpolantSettings;
  25694. if ( pingPong ) {
  25695. settings.endingStart = ZeroSlopeEnding;
  25696. settings.endingEnd = ZeroSlopeEnding;
  25697. } else {
  25698. // assuming for LoopOnce atStart == atEnd == true
  25699. if ( atStart ) {
  25700. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  25701. } else {
  25702. settings.endingStart = WrapAroundEnding;
  25703. }
  25704. if ( atEnd ) {
  25705. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  25706. } else {
  25707. settings.endingEnd = WrapAroundEnding;
  25708. }
  25709. }
  25710. }
  25711. _scheduleFading( duration, weightNow, weightThen ) {
  25712. const mixer = this._mixer, now = mixer.time;
  25713. let interpolant = this._weightInterpolant;
  25714. if ( interpolant === null ) {
  25715. interpolant = mixer._lendControlInterpolant();
  25716. this._weightInterpolant = interpolant;
  25717. }
  25718. const times = interpolant.parameterPositions,
  25719. values = interpolant.sampleValues;
  25720. times[ 0 ] = now;
  25721. values[ 0 ] = weightNow;
  25722. times[ 1 ] = now + duration;
  25723. values[ 1 ] = weightThen;
  25724. return this;
  25725. }
  25726. }
  25727. class AnimationMixer extends EventDispatcher {
  25728. constructor( root ) {
  25729. super();
  25730. this._root = root;
  25731. this._initMemoryManager();
  25732. this._accuIndex = 0;
  25733. this.time = 0;
  25734. this.timeScale = 1.0;
  25735. }
  25736. _bindAction( action, prototypeAction ) {
  25737. const root = action._localRoot || this._root,
  25738. tracks = action._clip.tracks,
  25739. nTracks = tracks.length,
  25740. bindings = action._propertyBindings,
  25741. interpolants = action._interpolants,
  25742. rootUuid = root.uuid,
  25743. bindingsByRoot = this._bindingsByRootAndName;
  25744. let bindingsByName = bindingsByRoot[ rootUuid ];
  25745. if ( bindingsByName === undefined ) {
  25746. bindingsByName = {};
  25747. bindingsByRoot[ rootUuid ] = bindingsByName;
  25748. }
  25749. for ( let i = 0; i !== nTracks; ++ i ) {
  25750. const track = tracks[ i ],
  25751. trackName = track.name;
  25752. let binding = bindingsByName[ trackName ];
  25753. if ( binding !== undefined ) {
  25754. bindings[ i ] = binding;
  25755. } else {
  25756. binding = bindings[ i ];
  25757. if ( binding !== undefined ) {
  25758. // existing binding, make sure the cache knows
  25759. if ( binding._cacheIndex === null ) {
  25760. ++ binding.referenceCount;
  25761. this._addInactiveBinding( binding, rootUuid, trackName );
  25762. }
  25763. continue;
  25764. }
  25765. const path = prototypeAction && prototypeAction.
  25766. _propertyBindings[ i ].binding.parsedPath;
  25767. binding = new PropertyMixer(
  25768. PropertyBinding.create( root, trackName, path ),
  25769. track.ValueTypeName, track.getValueSize() );
  25770. ++ binding.referenceCount;
  25771. this._addInactiveBinding( binding, rootUuid, trackName );
  25772. bindings[ i ] = binding;
  25773. }
  25774. interpolants[ i ].resultBuffer = binding.buffer;
  25775. }
  25776. }
  25777. _activateAction( action ) {
  25778. if ( ! this._isActiveAction( action ) ) {
  25779. if ( action._cacheIndex === null ) {
  25780. // this action has been forgotten by the cache, but the user
  25781. // appears to be still using it -> rebind
  25782. const rootUuid = ( action._localRoot || this._root ).uuid,
  25783. clipUuid = action._clip.uuid,
  25784. actionsForClip = this._actionsByClip[ clipUuid ];
  25785. this._bindAction( action,
  25786. actionsForClip && actionsForClip.knownActions[ 0 ] );
  25787. this._addInactiveAction( action, clipUuid, rootUuid );
  25788. }
  25789. const bindings = action._propertyBindings;
  25790. // increment reference counts / sort out state
  25791. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  25792. const binding = bindings[ i ];
  25793. if ( binding.useCount ++ === 0 ) {
  25794. this._lendBinding( binding );
  25795. binding.saveOriginalState();
  25796. }
  25797. }
  25798. this._lendAction( action );
  25799. }
  25800. }
  25801. _deactivateAction( action ) {
  25802. if ( this._isActiveAction( action ) ) {
  25803. const bindings = action._propertyBindings;
  25804. // decrement reference counts / sort out state
  25805. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  25806. const binding = bindings[ i ];
  25807. if ( -- binding.useCount === 0 ) {
  25808. binding.restoreOriginalState();
  25809. this._takeBackBinding( binding );
  25810. }
  25811. }
  25812. this._takeBackAction( action );
  25813. }
  25814. }
  25815. // Memory manager
  25816. _initMemoryManager() {
  25817. this._actions = []; // 'nActiveActions' followed by inactive ones
  25818. this._nActiveActions = 0;
  25819. this._actionsByClip = {};
  25820. // inside:
  25821. // {
  25822. // knownActions: Array< AnimationAction > - used as prototypes
  25823. // actionByRoot: AnimationAction - lookup
  25824. // }
  25825. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  25826. this._nActiveBindings = 0;
  25827. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  25828. this._controlInterpolants = []; // same game as above
  25829. this._nActiveControlInterpolants = 0;
  25830. const scope = this;
  25831. this.stats = {
  25832. actions: {
  25833. get total() {
  25834. return scope._actions.length;
  25835. },
  25836. get inUse() {
  25837. return scope._nActiveActions;
  25838. }
  25839. },
  25840. bindings: {
  25841. get total() {
  25842. return scope._bindings.length;
  25843. },
  25844. get inUse() {
  25845. return scope._nActiveBindings;
  25846. }
  25847. },
  25848. controlInterpolants: {
  25849. get total() {
  25850. return scope._controlInterpolants.length;
  25851. },
  25852. get inUse() {
  25853. return scope._nActiveControlInterpolants;
  25854. }
  25855. }
  25856. };
  25857. }
  25858. // Memory management for AnimationAction objects
  25859. _isActiveAction( action ) {
  25860. const index = action._cacheIndex;
  25861. return index !== null && index < this._nActiveActions;
  25862. }
  25863. _addInactiveAction( action, clipUuid, rootUuid ) {
  25864. const actions = this._actions,
  25865. actionsByClip = this._actionsByClip;
  25866. let actionsForClip = actionsByClip[ clipUuid ];
  25867. if ( actionsForClip === undefined ) {
  25868. actionsForClip = {
  25869. knownActions: [ action ],
  25870. actionByRoot: {}
  25871. };
  25872. action._byClipCacheIndex = 0;
  25873. actionsByClip[ clipUuid ] = actionsForClip;
  25874. } else {
  25875. const knownActions = actionsForClip.knownActions;
  25876. action._byClipCacheIndex = knownActions.length;
  25877. knownActions.push( action );
  25878. }
  25879. action._cacheIndex = actions.length;
  25880. actions.push( action );
  25881. actionsForClip.actionByRoot[ rootUuid ] = action;
  25882. }
  25883. _removeInactiveAction( action ) {
  25884. const actions = this._actions,
  25885. lastInactiveAction = actions[ actions.length - 1 ],
  25886. cacheIndex = action._cacheIndex;
  25887. lastInactiveAction._cacheIndex = cacheIndex;
  25888. actions[ cacheIndex ] = lastInactiveAction;
  25889. actions.pop();
  25890. action._cacheIndex = null;
  25891. const clipUuid = action._clip.uuid,
  25892. actionsByClip = this._actionsByClip,
  25893. actionsForClip = actionsByClip[ clipUuid ],
  25894. knownActionsForClip = actionsForClip.knownActions,
  25895. lastKnownAction =
  25896. knownActionsForClip[ knownActionsForClip.length - 1 ],
  25897. byClipCacheIndex = action._byClipCacheIndex;
  25898. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  25899. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  25900. knownActionsForClip.pop();
  25901. action._byClipCacheIndex = null;
  25902. const actionByRoot = actionsForClip.actionByRoot,
  25903. rootUuid = ( action._localRoot || this._root ).uuid;
  25904. delete actionByRoot[ rootUuid ];
  25905. if ( knownActionsForClip.length === 0 ) {
  25906. delete actionsByClip[ clipUuid ];
  25907. }
  25908. this._removeInactiveBindingsForAction( action );
  25909. }
  25910. _removeInactiveBindingsForAction( action ) {
  25911. const bindings = action._propertyBindings;
  25912. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  25913. const binding = bindings[ i ];
  25914. if ( -- binding.referenceCount === 0 ) {
  25915. this._removeInactiveBinding( binding );
  25916. }
  25917. }
  25918. }
  25919. _lendAction( action ) {
  25920. // [ active actions | inactive actions ]
  25921. // [ active actions >| inactive actions ]
  25922. // s a
  25923. // <-swap->
  25924. // a s
  25925. const actions = this._actions,
  25926. prevIndex = action._cacheIndex,
  25927. lastActiveIndex = this._nActiveActions ++,
  25928. firstInactiveAction = actions[ lastActiveIndex ];
  25929. action._cacheIndex = lastActiveIndex;
  25930. actions[ lastActiveIndex ] = action;
  25931. firstInactiveAction._cacheIndex = prevIndex;
  25932. actions[ prevIndex ] = firstInactiveAction;
  25933. }
  25934. _takeBackAction( action ) {
  25935. // [ active actions | inactive actions ]
  25936. // [ active actions |< inactive actions ]
  25937. // a s
  25938. // <-swap->
  25939. // s a
  25940. const actions = this._actions,
  25941. prevIndex = action._cacheIndex,
  25942. firstInactiveIndex = -- this._nActiveActions,
  25943. lastActiveAction = actions[ firstInactiveIndex ];
  25944. action._cacheIndex = firstInactiveIndex;
  25945. actions[ firstInactiveIndex ] = action;
  25946. lastActiveAction._cacheIndex = prevIndex;
  25947. actions[ prevIndex ] = lastActiveAction;
  25948. }
  25949. // Memory management for PropertyMixer objects
  25950. _addInactiveBinding( binding, rootUuid, trackName ) {
  25951. const bindingsByRoot = this._bindingsByRootAndName,
  25952. bindings = this._bindings;
  25953. let bindingByName = bindingsByRoot[ rootUuid ];
  25954. if ( bindingByName === undefined ) {
  25955. bindingByName = {};
  25956. bindingsByRoot[ rootUuid ] = bindingByName;
  25957. }
  25958. bindingByName[ trackName ] = binding;
  25959. binding._cacheIndex = bindings.length;
  25960. bindings.push( binding );
  25961. }
  25962. _removeInactiveBinding( binding ) {
  25963. const bindings = this._bindings,
  25964. propBinding = binding.binding,
  25965. rootUuid = propBinding.rootNode.uuid,
  25966. trackName = propBinding.path,
  25967. bindingsByRoot = this._bindingsByRootAndName,
  25968. bindingByName = bindingsByRoot[ rootUuid ],
  25969. lastInactiveBinding = bindings[ bindings.length - 1 ],
  25970. cacheIndex = binding._cacheIndex;
  25971. lastInactiveBinding._cacheIndex = cacheIndex;
  25972. bindings[ cacheIndex ] = lastInactiveBinding;
  25973. bindings.pop();
  25974. delete bindingByName[ trackName ];
  25975. if ( Object.keys( bindingByName ).length === 0 ) {
  25976. delete bindingsByRoot[ rootUuid ];
  25977. }
  25978. }
  25979. _lendBinding( binding ) {
  25980. const bindings = this._bindings,
  25981. prevIndex = binding._cacheIndex,
  25982. lastActiveIndex = this._nActiveBindings ++,
  25983. firstInactiveBinding = bindings[ lastActiveIndex ];
  25984. binding._cacheIndex = lastActiveIndex;
  25985. bindings[ lastActiveIndex ] = binding;
  25986. firstInactiveBinding._cacheIndex = prevIndex;
  25987. bindings[ prevIndex ] = firstInactiveBinding;
  25988. }
  25989. _takeBackBinding( binding ) {
  25990. const bindings = this._bindings,
  25991. prevIndex = binding._cacheIndex,
  25992. firstInactiveIndex = -- this._nActiveBindings,
  25993. lastActiveBinding = bindings[ firstInactiveIndex ];
  25994. binding._cacheIndex = firstInactiveIndex;
  25995. bindings[ firstInactiveIndex ] = binding;
  25996. lastActiveBinding._cacheIndex = prevIndex;
  25997. bindings[ prevIndex ] = lastActiveBinding;
  25998. }
  25999. // Memory management of Interpolants for weight and time scale
  26000. _lendControlInterpolant() {
  26001. const interpolants = this._controlInterpolants,
  26002. lastActiveIndex = this._nActiveControlInterpolants ++;
  26003. let interpolant = interpolants[ lastActiveIndex ];
  26004. if ( interpolant === undefined ) {
  26005. interpolant = new LinearInterpolant(
  26006. new Float32Array( 2 ), new Float32Array( 2 ),
  26007. 1, this._controlInterpolantsResultBuffer );
  26008. interpolant.__cacheIndex = lastActiveIndex;
  26009. interpolants[ lastActiveIndex ] = interpolant;
  26010. }
  26011. return interpolant;
  26012. }
  26013. _takeBackControlInterpolant( interpolant ) {
  26014. const interpolants = this._controlInterpolants,
  26015. prevIndex = interpolant.__cacheIndex,
  26016. firstInactiveIndex = -- this._nActiveControlInterpolants,
  26017. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  26018. interpolant.__cacheIndex = firstInactiveIndex;
  26019. interpolants[ firstInactiveIndex ] = interpolant;
  26020. lastActiveInterpolant.__cacheIndex = prevIndex;
  26021. interpolants[ prevIndex ] = lastActiveInterpolant;
  26022. }
  26023. // return an action for a clip optionally using a custom root target
  26024. // object (this method allocates a lot of dynamic memory in case a
  26025. // previously unknown clip/root combination is specified)
  26026. clipAction( clip, optionalRoot, blendMode ) {
  26027. const root = optionalRoot || this._root,
  26028. rootUuid = root.uuid;
  26029. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  26030. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  26031. const actionsForClip = this._actionsByClip[ clipUuid ];
  26032. let prototypeAction = null;
  26033. if ( blendMode === undefined ) {
  26034. if ( clipObject !== null ) {
  26035. blendMode = clipObject.blendMode;
  26036. } else {
  26037. blendMode = NormalAnimationBlendMode;
  26038. }
  26039. }
  26040. if ( actionsForClip !== undefined ) {
  26041. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  26042. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  26043. return existingAction;
  26044. }
  26045. // we know the clip, so we don't have to parse all
  26046. // the bindings again but can just copy
  26047. prototypeAction = actionsForClip.knownActions[ 0 ];
  26048. // also, take the clip from the prototype action
  26049. if ( clipObject === null )
  26050. clipObject = prototypeAction._clip;
  26051. }
  26052. // clip must be known when specified via string
  26053. if ( clipObject === null ) return null;
  26054. // allocate all resources required to run it
  26055. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  26056. this._bindAction( newAction, prototypeAction );
  26057. // and make the action known to the memory manager
  26058. this._addInactiveAction( newAction, clipUuid, rootUuid );
  26059. return newAction;
  26060. }
  26061. // get an existing action
  26062. existingAction( clip, optionalRoot ) {
  26063. const root = optionalRoot || this._root,
  26064. rootUuid = root.uuid,
  26065. clipObject = typeof clip === 'string' ?
  26066. AnimationClip.findByName( root, clip ) : clip,
  26067. clipUuid = clipObject ? clipObject.uuid : clip,
  26068. actionsForClip = this._actionsByClip[ clipUuid ];
  26069. if ( actionsForClip !== undefined ) {
  26070. return actionsForClip.actionByRoot[ rootUuid ] || null;
  26071. }
  26072. return null;
  26073. }
  26074. // deactivates all previously scheduled actions
  26075. stopAllAction() {
  26076. const actions = this._actions,
  26077. nActions = this._nActiveActions;
  26078. for ( let i = nActions - 1; i >= 0; -- i ) {
  26079. actions[ i ].stop();
  26080. }
  26081. return this;
  26082. }
  26083. // advance the time and update apply the animation
  26084. update( deltaTime ) {
  26085. deltaTime *= this.timeScale;
  26086. const actions = this._actions,
  26087. nActions = this._nActiveActions,
  26088. time = this.time += deltaTime,
  26089. timeDirection = Math.sign( deltaTime ),
  26090. accuIndex = this._accuIndex ^= 1;
  26091. // run active actions
  26092. for ( let i = 0; i !== nActions; ++ i ) {
  26093. const action = actions[ i ];
  26094. action._update( time, deltaTime, timeDirection, accuIndex );
  26095. }
  26096. // update scene graph
  26097. const bindings = this._bindings,
  26098. nBindings = this._nActiveBindings;
  26099. for ( let i = 0; i !== nBindings; ++ i ) {
  26100. bindings[ i ].apply( accuIndex );
  26101. }
  26102. return this;
  26103. }
  26104. // Allows you to seek to a specific time in an animation.
  26105. setTime( timeInSeconds ) {
  26106. this.time = 0; // Zero out time attribute for AnimationMixer object;
  26107. for ( let i = 0; i < this._actions.length; i ++ ) {
  26108. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  26109. }
  26110. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  26111. }
  26112. // return this mixer's root target object
  26113. getRoot() {
  26114. return this._root;
  26115. }
  26116. // free all resources specific to a particular clip
  26117. uncacheClip( clip ) {
  26118. const actions = this._actions,
  26119. clipUuid = clip.uuid,
  26120. actionsByClip = this._actionsByClip,
  26121. actionsForClip = actionsByClip[ clipUuid ];
  26122. if ( actionsForClip !== undefined ) {
  26123. // note: just calling _removeInactiveAction would mess up the
  26124. // iteration state and also require updating the state we can
  26125. // just throw away
  26126. const actionsToRemove = actionsForClip.knownActions;
  26127. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  26128. const action = actionsToRemove[ i ];
  26129. this._deactivateAction( action );
  26130. const cacheIndex = action._cacheIndex,
  26131. lastInactiveAction = actions[ actions.length - 1 ];
  26132. action._cacheIndex = null;
  26133. action._byClipCacheIndex = null;
  26134. lastInactiveAction._cacheIndex = cacheIndex;
  26135. actions[ cacheIndex ] = lastInactiveAction;
  26136. actions.pop();
  26137. this._removeInactiveBindingsForAction( action );
  26138. }
  26139. delete actionsByClip[ clipUuid ];
  26140. }
  26141. }
  26142. // free all resources specific to a particular root target object
  26143. uncacheRoot( root ) {
  26144. const rootUuid = root.uuid,
  26145. actionsByClip = this._actionsByClip;
  26146. for ( const clipUuid in actionsByClip ) {
  26147. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  26148. action = actionByRoot[ rootUuid ];
  26149. if ( action !== undefined ) {
  26150. this._deactivateAction( action );
  26151. this._removeInactiveAction( action );
  26152. }
  26153. }
  26154. const bindingsByRoot = this._bindingsByRootAndName,
  26155. bindingByName = bindingsByRoot[ rootUuid ];
  26156. if ( bindingByName !== undefined ) {
  26157. for ( const trackName in bindingByName ) {
  26158. const binding = bindingByName[ trackName ];
  26159. binding.restoreOriginalState();
  26160. this._removeInactiveBinding( binding );
  26161. }
  26162. }
  26163. }
  26164. // remove a targeted clip from the cache
  26165. uncacheAction( clip, optionalRoot ) {
  26166. const action = this.existingAction( clip, optionalRoot );
  26167. if ( action !== null ) {
  26168. this._deactivateAction( action );
  26169. this._removeInactiveAction( action );
  26170. }
  26171. }
  26172. }
  26173. AnimationMixer.prototype._controlInterpolantsResultBuffer = new Float32Array( 1 );
  26174. class Uniform {
  26175. constructor( value ) {
  26176. if ( typeof value === 'string' ) {
  26177. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  26178. value = arguments[ 1 ];
  26179. }
  26180. this.value = value;
  26181. }
  26182. clone() {
  26183. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  26184. }
  26185. }
  26186. function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) {
  26187. InterleavedBuffer.call( this, array, stride );
  26188. this.meshPerAttribute = meshPerAttribute || 1;
  26189. }
  26190. InstancedInterleavedBuffer.prototype = Object.assign( Object.create( InterleavedBuffer.prototype ), {
  26191. constructor: InstancedInterleavedBuffer,
  26192. isInstancedInterleavedBuffer: true,
  26193. copy: function ( source ) {
  26194. InterleavedBuffer.prototype.copy.call( this, source );
  26195. this.meshPerAttribute = source.meshPerAttribute;
  26196. return this;
  26197. },
  26198. clone: function ( data ) {
  26199. const ib = InterleavedBuffer.prototype.clone.call( this, data );
  26200. ib.meshPerAttribute = this.meshPerAttribute;
  26201. return ib;
  26202. },
  26203. toJSON: function ( data ) {
  26204. const json = InterleavedBuffer.prototype.toJSON.call( this, data );
  26205. json.isInstancedInterleavedBuffer = true;
  26206. json.meshPerAttribute = this.meshPerAttribute;
  26207. return json;
  26208. }
  26209. } );
  26210. function GLBufferAttribute( buffer, type, itemSize, elementSize, count ) {
  26211. this.buffer = buffer;
  26212. this.type = type;
  26213. this.itemSize = itemSize;
  26214. this.elementSize = elementSize;
  26215. this.count = count;
  26216. this.version = 0;
  26217. }
  26218. Object.defineProperty( GLBufferAttribute.prototype, 'needsUpdate', {
  26219. set: function ( value ) {
  26220. if ( value === true ) this.version ++;
  26221. }
  26222. } );
  26223. Object.assign( GLBufferAttribute.prototype, {
  26224. isGLBufferAttribute: true,
  26225. setBuffer: function ( buffer ) {
  26226. this.buffer = buffer;
  26227. return this;
  26228. },
  26229. setType: function ( type, elementSize ) {
  26230. this.type = type;
  26231. this.elementSize = elementSize;
  26232. return this;
  26233. },
  26234. setItemSize: function ( itemSize ) {
  26235. this.itemSize = itemSize;
  26236. return this;
  26237. },
  26238. setCount: function ( count ) {
  26239. this.count = count;
  26240. return this;
  26241. },
  26242. } );
  26243. function Raycaster( origin, direction, near = 0, far = Infinity ) {
  26244. this.ray = new Ray( origin, direction );
  26245. // direction is assumed to be normalized (for accurate distance calculations)
  26246. this.near = near;
  26247. this.far = far;
  26248. this.camera = null;
  26249. this.layers = new Layers();
  26250. this.params = {
  26251. Mesh: {},
  26252. Line: { threshold: 1 },
  26253. LOD: {},
  26254. Points: { threshold: 1 },
  26255. Sprite: {}
  26256. };
  26257. Object.defineProperties( this.params, {
  26258. PointCloud: {
  26259. get: function () {
  26260. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  26261. return this.Points;
  26262. }
  26263. }
  26264. } );
  26265. }
  26266. function ascSort( a, b ) {
  26267. return a.distance - b.distance;
  26268. }
  26269. function intersectObject( object, raycaster, intersects, recursive ) {
  26270. if ( object.layers.test( raycaster.layers ) ) {
  26271. object.raycast( raycaster, intersects );
  26272. }
  26273. if ( recursive === true ) {
  26274. const children = object.children;
  26275. for ( let i = 0, l = children.length; i < l; i ++ ) {
  26276. intersectObject( children[ i ], raycaster, intersects, true );
  26277. }
  26278. }
  26279. }
  26280. Object.assign( Raycaster.prototype, {
  26281. set: function ( origin, direction ) {
  26282. // direction is assumed to be normalized (for accurate distance calculations)
  26283. this.ray.set( origin, direction );
  26284. },
  26285. setFromCamera: function ( coords, camera ) {
  26286. if ( camera && camera.isPerspectiveCamera ) {
  26287. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  26288. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  26289. this.camera = camera;
  26290. } else if ( camera && camera.isOrthographicCamera ) {
  26291. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  26292. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  26293. this.camera = camera;
  26294. } else {
  26295. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  26296. }
  26297. },
  26298. intersectObject: function ( object, recursive = false, intersects = [] ) {
  26299. intersectObject( object, this, intersects, recursive );
  26300. intersects.sort( ascSort );
  26301. return intersects;
  26302. },
  26303. intersectObjects: function ( objects, recursive = false, intersects = [] ) {
  26304. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  26305. intersectObject( objects[ i ], this, intersects, recursive );
  26306. }
  26307. intersects.sort( ascSort );
  26308. return intersects;
  26309. }
  26310. } );
  26311. /**
  26312. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  26313. *
  26314. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  26315. * The azimuthal angle (theta) is measured from the positive z-axis.
  26316. */
  26317. class Spherical {
  26318. constructor( radius = 1, phi = 0, theta = 0 ) {
  26319. this.radius = radius;
  26320. this.phi = phi; // polar angle
  26321. this.theta = theta; // azimuthal angle
  26322. return this;
  26323. }
  26324. set( radius, phi, theta ) {
  26325. this.radius = radius;
  26326. this.phi = phi;
  26327. this.theta = theta;
  26328. return this;
  26329. }
  26330. copy( other ) {
  26331. this.radius = other.radius;
  26332. this.phi = other.phi;
  26333. this.theta = other.theta;
  26334. return this;
  26335. }
  26336. // restrict phi to be betwee EPS and PI-EPS
  26337. makeSafe() {
  26338. const EPS = 0.000001;
  26339. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  26340. return this;
  26341. }
  26342. setFromVector3( v ) {
  26343. return this.setFromCartesianCoords( v.x, v.y, v.z );
  26344. }
  26345. setFromCartesianCoords( x, y, z ) {
  26346. this.radius = Math.sqrt( x * x + y * y + z * z );
  26347. if ( this.radius === 0 ) {
  26348. this.theta = 0;
  26349. this.phi = 0;
  26350. } else {
  26351. this.theta = Math.atan2( x, z );
  26352. this.phi = Math.acos( MathUtils.clamp( y / this.radius, - 1, 1 ) );
  26353. }
  26354. return this;
  26355. }
  26356. clone() {
  26357. return new this.constructor().copy( this );
  26358. }
  26359. }
  26360. /**
  26361. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  26362. */
  26363. class Cylindrical {
  26364. constructor( radius = 1, theta = 0, y = 0 ) {
  26365. this.radius = radius; // distance from the origin to a point in the x-z plane
  26366. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  26367. this.y = y; // height above the x-z plane
  26368. return this;
  26369. }
  26370. set( radius, theta, y ) {
  26371. this.radius = radius;
  26372. this.theta = theta;
  26373. this.y = y;
  26374. return this;
  26375. }
  26376. copy( other ) {
  26377. this.radius = other.radius;
  26378. this.theta = other.theta;
  26379. this.y = other.y;
  26380. return this;
  26381. }
  26382. setFromVector3( v ) {
  26383. return this.setFromCartesianCoords( v.x, v.y, v.z );
  26384. }
  26385. setFromCartesianCoords( x, y, z ) {
  26386. this.radius = Math.sqrt( x * x + z * z );
  26387. this.theta = Math.atan2( x, z );
  26388. this.y = y;
  26389. return this;
  26390. }
  26391. clone() {
  26392. return new this.constructor().copy( this );
  26393. }
  26394. }
  26395. const _vector$8 = /*@__PURE__*/ new Vector2();
  26396. class Box2 {
  26397. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  26398. this.min = min;
  26399. this.max = max;
  26400. }
  26401. set( min, max ) {
  26402. this.min.copy( min );
  26403. this.max.copy( max );
  26404. return this;
  26405. }
  26406. setFromPoints( points ) {
  26407. this.makeEmpty();
  26408. for ( let i = 0, il = points.length; i < il; i ++ ) {
  26409. this.expandByPoint( points[ i ] );
  26410. }
  26411. return this;
  26412. }
  26413. setFromCenterAndSize( center, size ) {
  26414. const halfSize = _vector$8.copy( size ).multiplyScalar( 0.5 );
  26415. this.min.copy( center ).sub( halfSize );
  26416. this.max.copy( center ).add( halfSize );
  26417. return this;
  26418. }
  26419. clone() {
  26420. return new this.constructor().copy( this );
  26421. }
  26422. copy( box ) {
  26423. this.min.copy( box.min );
  26424. this.max.copy( box.max );
  26425. return this;
  26426. }
  26427. makeEmpty() {
  26428. this.min.x = this.min.y = + Infinity;
  26429. this.max.x = this.max.y = - Infinity;
  26430. return this;
  26431. }
  26432. isEmpty() {
  26433. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  26434. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  26435. }
  26436. getCenter( target ) {
  26437. if ( target === undefined ) {
  26438. console.warn( 'THREE.Box2: .getCenter() target is now required' );
  26439. target = new Vector2();
  26440. }
  26441. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  26442. }
  26443. getSize( target ) {
  26444. if ( target === undefined ) {
  26445. console.warn( 'THREE.Box2: .getSize() target is now required' );
  26446. target = new Vector2();
  26447. }
  26448. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  26449. }
  26450. expandByPoint( point ) {
  26451. this.min.min( point );
  26452. this.max.max( point );
  26453. return this;
  26454. }
  26455. expandByVector( vector ) {
  26456. this.min.sub( vector );
  26457. this.max.add( vector );
  26458. return this;
  26459. }
  26460. expandByScalar( scalar ) {
  26461. this.min.addScalar( - scalar );
  26462. this.max.addScalar( scalar );
  26463. return this;
  26464. }
  26465. containsPoint( point ) {
  26466. return point.x < this.min.x || point.x > this.max.x ||
  26467. point.y < this.min.y || point.y > this.max.y ? false : true;
  26468. }
  26469. containsBox( box ) {
  26470. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  26471. this.min.y <= box.min.y && box.max.y <= this.max.y;
  26472. }
  26473. getParameter( point, target ) {
  26474. // This can potentially have a divide by zero if the box
  26475. // has a size dimension of 0.
  26476. if ( target === undefined ) {
  26477. console.warn( 'THREE.Box2: .getParameter() target is now required' );
  26478. target = new Vector2();
  26479. }
  26480. return target.set(
  26481. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  26482. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  26483. );
  26484. }
  26485. intersectsBox( box ) {
  26486. // using 4 splitting planes to rule out intersections
  26487. return box.max.x < this.min.x || box.min.x > this.max.x ||
  26488. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  26489. }
  26490. clampPoint( point, target ) {
  26491. if ( target === undefined ) {
  26492. console.warn( 'THREE.Box2: .clampPoint() target is now required' );
  26493. target = new Vector2();
  26494. }
  26495. return target.copy( point ).clamp( this.min, this.max );
  26496. }
  26497. distanceToPoint( point ) {
  26498. const clampedPoint = _vector$8.copy( point ).clamp( this.min, this.max );
  26499. return clampedPoint.sub( point ).length();
  26500. }
  26501. intersect( box ) {
  26502. this.min.max( box.min );
  26503. this.max.min( box.max );
  26504. return this;
  26505. }
  26506. union( box ) {
  26507. this.min.min( box.min );
  26508. this.max.max( box.max );
  26509. return this;
  26510. }
  26511. translate( offset ) {
  26512. this.min.add( offset );
  26513. this.max.add( offset );
  26514. return this;
  26515. }
  26516. equals( box ) {
  26517. return box.min.equals( this.min ) && box.max.equals( this.max );
  26518. }
  26519. }
  26520. Box2.prototype.isBox2 = true;
  26521. const _startP = /*@__PURE__*/ new Vector3();
  26522. const _startEnd = /*@__PURE__*/ new Vector3();
  26523. class Line3 {
  26524. constructor( start = new Vector3(), end = new Vector3() ) {
  26525. this.start = start;
  26526. this.end = end;
  26527. }
  26528. set( start, end ) {
  26529. this.start.copy( start );
  26530. this.end.copy( end );
  26531. return this;
  26532. }
  26533. copy( line ) {
  26534. this.start.copy( line.start );
  26535. this.end.copy( line.end );
  26536. return this;
  26537. }
  26538. getCenter( target ) {
  26539. if ( target === undefined ) {
  26540. console.warn( 'THREE.Line3: .getCenter() target is now required' );
  26541. target = new Vector3();
  26542. }
  26543. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  26544. }
  26545. delta( target ) {
  26546. if ( target === undefined ) {
  26547. console.warn( 'THREE.Line3: .delta() target is now required' );
  26548. target = new Vector3();
  26549. }
  26550. return target.subVectors( this.end, this.start );
  26551. }
  26552. distanceSq() {
  26553. return this.start.distanceToSquared( this.end );
  26554. }
  26555. distance() {
  26556. return this.start.distanceTo( this.end );
  26557. }
  26558. at( t, target ) {
  26559. if ( target === undefined ) {
  26560. console.warn( 'THREE.Line3: .at() target is now required' );
  26561. target = new Vector3();
  26562. }
  26563. return this.delta( target ).multiplyScalar( t ).add( this.start );
  26564. }
  26565. closestPointToPointParameter( point, clampToLine ) {
  26566. _startP.subVectors( point, this.start );
  26567. _startEnd.subVectors( this.end, this.start );
  26568. const startEnd2 = _startEnd.dot( _startEnd );
  26569. const startEnd_startP = _startEnd.dot( _startP );
  26570. let t = startEnd_startP / startEnd2;
  26571. if ( clampToLine ) {
  26572. t = MathUtils.clamp( t, 0, 1 );
  26573. }
  26574. return t;
  26575. }
  26576. closestPointToPoint( point, clampToLine, target ) {
  26577. const t = this.closestPointToPointParameter( point, clampToLine );
  26578. if ( target === undefined ) {
  26579. console.warn( 'THREE.Line3: .closestPointToPoint() target is now required' );
  26580. target = new Vector3();
  26581. }
  26582. return this.delta( target ).multiplyScalar( t ).add( this.start );
  26583. }
  26584. applyMatrix4( matrix ) {
  26585. this.start.applyMatrix4( matrix );
  26586. this.end.applyMatrix4( matrix );
  26587. return this;
  26588. }
  26589. equals( line ) {
  26590. return line.start.equals( this.start ) && line.end.equals( this.end );
  26591. }
  26592. clone() {
  26593. return new this.constructor().copy( this );
  26594. }
  26595. }
  26596. function ImmediateRenderObject( material ) {
  26597. Object3D.call( this );
  26598. this.material = material;
  26599. this.render = function ( /* renderCallback */ ) {};
  26600. this.hasPositions = false;
  26601. this.hasNormals = false;
  26602. this.hasColors = false;
  26603. this.hasUvs = false;
  26604. this.positionArray = null;
  26605. this.normalArray = null;
  26606. this.colorArray = null;
  26607. this.uvArray = null;
  26608. this.count = 0;
  26609. }
  26610. ImmediateRenderObject.prototype = Object.create( Object3D.prototype );
  26611. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  26612. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  26613. const _vector$9 = /*@__PURE__*/ new Vector3();
  26614. class SpotLightHelper extends Object3D {
  26615. constructor( light, color ) {
  26616. super();
  26617. this.light = light;
  26618. this.light.updateMatrixWorld();
  26619. this.matrix = light.matrixWorld;
  26620. this.matrixAutoUpdate = false;
  26621. this.color = color;
  26622. const geometry = new BufferGeometry();
  26623. const positions = [
  26624. 0, 0, 0, 0, 0, 1,
  26625. 0, 0, 0, 1, 0, 1,
  26626. 0, 0, 0, - 1, 0, 1,
  26627. 0, 0, 0, 0, 1, 1,
  26628. 0, 0, 0, 0, - 1, 1
  26629. ];
  26630. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  26631. const p1 = ( i / l ) * Math.PI * 2;
  26632. const p2 = ( j / l ) * Math.PI * 2;
  26633. positions.push(
  26634. Math.cos( p1 ), Math.sin( p1 ), 1,
  26635. Math.cos( p2 ), Math.sin( p2 ), 1
  26636. );
  26637. }
  26638. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  26639. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  26640. this.cone = new LineSegments( geometry, material );
  26641. this.add( this.cone );
  26642. this.update();
  26643. }
  26644. dispose() {
  26645. this.cone.geometry.dispose();
  26646. this.cone.material.dispose();
  26647. }
  26648. update() {
  26649. this.light.updateMatrixWorld();
  26650. const coneLength = this.light.distance ? this.light.distance : 1000;
  26651. const coneWidth = coneLength * Math.tan( this.light.angle );
  26652. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  26653. _vector$9.setFromMatrixPosition( this.light.target.matrixWorld );
  26654. this.cone.lookAt( _vector$9 );
  26655. if ( this.color !== undefined ) {
  26656. this.cone.material.color.set( this.color );
  26657. } else {
  26658. this.cone.material.color.copy( this.light.color );
  26659. }
  26660. }
  26661. }
  26662. const _vector$a = /*@__PURE__*/ new Vector3();
  26663. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  26664. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  26665. class SkeletonHelper extends LineSegments {
  26666. constructor( object ) {
  26667. const bones = getBoneList( object );
  26668. const geometry = new BufferGeometry();
  26669. const vertices = [];
  26670. const colors = [];
  26671. const color1 = new Color( 0, 0, 1 );
  26672. const color2 = new Color( 0, 1, 0 );
  26673. for ( let i = 0; i < bones.length; i ++ ) {
  26674. const bone = bones[ i ];
  26675. if ( bone.parent && bone.parent.isBone ) {
  26676. vertices.push( 0, 0, 0 );
  26677. vertices.push( 0, 0, 0 );
  26678. colors.push( color1.r, color1.g, color1.b );
  26679. colors.push( color2.r, color2.g, color2.b );
  26680. }
  26681. }
  26682. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26683. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  26684. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  26685. super( geometry, material );
  26686. this.type = 'SkeletonHelper';
  26687. this.isSkeletonHelper = true;
  26688. this.root = object;
  26689. this.bones = bones;
  26690. this.matrix = object.matrixWorld;
  26691. this.matrixAutoUpdate = false;
  26692. }
  26693. updateMatrixWorld( force ) {
  26694. const bones = this.bones;
  26695. const geometry = this.geometry;
  26696. const position = geometry.getAttribute( 'position' );
  26697. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  26698. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  26699. const bone = bones[ i ];
  26700. if ( bone.parent && bone.parent.isBone ) {
  26701. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  26702. _vector$a.setFromMatrixPosition( _boneMatrix );
  26703. position.setXYZ( j, _vector$a.x, _vector$a.y, _vector$a.z );
  26704. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  26705. _vector$a.setFromMatrixPosition( _boneMatrix );
  26706. position.setXYZ( j + 1, _vector$a.x, _vector$a.y, _vector$a.z );
  26707. j += 2;
  26708. }
  26709. }
  26710. geometry.getAttribute( 'position' ).needsUpdate = true;
  26711. super.updateMatrixWorld( force );
  26712. }
  26713. }
  26714. function getBoneList( object ) {
  26715. const boneList = [];
  26716. if ( object && object.isBone ) {
  26717. boneList.push( object );
  26718. }
  26719. for ( let i = 0; i < object.children.length; i ++ ) {
  26720. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  26721. }
  26722. return boneList;
  26723. }
  26724. class PointLightHelper extends Mesh {
  26725. constructor( light, sphereSize, color ) {
  26726. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  26727. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  26728. super( geometry, material );
  26729. this.light = light;
  26730. this.light.updateMatrixWorld();
  26731. this.color = color;
  26732. this.type = 'PointLightHelper';
  26733. this.matrix = this.light.matrixWorld;
  26734. this.matrixAutoUpdate = false;
  26735. this.update();
  26736. /*
  26737. // TODO: delete this comment?
  26738. const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  26739. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  26740. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  26741. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  26742. const d = light.distance;
  26743. if ( d === 0.0 ) {
  26744. this.lightDistance.visible = false;
  26745. } else {
  26746. this.lightDistance.scale.set( d, d, d );
  26747. }
  26748. this.add( this.lightDistance );
  26749. */
  26750. }
  26751. dispose() {
  26752. this.geometry.dispose();
  26753. this.material.dispose();
  26754. }
  26755. update() {
  26756. if ( this.color !== undefined ) {
  26757. this.material.color.set( this.color );
  26758. } else {
  26759. this.material.color.copy( this.light.color );
  26760. }
  26761. /*
  26762. const d = this.light.distance;
  26763. if ( d === 0.0 ) {
  26764. this.lightDistance.visible = false;
  26765. } else {
  26766. this.lightDistance.visible = true;
  26767. this.lightDistance.scale.set( d, d, d );
  26768. }
  26769. */
  26770. }
  26771. }
  26772. const _vector$b = /*@__PURE__*/ new Vector3();
  26773. const _color1 = /*@__PURE__*/ new Color();
  26774. const _color2 = /*@__PURE__*/ new Color();
  26775. class HemisphereLightHelper extends Object3D {
  26776. constructor( light, size, color ) {
  26777. super();
  26778. this.light = light;
  26779. this.light.updateMatrixWorld();
  26780. this.matrix = light.matrixWorld;
  26781. this.matrixAutoUpdate = false;
  26782. this.color = color;
  26783. const geometry = new OctahedronGeometry( size );
  26784. geometry.rotateY( Math.PI * 0.5 );
  26785. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  26786. if ( this.color === undefined ) this.material.vertexColors = true;
  26787. const position = geometry.getAttribute( 'position' );
  26788. const colors = new Float32Array( position.count * 3 );
  26789. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  26790. this.add( new Mesh( geometry, this.material ) );
  26791. this.update();
  26792. }
  26793. dispose() {
  26794. this.children[ 0 ].geometry.dispose();
  26795. this.children[ 0 ].material.dispose();
  26796. }
  26797. update() {
  26798. const mesh = this.children[ 0 ];
  26799. if ( this.color !== undefined ) {
  26800. this.material.color.set( this.color );
  26801. } else {
  26802. const colors = mesh.geometry.getAttribute( 'color' );
  26803. _color1.copy( this.light.color );
  26804. _color2.copy( this.light.groundColor );
  26805. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  26806. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  26807. colors.setXYZ( i, color.r, color.g, color.b );
  26808. }
  26809. colors.needsUpdate = true;
  26810. }
  26811. mesh.lookAt( _vector$b.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  26812. }
  26813. }
  26814. class GridHelper extends LineSegments {
  26815. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  26816. color1 = new Color( color1 );
  26817. color2 = new Color( color2 );
  26818. const center = divisions / 2;
  26819. const step = size / divisions;
  26820. const halfSize = size / 2;
  26821. const vertices = [], colors = [];
  26822. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  26823. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  26824. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  26825. const color = i === center ? color1 : color2;
  26826. color.toArray( colors, j ); j += 3;
  26827. color.toArray( colors, j ); j += 3;
  26828. color.toArray( colors, j ); j += 3;
  26829. color.toArray( colors, j ); j += 3;
  26830. }
  26831. const geometry = new BufferGeometry();
  26832. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26833. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  26834. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  26835. super( geometry, material );
  26836. this.type = 'GridHelper';
  26837. }
  26838. }
  26839. class PolarGridHelper extends LineSegments {
  26840. constructor( radius = 10, radials = 16, circles = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  26841. color1 = new Color( color1 );
  26842. color2 = new Color( color2 );
  26843. const vertices = [];
  26844. const colors = [];
  26845. // create the radials
  26846. for ( let i = 0; i <= radials; i ++ ) {
  26847. const v = ( i / radials ) * ( Math.PI * 2 );
  26848. const x = Math.sin( v ) * radius;
  26849. const z = Math.cos( v ) * radius;
  26850. vertices.push( 0, 0, 0 );
  26851. vertices.push( x, 0, z );
  26852. const color = ( i & 1 ) ? color1 : color2;
  26853. colors.push( color.r, color.g, color.b );
  26854. colors.push( color.r, color.g, color.b );
  26855. }
  26856. // create the circles
  26857. for ( let i = 0; i <= circles; i ++ ) {
  26858. const color = ( i & 1 ) ? color1 : color2;
  26859. const r = radius - ( radius / circles * i );
  26860. for ( let j = 0; j < divisions; j ++ ) {
  26861. // first vertex
  26862. let v = ( j / divisions ) * ( Math.PI * 2 );
  26863. let x = Math.sin( v ) * r;
  26864. let z = Math.cos( v ) * r;
  26865. vertices.push( x, 0, z );
  26866. colors.push( color.r, color.g, color.b );
  26867. // second vertex
  26868. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  26869. x = Math.sin( v ) * r;
  26870. z = Math.cos( v ) * r;
  26871. vertices.push( x, 0, z );
  26872. colors.push( color.r, color.g, color.b );
  26873. }
  26874. }
  26875. const geometry = new BufferGeometry();
  26876. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26877. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  26878. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  26879. super( geometry, material );
  26880. this.type = 'PolarGridHelper';
  26881. }
  26882. }
  26883. const _v1$6 = /*@__PURE__*/ new Vector3();
  26884. const _v2$3 = /*@__PURE__*/ new Vector3();
  26885. const _v3$1 = /*@__PURE__*/ new Vector3();
  26886. class DirectionalLightHelper extends Object3D {
  26887. constructor( light, size, color ) {
  26888. super();
  26889. this.light = light;
  26890. this.light.updateMatrixWorld();
  26891. this.matrix = light.matrixWorld;
  26892. this.matrixAutoUpdate = false;
  26893. this.color = color;
  26894. if ( size === undefined ) size = 1;
  26895. let geometry = new BufferGeometry();
  26896. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  26897. - size, size, 0,
  26898. size, size, 0,
  26899. size, - size, 0,
  26900. - size, - size, 0,
  26901. - size, size, 0
  26902. ], 3 ) );
  26903. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  26904. this.lightPlane = new Line( geometry, material );
  26905. this.add( this.lightPlane );
  26906. geometry = new BufferGeometry();
  26907. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  26908. this.targetLine = new Line( geometry, material );
  26909. this.add( this.targetLine );
  26910. this.update();
  26911. }
  26912. dispose() {
  26913. this.lightPlane.geometry.dispose();
  26914. this.lightPlane.material.dispose();
  26915. this.targetLine.geometry.dispose();
  26916. this.targetLine.material.dispose();
  26917. }
  26918. update() {
  26919. _v1$6.setFromMatrixPosition( this.light.matrixWorld );
  26920. _v2$3.setFromMatrixPosition( this.light.target.matrixWorld );
  26921. _v3$1.subVectors( _v2$3, _v1$6 );
  26922. this.lightPlane.lookAt( _v2$3 );
  26923. if ( this.color !== undefined ) {
  26924. this.lightPlane.material.color.set( this.color );
  26925. this.targetLine.material.color.set( this.color );
  26926. } else {
  26927. this.lightPlane.material.color.copy( this.light.color );
  26928. this.targetLine.material.color.copy( this.light.color );
  26929. }
  26930. this.targetLine.lookAt( _v2$3 );
  26931. this.targetLine.scale.z = _v3$1.length();
  26932. }
  26933. }
  26934. const _vector$c = /*@__PURE__*/ new Vector3();
  26935. const _camera = /*@__PURE__*/ new Camera();
  26936. /**
  26937. * - shows frustum, line of sight and up of the camera
  26938. * - suitable for fast updates
  26939. * - based on frustum visualization in lightgl.js shadowmap example
  26940. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  26941. */
  26942. class CameraHelper extends LineSegments {
  26943. constructor( camera ) {
  26944. const geometry = new BufferGeometry();
  26945. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  26946. const vertices = [];
  26947. const colors = [];
  26948. const pointMap = {};
  26949. // colors
  26950. const colorFrustum = new Color( 0xffaa00 );
  26951. const colorCone = new Color( 0xff0000 );
  26952. const colorUp = new Color( 0x00aaff );
  26953. const colorTarget = new Color( 0xffffff );
  26954. const colorCross = new Color( 0x333333 );
  26955. // near
  26956. addLine( 'n1', 'n2', colorFrustum );
  26957. addLine( 'n2', 'n4', colorFrustum );
  26958. addLine( 'n4', 'n3', colorFrustum );
  26959. addLine( 'n3', 'n1', colorFrustum );
  26960. // far
  26961. addLine( 'f1', 'f2', colorFrustum );
  26962. addLine( 'f2', 'f4', colorFrustum );
  26963. addLine( 'f4', 'f3', colorFrustum );
  26964. addLine( 'f3', 'f1', colorFrustum );
  26965. // sides
  26966. addLine( 'n1', 'f1', colorFrustum );
  26967. addLine( 'n2', 'f2', colorFrustum );
  26968. addLine( 'n3', 'f3', colorFrustum );
  26969. addLine( 'n4', 'f4', colorFrustum );
  26970. // cone
  26971. addLine( 'p', 'n1', colorCone );
  26972. addLine( 'p', 'n2', colorCone );
  26973. addLine( 'p', 'n3', colorCone );
  26974. addLine( 'p', 'n4', colorCone );
  26975. // up
  26976. addLine( 'u1', 'u2', colorUp );
  26977. addLine( 'u2', 'u3', colorUp );
  26978. addLine( 'u3', 'u1', colorUp );
  26979. // target
  26980. addLine( 'c', 't', colorTarget );
  26981. addLine( 'p', 'c', colorCross );
  26982. // cross
  26983. addLine( 'cn1', 'cn2', colorCross );
  26984. addLine( 'cn3', 'cn4', colorCross );
  26985. addLine( 'cf1', 'cf2', colorCross );
  26986. addLine( 'cf3', 'cf4', colorCross );
  26987. function addLine( a, b, color ) {
  26988. addPoint( a, color );
  26989. addPoint( b, color );
  26990. }
  26991. function addPoint( id, color ) {
  26992. vertices.push( 0, 0, 0 );
  26993. colors.push( color.r, color.g, color.b );
  26994. if ( pointMap[ id ] === undefined ) {
  26995. pointMap[ id ] = [];
  26996. }
  26997. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  26998. }
  26999. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27000. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  27001. super( geometry, material );
  27002. this.type = 'CameraHelper';
  27003. this.camera = camera;
  27004. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  27005. this.matrix = camera.matrixWorld;
  27006. this.matrixAutoUpdate = false;
  27007. this.pointMap = pointMap;
  27008. this.update();
  27009. }
  27010. update() {
  27011. const geometry = this.geometry;
  27012. const pointMap = this.pointMap;
  27013. const w = 1, h = 1;
  27014. // we need just camera projection matrix inverse
  27015. // world matrix must be identity
  27016. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  27017. // center / target
  27018. setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
  27019. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  27020. // near
  27021. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
  27022. setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
  27023. setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
  27024. setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
  27025. // far
  27026. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  27027. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  27028. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  27029. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  27030. // up
  27031. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
  27032. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
  27033. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
  27034. // cross
  27035. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  27036. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  27037. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  27038. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  27039. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
  27040. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
  27041. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
  27042. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
  27043. geometry.getAttribute( 'position' ).needsUpdate = true;
  27044. }
  27045. }
  27046. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  27047. _vector$c.set( x, y, z ).unproject( camera );
  27048. const points = pointMap[ point ];
  27049. if ( points !== undefined ) {
  27050. const position = geometry.getAttribute( 'position' );
  27051. for ( let i = 0, l = points.length; i < l; i ++ ) {
  27052. position.setXYZ( points[ i ], _vector$c.x, _vector$c.y, _vector$c.z );
  27053. }
  27054. }
  27055. }
  27056. const _box$3 = /*@__PURE__*/ new Box3();
  27057. class BoxHelper extends LineSegments {
  27058. constructor( object, color = 0xffff00 ) {
  27059. 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 ] );
  27060. const positions = new Float32Array( 8 * 3 );
  27061. const geometry = new BufferGeometry();
  27062. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  27063. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  27064. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  27065. this.object = object;
  27066. this.type = 'BoxHelper';
  27067. this.matrixAutoUpdate = false;
  27068. this.update();
  27069. }
  27070. update( object ) {
  27071. if ( object !== undefined ) {
  27072. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  27073. }
  27074. if ( this.object !== undefined ) {
  27075. _box$3.setFromObject( this.object );
  27076. }
  27077. if ( _box$3.isEmpty() ) return;
  27078. const min = _box$3.min;
  27079. const max = _box$3.max;
  27080. /*
  27081. 5____4
  27082. 1/___0/|
  27083. | 6__|_7
  27084. 2/___3/
  27085. 0: max.x, max.y, max.z
  27086. 1: min.x, max.y, max.z
  27087. 2: min.x, min.y, max.z
  27088. 3: max.x, min.y, max.z
  27089. 4: max.x, max.y, min.z
  27090. 5: min.x, max.y, min.z
  27091. 6: min.x, min.y, min.z
  27092. 7: max.x, min.y, min.z
  27093. */
  27094. const position = this.geometry.attributes.position;
  27095. const array = position.array;
  27096. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  27097. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  27098. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  27099. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  27100. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  27101. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  27102. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  27103. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  27104. position.needsUpdate = true;
  27105. this.geometry.computeBoundingSphere();
  27106. }
  27107. setFromObject( object ) {
  27108. this.object = object;
  27109. this.update();
  27110. return this;
  27111. }
  27112. copy( source ) {
  27113. LineSegments.prototype.copy.call( this, source );
  27114. this.object = source.object;
  27115. return this;
  27116. }
  27117. }
  27118. class Box3Helper extends LineSegments {
  27119. constructor( box, color = 0xffff00 ) {
  27120. 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 ] );
  27121. 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 ];
  27122. const geometry = new BufferGeometry();
  27123. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  27124. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  27125. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  27126. this.box = box;
  27127. this.type = 'Box3Helper';
  27128. this.geometry.computeBoundingSphere();
  27129. }
  27130. updateMatrixWorld( force ) {
  27131. const box = this.box;
  27132. if ( box.isEmpty() ) return;
  27133. box.getCenter( this.position );
  27134. box.getSize( this.scale );
  27135. this.scale.multiplyScalar( 0.5 );
  27136. super.updateMatrixWorld( force );
  27137. }
  27138. }
  27139. class PlaneHelper extends Line {
  27140. constructor( plane, size = 1, hex = 0xffff00 ) {
  27141. const color = hex;
  27142. 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 ];
  27143. const geometry = new BufferGeometry();
  27144. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  27145. geometry.computeBoundingSphere();
  27146. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  27147. this.type = 'PlaneHelper';
  27148. this.plane = plane;
  27149. this.size = size;
  27150. const positions2 = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, - 1, 1, 1, - 1, 1 ];
  27151. const geometry2 = new BufferGeometry();
  27152. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  27153. geometry2.computeBoundingSphere();
  27154. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  27155. }
  27156. updateMatrixWorld( force ) {
  27157. let scale = - this.plane.constant;
  27158. if ( Math.abs( scale ) < 1e-8 ) scale = 1e-8; // sign does not matter
  27159. this.scale.set( 0.5 * this.size, 0.5 * this.size, scale );
  27160. this.children[ 0 ].material.side = ( scale < 0 ) ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  27161. this.lookAt( this.plane.normal );
  27162. super.updateMatrixWorld( force );
  27163. }
  27164. }
  27165. const _axis = /*@__PURE__*/ new Vector3();
  27166. let _lineGeometry, _coneGeometry;
  27167. class ArrowHelper extends Object3D {
  27168. // dir is assumed to be normalized
  27169. 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 ) {
  27170. super();
  27171. this.type = 'ArrowHelper';
  27172. if ( _lineGeometry === undefined ) {
  27173. _lineGeometry = new BufferGeometry();
  27174. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  27175. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  27176. _coneGeometry.translate( 0, - 0.5, 0 );
  27177. }
  27178. this.position.copy( origin );
  27179. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  27180. this.line.matrixAutoUpdate = false;
  27181. this.add( this.line );
  27182. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  27183. this.cone.matrixAutoUpdate = false;
  27184. this.add( this.cone );
  27185. this.setDirection( dir );
  27186. this.setLength( length, headLength, headWidth );
  27187. }
  27188. setDirection( dir ) {
  27189. // dir is assumed to be normalized
  27190. if ( dir.y > 0.99999 ) {
  27191. this.quaternion.set( 0, 0, 0, 1 );
  27192. } else if ( dir.y < - 0.99999 ) {
  27193. this.quaternion.set( 1, 0, 0, 0 );
  27194. } else {
  27195. _axis.set( dir.z, 0, - dir.x ).normalize();
  27196. const radians = Math.acos( dir.y );
  27197. this.quaternion.setFromAxisAngle( _axis, radians );
  27198. }
  27199. }
  27200. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  27201. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  27202. this.line.updateMatrix();
  27203. this.cone.scale.set( headWidth, headLength, headWidth );
  27204. this.cone.position.y = length;
  27205. this.cone.updateMatrix();
  27206. }
  27207. setColor( color ) {
  27208. this.line.material.color.set( color );
  27209. this.cone.material.color.set( color );
  27210. }
  27211. copy( source ) {
  27212. super.copy( source, false );
  27213. this.line.copy( source.line );
  27214. this.cone.copy( source.cone );
  27215. return this;
  27216. }
  27217. }
  27218. class AxesHelper extends LineSegments {
  27219. constructor( size = 1 ) {
  27220. const vertices = [
  27221. 0, 0, 0, size, 0, 0,
  27222. 0, 0, 0, 0, size, 0,
  27223. 0, 0, 0, 0, 0, size
  27224. ];
  27225. const colors = [
  27226. 1, 0, 0, 1, 0.6, 0,
  27227. 0, 1, 0, 0.6, 1, 0,
  27228. 0, 0, 1, 0, 0.6, 1
  27229. ];
  27230. const geometry = new BufferGeometry();
  27231. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27232. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  27233. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  27234. super( geometry, material );
  27235. this.type = 'AxesHelper';
  27236. }
  27237. }
  27238. const _floatView = new Float32Array( 1 );
  27239. const _int32View = new Int32Array( _floatView.buffer );
  27240. const DataUtils = {
  27241. // Converts float32 to float16 (stored as uint16 value).
  27242. toHalfFloat: function ( val ) {
  27243. // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
  27244. /* This method is faster than the OpenEXR implementation (very often
  27245. * used, eg. in Ogre), with the additional benefit of rounding, inspired
  27246. * by James Tursa?s half-precision code. */
  27247. _floatView[ 0 ] = val;
  27248. const x = _int32View[ 0 ];
  27249. let bits = ( x >> 16 ) & 0x8000; /* Get the sign */
  27250. let m = ( x >> 12 ) & 0x07ff; /* Keep one extra bit for rounding */
  27251. const e = ( x >> 23 ) & 0xff; /* Using int is faster here */
  27252. /* If zero, or denormal, or exponent underflows too much for a denormal
  27253. * half, return signed zero. */
  27254. if ( e < 103 ) return bits;
  27255. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  27256. if ( e > 142 ) {
  27257. bits |= 0x7c00;
  27258. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  27259. * not Inf, so make sure we set one mantissa bit too. */
  27260. bits |= ( ( e == 255 ) ? 0 : 1 ) && ( x & 0x007fffff );
  27261. return bits;
  27262. }
  27263. /* If exponent underflows but not too much, return a denormal */
  27264. if ( e < 113 ) {
  27265. m |= 0x0800;
  27266. /* Extra rounding may overflow and set mantissa to 0 and exponent
  27267. * to 1, which is OK. */
  27268. bits |= ( m >> ( 114 - e ) ) + ( ( m >> ( 113 - e ) ) & 1 );
  27269. return bits;
  27270. }
  27271. bits |= ( ( e - 112 ) << 10 ) | ( m >> 1 );
  27272. /* Extra rounding. An overflow will set mantissa to 0 and increment
  27273. * the exponent, which is OK. */
  27274. bits += m & 1;
  27275. return bits;
  27276. }
  27277. };
  27278. const LOD_MIN = 4;
  27279. const LOD_MAX = 8;
  27280. const SIZE_MAX = Math.pow( 2, LOD_MAX );
  27281. // The standard deviations (radians) associated with the extra mips. These are
  27282. // chosen to approximate a Trowbridge-Reitz distribution function times the
  27283. // geometric shadowing function. These sigma values squared must match the
  27284. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  27285. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  27286. const TOTAL_LODS = LOD_MAX - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  27287. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  27288. // samples and exit early, but not recompile the shader.
  27289. const MAX_SAMPLES = 20;
  27290. const ENCODINGS = {
  27291. [ LinearEncoding ]: 0,
  27292. [ sRGBEncoding ]: 1,
  27293. [ RGBEEncoding ]: 2,
  27294. [ RGBM7Encoding ]: 3,
  27295. [ RGBM16Encoding ]: 4,
  27296. [ RGBDEncoding ]: 5,
  27297. [ GammaEncoding ]: 6
  27298. };
  27299. const backgroundMaterial = new MeshBasicMaterial( {
  27300. side: BackSide,
  27301. depthWrite: false,
  27302. depthTest: false,
  27303. } );
  27304. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  27305. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  27306. const { _lodPlanes, _sizeLods, _sigmas } = /*@__PURE__*/ _createPlanes();
  27307. const _clearColor = /*@__PURE__*/ new Color();
  27308. let _oldTarget = null;
  27309. // Golden Ratio
  27310. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  27311. const INV_PHI = 1 / PHI;
  27312. // Vertices of a dodecahedron (except the opposites, which represent the
  27313. // same axis), used as axis directions evenly spread on a sphere.
  27314. const _axisDirections = [
  27315. /*@__PURE__*/ new Vector3( 1, 1, 1 ),
  27316. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  27317. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  27318. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  27319. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  27320. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  27321. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  27322. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  27323. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  27324. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ];
  27325. /**
  27326. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  27327. * (PMREM) from a cubeMap environment texture. This allows different levels of
  27328. * blur to be quickly accessed based on material roughness. It is packed into a
  27329. * special CubeUV format that allows us to perform custom interpolation so that
  27330. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  27331. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  27332. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  27333. * higher roughness levels. In this way we maintain resolution to smoothly
  27334. * interpolate diffuse lighting while limiting sampling computation.
  27335. */
  27336. function convertLinearToRGBE( color ) {
  27337. const maxComponent = Math.max( color.r, color.g, color.b );
  27338. const fExp = Math.min( Math.max( Math.ceil( Math.log2( maxComponent ) ), - 128.0 ), 127.0 );
  27339. color.multiplyScalar( Math.pow( 2.0, - fExp ) );
  27340. const alpha = ( fExp + 128.0 ) / 255.0;
  27341. return alpha;
  27342. }
  27343. class PMREMGenerator {
  27344. constructor( renderer ) {
  27345. this._renderer = renderer;
  27346. this._pingPongRenderTarget = null;
  27347. this._blurMaterial = _getBlurShader( MAX_SAMPLES );
  27348. this._equirectShader = null;
  27349. this._cubemapShader = null;
  27350. this._compileMaterial( this._blurMaterial );
  27351. }
  27352. /**
  27353. * Generates a PMREM from a supplied Scene, which can be faster than using an
  27354. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  27355. * in radians to be applied to the scene before PMREM generation. Optional near
  27356. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  27357. * is placed at the origin).
  27358. */
  27359. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  27360. _oldTarget = this._renderer.getRenderTarget();
  27361. const cubeUVRenderTarget = this._allocateTargets();
  27362. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  27363. if ( sigma > 0 ) {
  27364. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  27365. }
  27366. this._applyPMREM( cubeUVRenderTarget );
  27367. this._cleanup( cubeUVRenderTarget );
  27368. return cubeUVRenderTarget;
  27369. }
  27370. /**
  27371. * Generates a PMREM from an equirectangular texture, which can be either LDR
  27372. * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
  27373. * as this matches best with the 256 x 256 cubemap output.
  27374. */
  27375. fromEquirectangular( equirectangular ) {
  27376. return this._fromTexture( equirectangular );
  27377. }
  27378. /**
  27379. * Generates a PMREM from an cubemap texture, which can be either LDR
  27380. * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
  27381. * as this matches best with the 256 x 256 cubemap output.
  27382. */
  27383. fromCubemap( cubemap ) {
  27384. return this._fromTexture( cubemap );
  27385. }
  27386. /**
  27387. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  27388. * your texture's network fetch for increased concurrency.
  27389. */
  27390. compileCubemapShader() {
  27391. if ( this._cubemapShader === null ) {
  27392. this._cubemapShader = _getCubemapShader();
  27393. this._compileMaterial( this._cubemapShader );
  27394. }
  27395. }
  27396. /**
  27397. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  27398. * your texture's network fetch for increased concurrency.
  27399. */
  27400. compileEquirectangularShader() {
  27401. if ( this._equirectShader === null ) {
  27402. this._equirectShader = _getEquirectShader();
  27403. this._compileMaterial( this._equirectShader );
  27404. }
  27405. }
  27406. /**
  27407. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  27408. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  27409. * one of them will cause any others to also become unusable.
  27410. */
  27411. dispose() {
  27412. this._blurMaterial.dispose();
  27413. if ( this._cubemapShader !== null ) this._cubemapShader.dispose();
  27414. if ( this._equirectShader !== null ) this._equirectShader.dispose();
  27415. for ( let i = 0; i < _lodPlanes.length; i ++ ) {
  27416. _lodPlanes[ i ].dispose();
  27417. }
  27418. }
  27419. // private interface
  27420. _cleanup( outputTarget ) {
  27421. this._pingPongRenderTarget.dispose();
  27422. this._renderer.setRenderTarget( _oldTarget );
  27423. outputTarget.scissorTest = false;
  27424. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  27425. }
  27426. _fromTexture( texture ) {
  27427. _oldTarget = this._renderer.getRenderTarget();
  27428. const cubeUVRenderTarget = this._allocateTargets( texture );
  27429. this._textureToCubeUV( texture, cubeUVRenderTarget );
  27430. this._applyPMREM( cubeUVRenderTarget );
  27431. this._cleanup( cubeUVRenderTarget );
  27432. return cubeUVRenderTarget;
  27433. }
  27434. _allocateTargets( texture ) { // warning: null texture is valid
  27435. const params = {
  27436. magFilter: NearestFilter,
  27437. minFilter: NearestFilter,
  27438. generateMipmaps: false,
  27439. type: UnsignedByteType,
  27440. format: RGBEFormat,
  27441. encoding: _isLDR( texture ) ? texture.encoding : RGBEEncoding,
  27442. depthBuffer: false
  27443. };
  27444. const cubeUVRenderTarget = _createRenderTarget( params );
  27445. cubeUVRenderTarget.depthBuffer = texture ? false : true;
  27446. this._pingPongRenderTarget = _createRenderTarget( params );
  27447. return cubeUVRenderTarget;
  27448. }
  27449. _compileMaterial( material ) {
  27450. const tmpMesh = new Mesh( _lodPlanes[ 0 ], material );
  27451. this._renderer.compile( tmpMesh, _flatCamera );
  27452. }
  27453. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  27454. const fov = 90;
  27455. const aspect = 1;
  27456. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  27457. const upSign = [ 1, - 1, 1, 1, 1, 1 ];
  27458. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  27459. const renderer = this._renderer;
  27460. const originalAutoClear = renderer.autoClear;
  27461. const outputEncoding = renderer.outputEncoding;
  27462. const toneMapping = renderer.toneMapping;
  27463. renderer.getClearColor( _clearColor );
  27464. renderer.toneMapping = NoToneMapping;
  27465. renderer.outputEncoding = LinearEncoding;
  27466. renderer.autoClear = false;
  27467. let useSolidColor = false;
  27468. const background = scene.background;
  27469. if ( background ) {
  27470. if ( background.isColor ) {
  27471. backgroundMaterial.color.copy( background ).convertSRGBToLinear();
  27472. scene.background = null;
  27473. const alpha = convertLinearToRGBE( backgroundMaterial.color );
  27474. backgroundMaterial.opacity = alpha;
  27475. useSolidColor = true;
  27476. }
  27477. } else {
  27478. backgroundMaterial.color.copy( _clearColor ).convertSRGBToLinear();
  27479. const alpha = convertLinearToRGBE( backgroundMaterial.color );
  27480. backgroundMaterial.opacity = alpha;
  27481. useSolidColor = true;
  27482. }
  27483. for ( let i = 0; i < 6; i ++ ) {
  27484. const col = i % 3;
  27485. if ( col == 0 ) {
  27486. cubeCamera.up.set( 0, upSign[ i ], 0 );
  27487. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  27488. } else if ( col == 1 ) {
  27489. cubeCamera.up.set( 0, 0, upSign[ i ] );
  27490. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  27491. } else {
  27492. cubeCamera.up.set( 0, upSign[ i ], 0 );
  27493. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  27494. }
  27495. _setViewport( cubeUVRenderTarget,
  27496. col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX );
  27497. renderer.setRenderTarget( cubeUVRenderTarget );
  27498. if ( useSolidColor ) {
  27499. renderer.render( backgroundBox, cubeCamera );
  27500. }
  27501. renderer.render( scene, cubeCamera );
  27502. }
  27503. renderer.toneMapping = toneMapping;
  27504. renderer.outputEncoding = outputEncoding;
  27505. renderer.autoClear = originalAutoClear;
  27506. }
  27507. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  27508. const renderer = this._renderer;
  27509. if ( texture.isCubeTexture ) {
  27510. if ( this._cubemapShader == null ) {
  27511. this._cubemapShader = _getCubemapShader();
  27512. }
  27513. } else {
  27514. if ( this._equirectShader == null ) {
  27515. this._equirectShader = _getEquirectShader();
  27516. }
  27517. }
  27518. const material = texture.isCubeTexture ? this._cubemapShader : this._equirectShader;
  27519. const mesh = new Mesh( _lodPlanes[ 0 ], material );
  27520. const uniforms = material.uniforms;
  27521. uniforms[ 'envMap' ].value = texture;
  27522. if ( ! texture.isCubeTexture ) {
  27523. uniforms[ 'texelSize' ].value.set( 1.0 / texture.image.width, 1.0 / texture.image.height );
  27524. }
  27525. uniforms[ 'inputEncoding' ].value = ENCODINGS[ texture.encoding ];
  27526. uniforms[ 'outputEncoding' ].value = ENCODINGS[ cubeUVRenderTarget.texture.encoding ];
  27527. _setViewport( cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX );
  27528. renderer.setRenderTarget( cubeUVRenderTarget );
  27529. renderer.render( mesh, _flatCamera );
  27530. }
  27531. _applyPMREM( cubeUVRenderTarget ) {
  27532. const renderer = this._renderer;
  27533. const autoClear = renderer.autoClear;
  27534. renderer.autoClear = false;
  27535. for ( let i = 1; i < TOTAL_LODS; i ++ ) {
  27536. const sigma = Math.sqrt( _sigmas[ i ] * _sigmas[ i ] - _sigmas[ i - 1 ] * _sigmas[ i - 1 ] );
  27537. const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ];
  27538. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  27539. }
  27540. renderer.autoClear = autoClear;
  27541. }
  27542. /**
  27543. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  27544. * vertically and horizontally, but this breaks down on a cube. Here we apply
  27545. * the blur latitudinally (around the poles), and then longitudinally (towards
  27546. * the poles) to approximate the orthogonally-separable blur. It is least
  27547. * accurate at the poles, but still does a decent job.
  27548. */
  27549. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  27550. const pingPongRenderTarget = this._pingPongRenderTarget;
  27551. this._halfBlur(
  27552. cubeUVRenderTarget,
  27553. pingPongRenderTarget,
  27554. lodIn,
  27555. lodOut,
  27556. sigma,
  27557. 'latitudinal',
  27558. poleAxis );
  27559. this._halfBlur(
  27560. pingPongRenderTarget,
  27561. cubeUVRenderTarget,
  27562. lodOut,
  27563. lodOut,
  27564. sigma,
  27565. 'longitudinal',
  27566. poleAxis );
  27567. }
  27568. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  27569. const renderer = this._renderer;
  27570. const blurMaterial = this._blurMaterial;
  27571. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  27572. console.error(
  27573. 'blur direction must be either latitudinal or longitudinal!' );
  27574. }
  27575. // Number of standard deviations at which to cut off the discrete approximation.
  27576. const STANDARD_DEVIATIONS = 3;
  27577. const blurMesh = new Mesh( _lodPlanes[ lodOut ], blurMaterial );
  27578. const blurUniforms = blurMaterial.uniforms;
  27579. const pixels = _sizeLods[ lodIn ] - 1;
  27580. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  27581. const sigmaPixels = sigmaRadians / radiansPerPixel;
  27582. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  27583. if ( samples > MAX_SAMPLES ) {
  27584. console.warn( `sigmaRadians, ${
  27585. sigmaRadians}, is too large and will clip, as it requested ${
  27586. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  27587. }
  27588. const weights = [];
  27589. let sum = 0;
  27590. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  27591. const x = i / sigmaPixels;
  27592. const weight = Math.exp( - x * x / 2 );
  27593. weights.push( weight );
  27594. if ( i == 0 ) {
  27595. sum += weight;
  27596. } else if ( i < samples ) {
  27597. sum += 2 * weight;
  27598. }
  27599. }
  27600. for ( let i = 0; i < weights.length; i ++ ) {
  27601. weights[ i ] = weights[ i ] / sum;
  27602. }
  27603. blurUniforms[ 'envMap' ].value = targetIn.texture;
  27604. blurUniforms[ 'samples' ].value = samples;
  27605. blurUniforms[ 'weights' ].value = weights;
  27606. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  27607. if ( poleAxis ) {
  27608. blurUniforms[ 'poleAxis' ].value = poleAxis;
  27609. }
  27610. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  27611. blurUniforms[ 'mipInt' ].value = LOD_MAX - lodIn;
  27612. blurUniforms[ 'inputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ];
  27613. blurUniforms[ 'outputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ];
  27614. const outputSize = _sizeLods[ lodOut ];
  27615. const x = 3 * Math.max( 0, SIZE_MAX - 2 * outputSize );
  27616. const y = ( lodOut === 0 ? 0 : 2 * SIZE_MAX ) + 2 * outputSize * ( lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0 );
  27617. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  27618. renderer.setRenderTarget( targetOut );
  27619. renderer.render( blurMesh, _flatCamera );
  27620. }
  27621. }
  27622. function _isLDR( texture ) {
  27623. if ( texture === undefined || texture.type !== UnsignedByteType ) return false;
  27624. return texture.encoding === LinearEncoding || texture.encoding === sRGBEncoding || texture.encoding === GammaEncoding;
  27625. }
  27626. function _createPlanes() {
  27627. const _lodPlanes = [];
  27628. const _sizeLods = [];
  27629. const _sigmas = [];
  27630. let lod = LOD_MAX;
  27631. for ( let i = 0; i < TOTAL_LODS; i ++ ) {
  27632. const sizeLod = Math.pow( 2, lod );
  27633. _sizeLods.push( sizeLod );
  27634. let sigma = 1.0 / sizeLod;
  27635. if ( i > LOD_MAX - LOD_MIN ) {
  27636. sigma = EXTRA_LOD_SIGMA[ i - LOD_MAX + LOD_MIN - 1 ];
  27637. } else if ( i == 0 ) {
  27638. sigma = 0;
  27639. }
  27640. _sigmas.push( sigma );
  27641. const texelSize = 1.0 / ( sizeLod - 1 );
  27642. const min = - texelSize / 2;
  27643. const max = 1 + texelSize / 2;
  27644. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  27645. const cubeFaces = 6;
  27646. const vertices = 6;
  27647. const positionSize = 3;
  27648. const uvSize = 2;
  27649. const faceIndexSize = 1;
  27650. const position = new Float32Array( positionSize * vertices * cubeFaces );
  27651. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  27652. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  27653. for ( let face = 0; face < cubeFaces; face ++ ) {
  27654. const x = ( face % 3 ) * 2 / 3 - 1;
  27655. const y = face > 2 ? 0 : - 1;
  27656. const coordinates = [
  27657. x, y, 0,
  27658. x + 2 / 3, y, 0,
  27659. x + 2 / 3, y + 1, 0,
  27660. x, y, 0,
  27661. x + 2 / 3, y + 1, 0,
  27662. x, y + 1, 0
  27663. ];
  27664. position.set( coordinates, positionSize * vertices * face );
  27665. uv.set( uv1, uvSize * vertices * face );
  27666. const fill = [ face, face, face, face, face, face ];
  27667. faceIndex.set( fill, faceIndexSize * vertices * face );
  27668. }
  27669. const planes = new BufferGeometry();
  27670. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  27671. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  27672. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  27673. _lodPlanes.push( planes );
  27674. if ( lod > LOD_MIN ) {
  27675. lod --;
  27676. }
  27677. }
  27678. return { _lodPlanes, _sizeLods, _sigmas };
  27679. }
  27680. function _createRenderTarget( params ) {
  27681. const cubeUVRenderTarget = new WebGLRenderTarget( 3 * SIZE_MAX, 3 * SIZE_MAX, params );
  27682. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  27683. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  27684. cubeUVRenderTarget.scissorTest = true;
  27685. return cubeUVRenderTarget;
  27686. }
  27687. function _setViewport( target, x, y, width, height ) {
  27688. target.viewport.set( x, y, width, height );
  27689. target.scissor.set( x, y, width, height );
  27690. }
  27691. function _getBlurShader( maxSamples ) {
  27692. const weights = new Float32Array( maxSamples );
  27693. const poleAxis = new Vector3( 0, 1, 0 );
  27694. const shaderMaterial = new RawShaderMaterial( {
  27695. name: 'SphericalGaussianBlur',
  27696. defines: { 'n': maxSamples },
  27697. uniforms: {
  27698. 'envMap': { value: null },
  27699. 'samples': { value: 1 },
  27700. 'weights': { value: weights },
  27701. 'latitudinal': { value: false },
  27702. 'dTheta': { value: 0 },
  27703. 'mipInt': { value: 0 },
  27704. 'poleAxis': { value: poleAxis },
  27705. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  27706. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  27707. },
  27708. vertexShader: _getCommonVertexShader(),
  27709. fragmentShader: /* glsl */`
  27710. precision mediump float;
  27711. precision mediump int;
  27712. varying vec3 vOutputDirection;
  27713. uniform sampler2D envMap;
  27714. uniform int samples;
  27715. uniform float weights[ n ];
  27716. uniform bool latitudinal;
  27717. uniform float dTheta;
  27718. uniform float mipInt;
  27719. uniform vec3 poleAxis;
  27720. ${ _getEncodings() }
  27721. #define ENVMAP_TYPE_CUBE_UV
  27722. #include <cube_uv_reflection_fragment>
  27723. vec3 getSample( float theta, vec3 axis ) {
  27724. float cosTheta = cos( theta );
  27725. // Rodrigues' axis-angle rotation
  27726. vec3 sampleDirection = vOutputDirection * cosTheta
  27727. + cross( axis, vOutputDirection ) * sin( theta )
  27728. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  27729. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  27730. }
  27731. void main() {
  27732. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  27733. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  27734. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  27735. }
  27736. axis = normalize( axis );
  27737. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  27738. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  27739. for ( int i = 1; i < n; i++ ) {
  27740. if ( i >= samples ) {
  27741. break;
  27742. }
  27743. float theta = dTheta * float( i );
  27744. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  27745. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  27746. }
  27747. gl_FragColor = linearToOutputTexel( gl_FragColor );
  27748. }
  27749. `,
  27750. blending: NoBlending,
  27751. depthTest: false,
  27752. depthWrite: false
  27753. } );
  27754. return shaderMaterial;
  27755. }
  27756. function _getEquirectShader() {
  27757. const texelSize = new Vector2( 1, 1 );
  27758. const shaderMaterial = new RawShaderMaterial( {
  27759. name: 'EquirectangularToCubeUV',
  27760. uniforms: {
  27761. 'envMap': { value: null },
  27762. 'texelSize': { value: texelSize },
  27763. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  27764. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  27765. },
  27766. vertexShader: _getCommonVertexShader(),
  27767. fragmentShader: /* glsl */`
  27768. precision mediump float;
  27769. precision mediump int;
  27770. varying vec3 vOutputDirection;
  27771. uniform sampler2D envMap;
  27772. uniform vec2 texelSize;
  27773. ${ _getEncodings() }
  27774. #include <common>
  27775. void main() {
  27776. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  27777. vec3 outputDirection = normalize( vOutputDirection );
  27778. vec2 uv = equirectUv( outputDirection );
  27779. vec2 f = fract( uv / texelSize - 0.5 );
  27780. uv -= f * texelSize;
  27781. vec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  27782. uv.x += texelSize.x;
  27783. vec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  27784. uv.y += texelSize.y;
  27785. vec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  27786. uv.x -= texelSize.x;
  27787. vec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  27788. vec3 tm = mix( tl, tr, f.x );
  27789. vec3 bm = mix( bl, br, f.x );
  27790. gl_FragColor.rgb = mix( tm, bm, f.y );
  27791. gl_FragColor = linearToOutputTexel( gl_FragColor );
  27792. }
  27793. `,
  27794. blending: NoBlending,
  27795. depthTest: false,
  27796. depthWrite: false
  27797. } );
  27798. return shaderMaterial;
  27799. }
  27800. function _getCubemapShader() {
  27801. const shaderMaterial = new RawShaderMaterial( {
  27802. name: 'CubemapToCubeUV',
  27803. uniforms: {
  27804. 'envMap': { value: null },
  27805. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  27806. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  27807. },
  27808. vertexShader: _getCommonVertexShader(),
  27809. fragmentShader: /* glsl */`
  27810. precision mediump float;
  27811. precision mediump int;
  27812. varying vec3 vOutputDirection;
  27813. uniform samplerCube envMap;
  27814. ${ _getEncodings() }
  27815. void main() {
  27816. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  27817. gl_FragColor.rgb = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) ).rgb;
  27818. gl_FragColor = linearToOutputTexel( gl_FragColor );
  27819. }
  27820. `,
  27821. blending: NoBlending,
  27822. depthTest: false,
  27823. depthWrite: false
  27824. } );
  27825. return shaderMaterial;
  27826. }
  27827. function _getCommonVertexShader() {
  27828. return /* glsl */`
  27829. precision mediump float;
  27830. precision mediump int;
  27831. attribute vec3 position;
  27832. attribute vec2 uv;
  27833. attribute float faceIndex;
  27834. varying vec3 vOutputDirection;
  27835. // RH coordinate system; PMREM face-indexing convention
  27836. vec3 getDirection( vec2 uv, float face ) {
  27837. uv = 2.0 * uv - 1.0;
  27838. vec3 direction = vec3( uv, 1.0 );
  27839. if ( face == 0.0 ) {
  27840. direction = direction.zyx; // ( 1, v, u ) pos x
  27841. } else if ( face == 1.0 ) {
  27842. direction = direction.xzy;
  27843. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  27844. } else if ( face == 2.0 ) {
  27845. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  27846. } else if ( face == 3.0 ) {
  27847. direction = direction.zyx;
  27848. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  27849. } else if ( face == 4.0 ) {
  27850. direction = direction.xzy;
  27851. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  27852. } else if ( face == 5.0 ) {
  27853. direction.z *= -1.0; // ( u, v, -1 ) neg z
  27854. }
  27855. return direction;
  27856. }
  27857. void main() {
  27858. vOutputDirection = getDirection( uv, faceIndex );
  27859. gl_Position = vec4( position, 1.0 );
  27860. }
  27861. `;
  27862. }
  27863. function _getEncodings() {
  27864. return /* glsl */`
  27865. uniform int inputEncoding;
  27866. uniform int outputEncoding;
  27867. #include <encodings_pars_fragment>
  27868. vec4 inputTexelToLinear( vec4 value ) {
  27869. if ( inputEncoding == 0 ) {
  27870. return value;
  27871. } else if ( inputEncoding == 1 ) {
  27872. return sRGBToLinear( value );
  27873. } else if ( inputEncoding == 2 ) {
  27874. return RGBEToLinear( value );
  27875. } else if ( inputEncoding == 3 ) {
  27876. return RGBMToLinear( value, 7.0 );
  27877. } else if ( inputEncoding == 4 ) {
  27878. return RGBMToLinear( value, 16.0 );
  27879. } else if ( inputEncoding == 5 ) {
  27880. return RGBDToLinear( value, 256.0 );
  27881. } else {
  27882. return GammaToLinear( value, 2.2 );
  27883. }
  27884. }
  27885. vec4 linearToOutputTexel( vec4 value ) {
  27886. if ( outputEncoding == 0 ) {
  27887. return value;
  27888. } else if ( outputEncoding == 1 ) {
  27889. return LinearTosRGB( value );
  27890. } else if ( outputEncoding == 2 ) {
  27891. return LinearToRGBE( value );
  27892. } else if ( outputEncoding == 3 ) {
  27893. return LinearToRGBM( value, 7.0 );
  27894. } else if ( outputEncoding == 4 ) {
  27895. return LinearToRGBM( value, 16.0 );
  27896. } else if ( outputEncoding == 5 ) {
  27897. return LinearToRGBD( value, 256.0 );
  27898. } else {
  27899. return LinearToGamma( value, 2.2 );
  27900. }
  27901. }
  27902. vec4 envMapTexelToLinear( vec4 color ) {
  27903. return inputTexelToLinear( color );
  27904. }
  27905. `;
  27906. }
  27907. const LineStrip = 0;
  27908. const LinePieces = 1;
  27909. const NoColors = 0;
  27910. const FaceColors = 1;
  27911. const VertexColors = 2;
  27912. function MeshFaceMaterial( materials ) {
  27913. console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' );
  27914. return materials;
  27915. }
  27916. function MultiMaterial( materials = [] ) {
  27917. console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' );
  27918. materials.isMultiMaterial = true;
  27919. materials.materials = materials;
  27920. materials.clone = function () {
  27921. return materials.slice();
  27922. };
  27923. return materials;
  27924. }
  27925. function PointCloud( geometry, material ) {
  27926. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  27927. return new Points( geometry, material );
  27928. }
  27929. function Particle( material ) {
  27930. console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
  27931. return new Sprite( material );
  27932. }
  27933. function ParticleSystem( geometry, material ) {
  27934. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  27935. return new Points( geometry, material );
  27936. }
  27937. function PointCloudMaterial( parameters ) {
  27938. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  27939. return new PointsMaterial( parameters );
  27940. }
  27941. function ParticleBasicMaterial( parameters ) {
  27942. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  27943. return new PointsMaterial( parameters );
  27944. }
  27945. function ParticleSystemMaterial( parameters ) {
  27946. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  27947. return new PointsMaterial( parameters );
  27948. }
  27949. function Vertex( x, y, z ) {
  27950. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  27951. return new Vector3( x, y, z );
  27952. }
  27953. //
  27954. function DynamicBufferAttribute( array, itemSize ) {
  27955. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.' );
  27956. return new BufferAttribute( array, itemSize ).setUsage( DynamicDrawUsage );
  27957. }
  27958. function Int8Attribute( array, itemSize ) {
  27959. console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
  27960. return new Int8BufferAttribute( array, itemSize );
  27961. }
  27962. function Uint8Attribute( array, itemSize ) {
  27963. console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
  27964. return new Uint8BufferAttribute( array, itemSize );
  27965. }
  27966. function Uint8ClampedAttribute( array, itemSize ) {
  27967. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
  27968. return new Uint8ClampedBufferAttribute( array, itemSize );
  27969. }
  27970. function Int16Attribute( array, itemSize ) {
  27971. console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
  27972. return new Int16BufferAttribute( array, itemSize );
  27973. }
  27974. function Uint16Attribute( array, itemSize ) {
  27975. console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
  27976. return new Uint16BufferAttribute( array, itemSize );
  27977. }
  27978. function Int32Attribute( array, itemSize ) {
  27979. console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
  27980. return new Int32BufferAttribute( array, itemSize );
  27981. }
  27982. function Uint32Attribute( array, itemSize ) {
  27983. console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
  27984. return new Uint32BufferAttribute( array, itemSize );
  27985. }
  27986. function Float32Attribute( array, itemSize ) {
  27987. console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
  27988. return new Float32BufferAttribute( array, itemSize );
  27989. }
  27990. function Float64Attribute( array, itemSize ) {
  27991. console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
  27992. return new Float64BufferAttribute( array, itemSize );
  27993. }
  27994. //
  27995. Curve.create = function ( construct, getPoint ) {
  27996. console.log( 'THREE.Curve.create() has been deprecated' );
  27997. construct.prototype = Object.create( Curve.prototype );
  27998. construct.prototype.constructor = construct;
  27999. construct.prototype.getPoint = getPoint;
  28000. return construct;
  28001. };
  28002. //
  28003. Path.prototype.fromPoints = function ( points ) {
  28004. console.warn( 'THREE.Path: .fromPoints() has been renamed to .setFromPoints().' );
  28005. return this.setFromPoints( points );
  28006. };
  28007. //
  28008. function AxisHelper( size ) {
  28009. console.warn( 'THREE.AxisHelper has been renamed to THREE.AxesHelper.' );
  28010. return new AxesHelper( size );
  28011. }
  28012. function BoundingBoxHelper( object, color ) {
  28013. console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
  28014. return new BoxHelper( object, color );
  28015. }
  28016. function EdgesHelper( object, hex ) {
  28017. console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
  28018. return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  28019. }
  28020. GridHelper.prototype.setColors = function () {
  28021. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  28022. };
  28023. SkeletonHelper.prototype.update = function () {
  28024. console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' );
  28025. };
  28026. function WireframeHelper( object, hex ) {
  28027. console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
  28028. return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  28029. }
  28030. //
  28031. Loader.prototype.extractUrlBase = function ( url ) {
  28032. console.warn( 'THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.' );
  28033. return LoaderUtils.extractUrlBase( url );
  28034. };
  28035. Loader.Handlers = {
  28036. add: function ( /* regex, loader */ ) {
  28037. console.error( 'THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.' );
  28038. },
  28039. get: function ( /* file */ ) {
  28040. console.error( 'THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.' );
  28041. }
  28042. };
  28043. function XHRLoader( manager ) {
  28044. console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
  28045. return new FileLoader( manager );
  28046. }
  28047. function BinaryTextureLoader( manager ) {
  28048. console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' );
  28049. return new DataTextureLoader( manager );
  28050. }
  28051. //
  28052. Box2.prototype.center = function ( optionalTarget ) {
  28053. console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
  28054. return this.getCenter( optionalTarget );
  28055. };
  28056. Box2.prototype.empty = function () {
  28057. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  28058. return this.isEmpty();
  28059. };
  28060. Box2.prototype.isIntersectionBox = function ( box ) {
  28061. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  28062. return this.intersectsBox( box );
  28063. };
  28064. Box2.prototype.size = function ( optionalTarget ) {
  28065. console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
  28066. return this.getSize( optionalTarget );
  28067. };
  28068. //
  28069. Box3.prototype.center = function ( optionalTarget ) {
  28070. console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
  28071. return this.getCenter( optionalTarget );
  28072. };
  28073. Box3.prototype.empty = function () {
  28074. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  28075. return this.isEmpty();
  28076. };
  28077. Box3.prototype.isIntersectionBox = function ( box ) {
  28078. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  28079. return this.intersectsBox( box );
  28080. };
  28081. Box3.prototype.isIntersectionSphere = function ( sphere ) {
  28082. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  28083. return this.intersectsSphere( sphere );
  28084. };
  28085. Box3.prototype.size = function ( optionalTarget ) {
  28086. console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
  28087. return this.getSize( optionalTarget );
  28088. };
  28089. //
  28090. Sphere.prototype.empty = function () {
  28091. console.warn( 'THREE.Sphere: .empty() has been renamed to .isEmpty().' );
  28092. return this.isEmpty();
  28093. };
  28094. //
  28095. Frustum.prototype.setFromMatrix = function ( m ) {
  28096. console.warn( 'THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().' );
  28097. return this.setFromProjectionMatrix( m );
  28098. };
  28099. //
  28100. Line3.prototype.center = function ( optionalTarget ) {
  28101. console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
  28102. return this.getCenter( optionalTarget );
  28103. };
  28104. //
  28105. MathUtils.random16 = function () {
  28106. console.warn( 'THREE.Math: .random16() has been deprecated. Use Math.random() instead.' );
  28107. return Math.random();
  28108. };
  28109. MathUtils.nearestPowerOfTwo = function ( value ) {
  28110. console.warn( 'THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().' );
  28111. return MathUtils.floorPowerOfTwo( value );
  28112. };
  28113. MathUtils.nextPowerOfTwo = function ( value ) {
  28114. console.warn( 'THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().' );
  28115. return MathUtils.ceilPowerOfTwo( value );
  28116. };
  28117. //
  28118. Matrix3.prototype.flattenToArrayOffset = function ( array, offset ) {
  28119. console.warn( 'THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.' );
  28120. return this.toArray( array, offset );
  28121. };
  28122. Matrix3.prototype.multiplyVector3 = function ( vector ) {
  28123. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  28124. return vector.applyMatrix3( this );
  28125. };
  28126. Matrix3.prototype.multiplyVector3Array = function ( /* a */ ) {
  28127. console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' );
  28128. };
  28129. Matrix3.prototype.applyToBufferAttribute = function ( attribute ) {
  28130. console.warn( 'THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.' );
  28131. return attribute.applyMatrix3( this );
  28132. };
  28133. Matrix3.prototype.applyToVector3Array = function ( /* array, offset, length */ ) {
  28134. console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' );
  28135. };
  28136. Matrix3.prototype.getInverse = function ( matrix ) {
  28137. console.warn( 'THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.' );
  28138. return this.copy( matrix ).invert();
  28139. };
  28140. //
  28141. Matrix4.prototype.extractPosition = function ( m ) {
  28142. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  28143. return this.copyPosition( m );
  28144. };
  28145. Matrix4.prototype.flattenToArrayOffset = function ( array, offset ) {
  28146. console.warn( 'THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.' );
  28147. return this.toArray( array, offset );
  28148. };
  28149. Matrix4.prototype.getPosition = function () {
  28150. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  28151. return new Vector3().setFromMatrixColumn( this, 3 );
  28152. };
  28153. Matrix4.prototype.setRotationFromQuaternion = function ( q ) {
  28154. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  28155. return this.makeRotationFromQuaternion( q );
  28156. };
  28157. Matrix4.prototype.multiplyToArray = function () {
  28158. console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' );
  28159. };
  28160. Matrix4.prototype.multiplyVector3 = function ( vector ) {
  28161. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  28162. return vector.applyMatrix4( this );
  28163. };
  28164. Matrix4.prototype.multiplyVector4 = function ( vector ) {
  28165. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  28166. return vector.applyMatrix4( this );
  28167. };
  28168. Matrix4.prototype.multiplyVector3Array = function ( /* a */ ) {
  28169. console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' );
  28170. };
  28171. Matrix4.prototype.rotateAxis = function ( v ) {
  28172. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  28173. v.transformDirection( this );
  28174. };
  28175. Matrix4.prototype.crossVector = function ( vector ) {
  28176. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  28177. return vector.applyMatrix4( this );
  28178. };
  28179. Matrix4.prototype.translate = function () {
  28180. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  28181. };
  28182. Matrix4.prototype.rotateX = function () {
  28183. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  28184. };
  28185. Matrix4.prototype.rotateY = function () {
  28186. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  28187. };
  28188. Matrix4.prototype.rotateZ = function () {
  28189. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  28190. };
  28191. Matrix4.prototype.rotateByAxis = function () {
  28192. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  28193. };
  28194. Matrix4.prototype.applyToBufferAttribute = function ( attribute ) {
  28195. console.warn( 'THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.' );
  28196. return attribute.applyMatrix4( this );
  28197. };
  28198. Matrix4.prototype.applyToVector3Array = function ( /* array, offset, length */ ) {
  28199. console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' );
  28200. };
  28201. Matrix4.prototype.makeFrustum = function ( left, right, bottom, top, near, far ) {
  28202. console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' );
  28203. return this.makePerspective( left, right, top, bottom, near, far );
  28204. };
  28205. Matrix4.prototype.getInverse = function ( matrix ) {
  28206. console.warn( 'THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.' );
  28207. return this.copy( matrix ).invert();
  28208. };
  28209. //
  28210. Plane.prototype.isIntersectionLine = function ( line ) {
  28211. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  28212. return this.intersectsLine( line );
  28213. };
  28214. //
  28215. Quaternion.prototype.multiplyVector3 = function ( vector ) {
  28216. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  28217. return vector.applyQuaternion( this );
  28218. };
  28219. Quaternion.prototype.inverse = function ( ) {
  28220. console.warn( 'THREE.Quaternion: .inverse() has been renamed to invert().' );
  28221. return this.invert();
  28222. };
  28223. //
  28224. Ray.prototype.isIntersectionBox = function ( box ) {
  28225. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  28226. return this.intersectsBox( box );
  28227. };
  28228. Ray.prototype.isIntersectionPlane = function ( plane ) {
  28229. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  28230. return this.intersectsPlane( plane );
  28231. };
  28232. Ray.prototype.isIntersectionSphere = function ( sphere ) {
  28233. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  28234. return this.intersectsSphere( sphere );
  28235. };
  28236. //
  28237. Triangle.prototype.area = function () {
  28238. console.warn( 'THREE.Triangle: .area() has been renamed to .getArea().' );
  28239. return this.getArea();
  28240. };
  28241. Triangle.prototype.barycoordFromPoint = function ( point, target ) {
  28242. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  28243. return this.getBarycoord( point, target );
  28244. };
  28245. Triangle.prototype.midpoint = function ( target ) {
  28246. console.warn( 'THREE.Triangle: .midpoint() has been renamed to .getMidpoint().' );
  28247. return this.getMidpoint( target );
  28248. };
  28249. Triangle.prototypenormal = function ( target ) {
  28250. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  28251. return this.getNormal( target );
  28252. };
  28253. Triangle.prototype.plane = function ( target ) {
  28254. console.warn( 'THREE.Triangle: .plane() has been renamed to .getPlane().' );
  28255. return this.getPlane( target );
  28256. };
  28257. Triangle.barycoordFromPoint = function ( point, a, b, c, target ) {
  28258. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  28259. return Triangle.getBarycoord( point, a, b, c, target );
  28260. };
  28261. Triangle.normal = function ( a, b, c, target ) {
  28262. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  28263. return Triangle.getNormal( a, b, c, target );
  28264. };
  28265. //
  28266. Shape.prototype.extractAllPoints = function ( divisions ) {
  28267. console.warn( 'THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.' );
  28268. return this.extractPoints( divisions );
  28269. };
  28270. Shape.prototype.extrude = function ( options ) {
  28271. console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
  28272. return new ExtrudeGeometry( this, options );
  28273. };
  28274. Shape.prototype.makeGeometry = function ( options ) {
  28275. console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
  28276. return new ShapeGeometry( this, options );
  28277. };
  28278. //
  28279. Vector2.prototype.fromAttribute = function ( attribute, index, offset ) {
  28280. console.warn( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  28281. return this.fromBufferAttribute( attribute, index, offset );
  28282. };
  28283. Vector2.prototype.distanceToManhattan = function ( v ) {
  28284. console.warn( 'THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  28285. return this.manhattanDistanceTo( v );
  28286. };
  28287. Vector2.prototype.lengthManhattan = function () {
  28288. console.warn( 'THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().' );
  28289. return this.manhattanLength();
  28290. };
  28291. //
  28292. Vector3.prototype.setEulerFromRotationMatrix = function () {
  28293. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  28294. };
  28295. Vector3.prototype.setEulerFromQuaternion = function () {
  28296. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  28297. };
  28298. Vector3.prototype.getPositionFromMatrix = function ( m ) {
  28299. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  28300. return this.setFromMatrixPosition( m );
  28301. };
  28302. Vector3.prototype.getScaleFromMatrix = function ( m ) {
  28303. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  28304. return this.setFromMatrixScale( m );
  28305. };
  28306. Vector3.prototype.getColumnFromMatrix = function ( index, matrix ) {
  28307. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  28308. return this.setFromMatrixColumn( matrix, index );
  28309. };
  28310. Vector3.prototype.applyProjection = function ( m ) {
  28311. console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' );
  28312. return this.applyMatrix4( m );
  28313. };
  28314. Vector3.prototype.fromAttribute = function ( attribute, index, offset ) {
  28315. console.warn( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  28316. return this.fromBufferAttribute( attribute, index, offset );
  28317. };
  28318. Vector3.prototype.distanceToManhattan = function ( v ) {
  28319. console.warn( 'THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  28320. return this.manhattanDistanceTo( v );
  28321. };
  28322. Vector3.prototype.lengthManhattan = function () {
  28323. console.warn( 'THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().' );
  28324. return this.manhattanLength();
  28325. };
  28326. //
  28327. Vector4.prototype.fromAttribute = function ( attribute, index, offset ) {
  28328. console.warn( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  28329. return this.fromBufferAttribute( attribute, index, offset );
  28330. };
  28331. Vector4.prototype.lengthManhattan = function () {
  28332. console.warn( 'THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().' );
  28333. return this.manhattanLength();
  28334. };
  28335. //
  28336. Object3D.prototype.getChildByName = function ( name ) {
  28337. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  28338. return this.getObjectByName( name );
  28339. };
  28340. Object3D.prototype.renderDepth = function () {
  28341. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  28342. };
  28343. Object3D.prototype.translate = function ( distance, axis ) {
  28344. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  28345. return this.translateOnAxis( axis, distance );
  28346. };
  28347. Object3D.prototype.getWorldRotation = function () {
  28348. console.error( 'THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.' );
  28349. };
  28350. Object3D.prototype.applyMatrix = function ( matrix ) {
  28351. console.warn( 'THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().' );
  28352. return this.applyMatrix4( matrix );
  28353. };
  28354. Object.defineProperties( Object3D.prototype, {
  28355. eulerOrder: {
  28356. get: function () {
  28357. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  28358. return this.rotation.order;
  28359. },
  28360. set: function ( value ) {
  28361. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  28362. this.rotation.order = value;
  28363. }
  28364. },
  28365. useQuaternion: {
  28366. get: function () {
  28367. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  28368. },
  28369. set: function () {
  28370. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  28371. }
  28372. }
  28373. } );
  28374. Mesh.prototype.setDrawMode = function () {
  28375. console.error( 'THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' );
  28376. };
  28377. Object.defineProperties( Mesh.prototype, {
  28378. drawMode: {
  28379. get: function () {
  28380. console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.' );
  28381. return TrianglesDrawMode;
  28382. },
  28383. set: function () {
  28384. console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' );
  28385. }
  28386. }
  28387. } );
  28388. Object.defineProperties( LOD.prototype, {
  28389. objects: {
  28390. get: function () {
  28391. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  28392. return this.levels;
  28393. }
  28394. }
  28395. } );
  28396. Object.defineProperty( Skeleton.prototype, 'useVertexTexture', {
  28397. get: function () {
  28398. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  28399. },
  28400. set: function () {
  28401. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  28402. }
  28403. } );
  28404. SkinnedMesh.prototype.initBones = function () {
  28405. console.error( 'THREE.SkinnedMesh: initBones() has been removed.' );
  28406. };
  28407. Object.defineProperty( Curve.prototype, '__arcLengthDivisions', {
  28408. get: function () {
  28409. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  28410. return this.arcLengthDivisions;
  28411. },
  28412. set: function ( value ) {
  28413. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  28414. this.arcLengthDivisions = value;
  28415. }
  28416. } );
  28417. //
  28418. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  28419. console.warn( 'THREE.PerspectiveCamera.setLens is deprecated. ' +
  28420. 'Use .setFocalLength and .filmGauge for a photographic setup.' );
  28421. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  28422. this.setFocalLength( focalLength );
  28423. };
  28424. //
  28425. Object.defineProperties( Light.prototype, {
  28426. onlyShadow: {
  28427. set: function () {
  28428. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  28429. }
  28430. },
  28431. shadowCameraFov: {
  28432. set: function ( value ) {
  28433. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  28434. this.shadow.camera.fov = value;
  28435. }
  28436. },
  28437. shadowCameraLeft: {
  28438. set: function ( value ) {
  28439. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  28440. this.shadow.camera.left = value;
  28441. }
  28442. },
  28443. shadowCameraRight: {
  28444. set: function ( value ) {
  28445. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  28446. this.shadow.camera.right = value;
  28447. }
  28448. },
  28449. shadowCameraTop: {
  28450. set: function ( value ) {
  28451. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  28452. this.shadow.camera.top = value;
  28453. }
  28454. },
  28455. shadowCameraBottom: {
  28456. set: function ( value ) {
  28457. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  28458. this.shadow.camera.bottom = value;
  28459. }
  28460. },
  28461. shadowCameraNear: {
  28462. set: function ( value ) {
  28463. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  28464. this.shadow.camera.near = value;
  28465. }
  28466. },
  28467. shadowCameraFar: {
  28468. set: function ( value ) {
  28469. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  28470. this.shadow.camera.far = value;
  28471. }
  28472. },
  28473. shadowCameraVisible: {
  28474. set: function () {
  28475. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  28476. }
  28477. },
  28478. shadowBias: {
  28479. set: function ( value ) {
  28480. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  28481. this.shadow.bias = value;
  28482. }
  28483. },
  28484. shadowDarkness: {
  28485. set: function () {
  28486. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  28487. }
  28488. },
  28489. shadowMapWidth: {
  28490. set: function ( value ) {
  28491. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  28492. this.shadow.mapSize.width = value;
  28493. }
  28494. },
  28495. shadowMapHeight: {
  28496. set: function ( value ) {
  28497. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  28498. this.shadow.mapSize.height = value;
  28499. }
  28500. }
  28501. } );
  28502. //
  28503. Object.defineProperties( BufferAttribute.prototype, {
  28504. length: {
  28505. get: function () {
  28506. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
  28507. return this.array.length;
  28508. }
  28509. },
  28510. dynamic: {
  28511. get: function () {
  28512. console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' );
  28513. return this.usage === DynamicDrawUsage;
  28514. },
  28515. set: function ( /* value */ ) {
  28516. console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' );
  28517. this.setUsage( DynamicDrawUsage );
  28518. }
  28519. }
  28520. } );
  28521. BufferAttribute.prototype.setDynamic = function ( value ) {
  28522. console.warn( 'THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.' );
  28523. this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage );
  28524. return this;
  28525. };
  28526. BufferAttribute.prototype.copyIndicesArray = function ( /* indices */ ) {
  28527. console.error( 'THREE.BufferAttribute: .copyIndicesArray() has been removed.' );
  28528. },
  28529. BufferAttribute.prototype.setArray = function ( /* array */ ) {
  28530. console.error( 'THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );
  28531. };
  28532. //
  28533. BufferGeometry.prototype.addIndex = function ( index ) {
  28534. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  28535. this.setIndex( index );
  28536. };
  28537. BufferGeometry.prototype.addAttribute = function ( name, attribute ) {
  28538. console.warn( 'THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().' );
  28539. if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) {
  28540. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  28541. return this.setAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  28542. }
  28543. if ( name === 'index' ) {
  28544. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  28545. this.setIndex( attribute );
  28546. return this;
  28547. }
  28548. return this.setAttribute( name, attribute );
  28549. };
  28550. BufferGeometry.prototype.addDrawCall = function ( start, count, indexOffset ) {
  28551. if ( indexOffset !== undefined ) {
  28552. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  28553. }
  28554. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  28555. this.addGroup( start, count );
  28556. };
  28557. BufferGeometry.prototype.clearDrawCalls = function () {
  28558. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  28559. this.clearGroups();
  28560. };
  28561. BufferGeometry.prototype.computeOffsets = function () {
  28562. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  28563. };
  28564. BufferGeometry.prototype.removeAttribute = function ( name ) {
  28565. console.warn( 'THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().' );
  28566. return this.deleteAttribute( name );
  28567. };
  28568. BufferGeometry.prototype.applyMatrix = function ( matrix ) {
  28569. console.warn( 'THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().' );
  28570. return this.applyMatrix4( matrix );
  28571. };
  28572. Object.defineProperties( BufferGeometry.prototype, {
  28573. drawcalls: {
  28574. get: function () {
  28575. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  28576. return this.groups;
  28577. }
  28578. },
  28579. offsets: {
  28580. get: function () {
  28581. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  28582. return this.groups;
  28583. }
  28584. }
  28585. } );
  28586. Object.defineProperties( InstancedBufferGeometry.prototype, {
  28587. maxInstancedCount: {
  28588. get: function () {
  28589. console.warn( 'THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount.' );
  28590. return this.instanceCount;
  28591. },
  28592. set: function ( value ) {
  28593. console.warn( 'THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount.' );
  28594. this.instanceCount = value;
  28595. }
  28596. }
  28597. } );
  28598. Object.defineProperties( Raycaster.prototype, {
  28599. linePrecision: {
  28600. get: function () {
  28601. console.warn( 'THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.' );
  28602. return this.params.Line.threshold;
  28603. },
  28604. set: function ( value ) {
  28605. console.warn( 'THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.' );
  28606. this.params.Line.threshold = value;
  28607. }
  28608. }
  28609. } );
  28610. Object.defineProperties( InterleavedBuffer.prototype, {
  28611. dynamic: {
  28612. get: function () {
  28613. console.warn( 'THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.' );
  28614. return this.usage === DynamicDrawUsage;
  28615. },
  28616. set: function ( value ) {
  28617. console.warn( 'THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.' );
  28618. this.setUsage( value );
  28619. }
  28620. }
  28621. } );
  28622. InterleavedBuffer.prototype.setDynamic = function ( value ) {
  28623. console.warn( 'THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.' );
  28624. this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage );
  28625. return this;
  28626. };
  28627. InterleavedBuffer.prototype.setArray = function ( /* array */ ) {
  28628. console.error( 'THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );
  28629. };
  28630. //
  28631. ExtrudeGeometry.prototype.getArrays = function () {
  28632. console.error( 'THREE.ExtrudeGeometry: .getArrays() has been removed.' );
  28633. };
  28634. ExtrudeGeometry.prototype.addShapeList = function () {
  28635. console.error( 'THREE.ExtrudeGeometry: .addShapeList() has been removed.' );
  28636. };
  28637. ExtrudeGeometry.prototype.addShape = function () {
  28638. console.error( 'THREE.ExtrudeGeometry: .addShape() has been removed.' );
  28639. };
  28640. //
  28641. Scene.prototype.dispose = function () {
  28642. console.error( 'THREE.Scene: .dispose() has been removed.' );
  28643. };
  28644. //
  28645. Object.defineProperties( Uniform.prototype, {
  28646. dynamic: {
  28647. set: function () {
  28648. console.warn( 'THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.' );
  28649. }
  28650. },
  28651. onUpdate: {
  28652. value: function () {
  28653. console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
  28654. return this;
  28655. }
  28656. }
  28657. } );
  28658. //
  28659. Object.defineProperties( Material.prototype, {
  28660. wrapAround: {
  28661. get: function () {
  28662. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  28663. },
  28664. set: function () {
  28665. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  28666. }
  28667. },
  28668. overdraw: {
  28669. get: function () {
  28670. console.warn( 'THREE.Material: .overdraw has been removed.' );
  28671. },
  28672. set: function () {
  28673. console.warn( 'THREE.Material: .overdraw has been removed.' );
  28674. }
  28675. },
  28676. wrapRGB: {
  28677. get: function () {
  28678. console.warn( 'THREE.Material: .wrapRGB has been removed.' );
  28679. return new Color();
  28680. }
  28681. },
  28682. shading: {
  28683. get: function () {
  28684. console.error( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  28685. },
  28686. set: function ( value ) {
  28687. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  28688. this.flatShading = ( value === FlatShading );
  28689. }
  28690. },
  28691. stencilMask: {
  28692. get: function () {
  28693. console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
  28694. return this.stencilFuncMask;
  28695. },
  28696. set: function ( value ) {
  28697. console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
  28698. this.stencilFuncMask = value;
  28699. }
  28700. }
  28701. } );
  28702. Object.defineProperties( MeshPhongMaterial.prototype, {
  28703. metal: {
  28704. get: function () {
  28705. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
  28706. return false;
  28707. },
  28708. set: function () {
  28709. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
  28710. }
  28711. }
  28712. } );
  28713. Object.defineProperties( MeshPhysicalMaterial.prototype, {
  28714. transparency: {
  28715. get: function () {
  28716. console.warn( 'THREE.MeshPhysicalMaterial: .transparency has been renamed to .transmission.' );
  28717. return this.transmission;
  28718. },
  28719. set: function ( value ) {
  28720. console.warn( 'THREE.MeshPhysicalMaterial: .transparency has been renamed to .transmission.' );
  28721. this.transmission = value;
  28722. }
  28723. }
  28724. } );
  28725. Object.defineProperties( ShaderMaterial.prototype, {
  28726. derivatives: {
  28727. get: function () {
  28728. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  28729. return this.extensions.derivatives;
  28730. },
  28731. set: function ( value ) {
  28732. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  28733. this.extensions.derivatives = value;
  28734. }
  28735. }
  28736. } );
  28737. //
  28738. WebGLRenderer.prototype.clearTarget = function ( renderTarget, color, depth, stencil ) {
  28739. console.warn( 'THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.' );
  28740. this.setRenderTarget( renderTarget );
  28741. this.clear( color, depth, stencil );
  28742. };
  28743. WebGLRenderer.prototype.animate = function ( callback ) {
  28744. console.warn( 'THREE.WebGLRenderer: .animate() is now .setAnimationLoop().' );
  28745. this.setAnimationLoop( callback );
  28746. };
  28747. WebGLRenderer.prototype.getCurrentRenderTarget = function () {
  28748. console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' );
  28749. return this.getRenderTarget();
  28750. };
  28751. WebGLRenderer.prototype.getMaxAnisotropy = function () {
  28752. console.warn( 'THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().' );
  28753. return this.capabilities.getMaxAnisotropy();
  28754. };
  28755. WebGLRenderer.prototype.getPrecision = function () {
  28756. console.warn( 'THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.' );
  28757. return this.capabilities.precision;
  28758. };
  28759. WebGLRenderer.prototype.resetGLState = function () {
  28760. console.warn( 'THREE.WebGLRenderer: .resetGLState() is now .state.reset().' );
  28761. return this.state.reset();
  28762. };
  28763. WebGLRenderer.prototype.supportsFloatTextures = function () {
  28764. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  28765. return this.extensions.get( 'OES_texture_float' );
  28766. };
  28767. WebGLRenderer.prototype.supportsHalfFloatTextures = function () {
  28768. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  28769. return this.extensions.get( 'OES_texture_half_float' );
  28770. };
  28771. WebGLRenderer.prototype.supportsStandardDerivatives = function () {
  28772. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  28773. return this.extensions.get( 'OES_standard_derivatives' );
  28774. };
  28775. WebGLRenderer.prototype.supportsCompressedTextureS3TC = function () {
  28776. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  28777. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  28778. };
  28779. WebGLRenderer.prototype.supportsCompressedTexturePVRTC = function () {
  28780. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  28781. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  28782. };
  28783. WebGLRenderer.prototype.supportsBlendMinMax = function () {
  28784. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  28785. return this.extensions.get( 'EXT_blend_minmax' );
  28786. };
  28787. WebGLRenderer.prototype.supportsVertexTextures = function () {
  28788. console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
  28789. return this.capabilities.vertexTextures;
  28790. };
  28791. WebGLRenderer.prototype.supportsInstancedArrays = function () {
  28792. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  28793. return this.extensions.get( 'ANGLE_instanced_arrays' );
  28794. };
  28795. WebGLRenderer.prototype.enableScissorTest = function ( boolean ) {
  28796. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  28797. this.setScissorTest( boolean );
  28798. };
  28799. WebGLRenderer.prototype.initMaterial = function () {
  28800. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  28801. };
  28802. WebGLRenderer.prototype.addPrePlugin = function () {
  28803. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  28804. };
  28805. WebGLRenderer.prototype.addPostPlugin = function () {
  28806. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  28807. };
  28808. WebGLRenderer.prototype.updateShadowMap = function () {
  28809. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  28810. };
  28811. WebGLRenderer.prototype.setFaceCulling = function () {
  28812. console.warn( 'THREE.WebGLRenderer: .setFaceCulling() has been removed.' );
  28813. };
  28814. WebGLRenderer.prototype.allocTextureUnit = function () {
  28815. console.warn( 'THREE.WebGLRenderer: .allocTextureUnit() has been removed.' );
  28816. };
  28817. WebGLRenderer.prototype.setTexture = function () {
  28818. console.warn( 'THREE.WebGLRenderer: .setTexture() has been removed.' );
  28819. };
  28820. WebGLRenderer.prototype.setTexture2D = function () {
  28821. console.warn( 'THREE.WebGLRenderer: .setTexture2D() has been removed.' );
  28822. };
  28823. WebGLRenderer.prototype.setTextureCube = function () {
  28824. console.warn( 'THREE.WebGLRenderer: .setTextureCube() has been removed.' );
  28825. };
  28826. WebGLRenderer.prototype.getActiveMipMapLevel = function () {
  28827. console.warn( 'THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().' );
  28828. return this.getActiveMipmapLevel();
  28829. };
  28830. Object.defineProperties( WebGLRenderer.prototype, {
  28831. shadowMapEnabled: {
  28832. get: function () {
  28833. return this.shadowMap.enabled;
  28834. },
  28835. set: function ( value ) {
  28836. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  28837. this.shadowMap.enabled = value;
  28838. }
  28839. },
  28840. shadowMapType: {
  28841. get: function () {
  28842. return this.shadowMap.type;
  28843. },
  28844. set: function ( value ) {
  28845. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  28846. this.shadowMap.type = value;
  28847. }
  28848. },
  28849. shadowMapCullFace: {
  28850. get: function () {
  28851. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  28852. return undefined;
  28853. },
  28854. set: function ( /* value */ ) {
  28855. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  28856. }
  28857. },
  28858. context: {
  28859. get: function () {
  28860. console.warn( 'THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.' );
  28861. return this.getContext();
  28862. }
  28863. },
  28864. vr: {
  28865. get: function () {
  28866. console.warn( 'THREE.WebGLRenderer: .vr has been renamed to .xr' );
  28867. return this.xr;
  28868. }
  28869. },
  28870. gammaInput: {
  28871. get: function () {
  28872. console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' );
  28873. return false;
  28874. },
  28875. set: function () {
  28876. console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' );
  28877. }
  28878. },
  28879. gammaOutput: {
  28880. get: function () {
  28881. console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' );
  28882. return false;
  28883. },
  28884. set: function ( value ) {
  28885. console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' );
  28886. this.outputEncoding = ( value === true ) ? sRGBEncoding : LinearEncoding;
  28887. }
  28888. },
  28889. toneMappingWhitePoint: {
  28890. get: function () {
  28891. console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' );
  28892. return 1.0;
  28893. },
  28894. set: function () {
  28895. console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' );
  28896. }
  28897. },
  28898. } );
  28899. Object.defineProperties( WebGLShadowMap.prototype, {
  28900. cullFace: {
  28901. get: function () {
  28902. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  28903. return undefined;
  28904. },
  28905. set: function ( /* cullFace */ ) {
  28906. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  28907. }
  28908. },
  28909. renderReverseSided: {
  28910. get: function () {
  28911. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  28912. return undefined;
  28913. },
  28914. set: function () {
  28915. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  28916. }
  28917. },
  28918. renderSingleSided: {
  28919. get: function () {
  28920. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  28921. return undefined;
  28922. },
  28923. set: function () {
  28924. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  28925. }
  28926. }
  28927. } );
  28928. function WebGLRenderTargetCube( width, height, options ) {
  28929. console.warn( 'THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).' );
  28930. return new WebGLCubeRenderTarget( width, options );
  28931. }
  28932. //
  28933. Object.defineProperties( WebGLRenderTarget.prototype, {
  28934. wrapS: {
  28935. get: function () {
  28936. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  28937. return this.texture.wrapS;
  28938. },
  28939. set: function ( value ) {
  28940. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  28941. this.texture.wrapS = value;
  28942. }
  28943. },
  28944. wrapT: {
  28945. get: function () {
  28946. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  28947. return this.texture.wrapT;
  28948. },
  28949. set: function ( value ) {
  28950. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  28951. this.texture.wrapT = value;
  28952. }
  28953. },
  28954. magFilter: {
  28955. get: function () {
  28956. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  28957. return this.texture.magFilter;
  28958. },
  28959. set: function ( value ) {
  28960. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  28961. this.texture.magFilter = value;
  28962. }
  28963. },
  28964. minFilter: {
  28965. get: function () {
  28966. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  28967. return this.texture.minFilter;
  28968. },
  28969. set: function ( value ) {
  28970. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  28971. this.texture.minFilter = value;
  28972. }
  28973. },
  28974. anisotropy: {
  28975. get: function () {
  28976. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  28977. return this.texture.anisotropy;
  28978. },
  28979. set: function ( value ) {
  28980. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  28981. this.texture.anisotropy = value;
  28982. }
  28983. },
  28984. offset: {
  28985. get: function () {
  28986. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  28987. return this.texture.offset;
  28988. },
  28989. set: function ( value ) {
  28990. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  28991. this.texture.offset = value;
  28992. }
  28993. },
  28994. repeat: {
  28995. get: function () {
  28996. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  28997. return this.texture.repeat;
  28998. },
  28999. set: function ( value ) {
  29000. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  29001. this.texture.repeat = value;
  29002. }
  29003. },
  29004. format: {
  29005. get: function () {
  29006. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  29007. return this.texture.format;
  29008. },
  29009. set: function ( value ) {
  29010. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  29011. this.texture.format = value;
  29012. }
  29013. },
  29014. type: {
  29015. get: function () {
  29016. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  29017. return this.texture.type;
  29018. },
  29019. set: function ( value ) {
  29020. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  29021. this.texture.type = value;
  29022. }
  29023. },
  29024. generateMipmaps: {
  29025. get: function () {
  29026. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  29027. return this.texture.generateMipmaps;
  29028. },
  29029. set: function ( value ) {
  29030. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  29031. this.texture.generateMipmaps = value;
  29032. }
  29033. }
  29034. } );
  29035. //
  29036. Object.defineProperties( Audio.prototype, {
  29037. load: {
  29038. value: function ( file ) {
  29039. console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
  29040. const scope = this;
  29041. const audioLoader = new AudioLoader();
  29042. audioLoader.load( file, function ( buffer ) {
  29043. scope.setBuffer( buffer );
  29044. } );
  29045. return this;
  29046. }
  29047. },
  29048. startTime: {
  29049. set: function () {
  29050. console.warn( 'THREE.Audio: .startTime is now .play( delay ).' );
  29051. }
  29052. }
  29053. } );
  29054. AudioAnalyser.prototype.getData = function () {
  29055. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  29056. return this.getFrequencyData();
  29057. };
  29058. //
  29059. CubeCamera.prototype.updateCubeMap = function ( renderer, scene ) {
  29060. console.warn( 'THREE.CubeCamera: .updateCubeMap() is now .update().' );
  29061. return this.update( renderer, scene );
  29062. };
  29063. CubeCamera.prototype.clear = function ( renderer, color, depth, stencil ) {
  29064. console.warn( 'THREE.CubeCamera: .clear() is now .renderTarget.clear().' );
  29065. return this.renderTarget.clear( renderer, color, depth, stencil );
  29066. };
  29067. ImageUtils.crossOrigin = undefined;
  29068. ImageUtils.loadTexture = function ( url, mapping, onLoad, onError ) {
  29069. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  29070. const loader = new TextureLoader();
  29071. loader.setCrossOrigin( this.crossOrigin );
  29072. const texture = loader.load( url, onLoad, undefined, onError );
  29073. if ( mapping ) texture.mapping = mapping;
  29074. return texture;
  29075. };
  29076. ImageUtils.loadTextureCube = function ( urls, mapping, onLoad, onError ) {
  29077. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  29078. const loader = new CubeTextureLoader();
  29079. loader.setCrossOrigin( this.crossOrigin );
  29080. const texture = loader.load( urls, onLoad, undefined, onError );
  29081. if ( mapping ) texture.mapping = mapping;
  29082. return texture;
  29083. };
  29084. ImageUtils.loadCompressedTexture = function () {
  29085. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  29086. };
  29087. ImageUtils.loadCompressedTextureCube = function () {
  29088. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  29089. };
  29090. //
  29091. function CanvasRenderer() {
  29092. console.error( 'THREE.CanvasRenderer has been removed' );
  29093. }
  29094. //
  29095. function JSONLoader() {
  29096. console.error( 'THREE.JSONLoader has been removed.' );
  29097. }
  29098. //
  29099. const SceneUtils = {
  29100. createMultiMaterialObject: function ( /* geometry, materials */ ) {
  29101. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  29102. },
  29103. detach: function ( /* child, parent, scene */ ) {
  29104. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  29105. },
  29106. attach: function ( /* child, scene, parent */ ) {
  29107. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  29108. }
  29109. };
  29110. //
  29111. function LensFlare() {
  29112. console.error( 'THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js' );
  29113. }
  29114. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  29115. /* eslint-disable no-undef */
  29116. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  29117. revision: REVISION,
  29118. } } ) );
  29119. /* eslint-enable no-undef */
  29120. }
  29121. if ( typeof window !== 'undefined' ) {
  29122. if ( window.__THREE__ ) {
  29123. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  29124. } else {
  29125. window.__THREE__ = REVISION;
  29126. }
  29127. }
  29128. 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 as ParametricBufferGeometry, 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 as TextBufferGeometry, 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, WebGLMultisampleRenderTarget, WebGLRenderTarget, WebGLRenderTargetCube, WebGLRenderer, WebGLUtils, WireframeGeometry, WireframeHelper, WrapAroundEnding, XHRLoader, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, sRGBEncoding };